code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from __future__ import absolute_import, unicode_literals, print_function, division
from sys import argv
from os import environ, stat, remove as _delete_file
from os.path import isfile, dirname, basename, abspath
from hashlib import sha256
from subprocess import check_call as run
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.exception import S3ResponseError
NEED_TO_UPLOAD_MARKER = '.need-to-upload'
BYTES_PER_MB = 1024 * 1024
try:
BUCKET_NAME = environ['TWBS_S3_BUCKET']
except KeyError:
raise SystemExit("TWBS_S3_BUCKET environment variable not set!")
def _sha256_of_file(filename):
hasher = sha256()
with open(filename, 'rb') as input_file:
hasher.update(input_file.read())
file_hash = hasher.hexdigest()
print('sha256({}) = {}'.format(filename, file_hash))
return file_hash
def _delete_file_quietly(filename):
try:
_delete_file(filename)
except (OSError, IOError):
pass
def _tarball_size(directory):
kib = stat(_tarball_filename_for(directory)).st_size // BYTES_PER_MB
return "{} MiB".format(kib)
def _tarball_filename_for(directory):
return abspath('./{}.tar.gz'.format(basename(directory)))
def _create_tarball(directory):
print("Creating tarball of {}...".format(directory))
run(['tar', '-czf', _tarball_filename_for(directory), '-C', dirname(directory), basename(directory)])
def _extract_tarball(directory):
print("Extracting tarball of {}...".format(directory))
run(['tar', '-xzf', _tarball_filename_for(directory), '-C', dirname(directory)])
def download(directory):
_delete_file_quietly(NEED_TO_UPLOAD_MARKER)
try:
print("Downloading {} tarball from S3...".format(friendly_name))
key.get_contents_to_filename(_tarball_filename_for(directory))
except S3ResponseError as err:
open(NEED_TO_UPLOAD_MARKER, 'a').close()
print(err)
raise SystemExit("Cached {} download failed!".format(friendly_name))
print("Downloaded {}.".format(_tarball_size(directory)))
_extract_tarball(directory)
print("{} successfully installed from cache.".format(friendly_name))
def upload(directory):
_create_tarball(directory)
print("Uploading {} tarball to S3... ({})".format(friendly_name, _tarball_size(directory)))
key.set_contents_from_filename(_tarball_filename_for(directory))
print("{} cache successfully updated.".format(friendly_name))
_delete_file_quietly(NEED_TO_UPLOAD_MARKER)
if __name__ == '__main__':
# Uses environment variables:
# AWS_ACCESS_KEY_ID -- AWS Access Key ID
# AWS_SECRET_ACCESS_KEY -- AWS Secret Access Key
argv.pop(0)
if len(argv) != 4:
raise SystemExit("USAGE: s3_cache.py <download | upload> <friendly name> <dependencies file> <directory>")
mode, friendly_name, dependencies_file, directory = argv
conn = S3Connection()
bucket = conn.lookup(BUCKET_NAME, validate=False)
if bucket is None:
raise SystemExit("Could not access bucket!")
dependencies_file_hash = _sha256_of_file(dependencies_file)
key = Key(bucket, dependencies_file_hash)
key.storage_class = 'REDUCED_REDUNDANCY'
if mode == 'download':
download(directory)
elif mode == 'upload':
if isfile(NEED_TO_UPLOAD_MARKER): # FIXME
upload(directory)
else:
print("No need to upload anything.")
else:
raise SystemExit("Unrecognized mode {!r}".format(mode)) | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap/test-infra/s3_cache.py | s3_cache.py |
# bootstrap-datepicker
This is a fork of Stefan Petre's [original code](http://www.eyecon.ro/bootstrap-datepicker/);
thanks go to him for getting this thing started!
Please note that this fork is not used on Stefan's page, nor is it maintained or contributed to by him.
Versions are incremented according to [semver](http://semver.org/).
## Links
* [Online Demo](http://eternicode.github.io/bootstrap-datepicker/)
* [Online Docs](http://bootstrap-datepicker.readthedocs.org/) (ReadTheDocs.com)
* [Google Group](https://groups.google.com/group/bootstrap-datepicker/)
* [Travis CI ](https://travis-ci.org/eternicode/bootstrap-datepicker)
## Development
Once you cloned the repo, you'll need to install [grunt](http://gruntjs.com/) and the development dependencies using [npm](https://npmjs.org/).
npm install -g grunt-cli
npm install
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/README.md | README.md |
# Contributing
## Support requests
The issue tracker is not the place for support requests. If you get stuck with bootstrap-datepicker, it's very likely that the fine folks at [StackOverflow](http://stackoverflow.com/) will be able to help you; simply describe the problem you're having and provide them a link to the repo (so they know what code you're using). Another option is to post to the [bootstrap-datepicker google group](https://groups.google.com/group/bootstrap-datepicker).
## Issues
If you've found a bug in bootstrap-datepicker, we want to know about it! However, please keep the following in mind:
* This is not the bootstrap-datepicker from [eyecon.ro](http://www.eyecon.ro/bootstrap-datepicker/). Stefan provided the initial code for bootstrap-datepicker, but this repo is divergent from his codebase. Please make sure you're using either the latest tagged version or the latest master from https://github.com/eternicode/bootstrap-datepicker/ .
* A working example of the bug you've found is *much* easier to work with than a description alone. If possible, please provide a link to a demonstration of the bug, perhaps using http://jsfiddle.net/ .
* CDN-backed assets can be found at http://bsdp-assets.blackcherry.us/ . These should be used *only* for building test cases, as they may be removed or changed at any time.
* Finally, it's possible someone else has already reported the same bug you have. Please search the issue tracker for similar issues before posting your own. Thanks!
## Pull Requests
Patches welcome!
For all cases, you should have your own fork of the repo.
To submit a pull request for a **new feature**:
1. Run the tests. Every pull request for a new feature should have an accompanying unit test and docs changes. See the README in the `tests/` and `docs/` directories for details.
2. Create a new branch off of the `master` branch for your feature. This is particularly helpful when you want to submit multiple pull requests.
3. Add a test (or multiple tests) for your feature. Again, see `tests/README.md`.
4. Add your new feature, making the test pass.
5. Push to your fork and submit the pull request!
To submit a **bug fix**:
1. Create a new branch off of the `master` branch.
2. Add a test that demonstrates the bug.
3. Make the test pass.
4. Push to your fork and submit the pull request!
To submit a **documentation fix**:
1. Create a new branch off of the `master` branch.
2. Add your documentation fixes (no tests required).
3. Push to your fork and submit the pull request!
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/CONTRIBUTING.md | CONTRIBUTING.md |
module.exports = function(grunt){
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
qunit: {
all: ['tests/tests.html']
},
jshint: {
options: {
jshintrc: true
},
gruntfile: ['Gruntfile.js'],
main: ['js/bootstrap-datepicker.js'],
locales: ['js/locales/*js']
},
jscs: {
/* grunt-contrib-jscs notes:
0.1.2 works
0.1.3 infinite loops on postinstall
0.1.4 doesn't seem to hit all targets when run via "grunt jscs"
*/
gruntfile: ['Gruntfile.js'],
main: ['js/bootstrap-datepicker.js'],
locales: ['js/locales/*js']
},
less: {
standalone: {
files: {
'_build/datepicker.standalone.css': 'build/build_standalone.less',
'_build/datepicker3.standalone.css': 'build/build_standalone3.less'
}
},
css: {
files: {
'_build/datepicker.css': 'build/build.less',
'_build/datepicker3.css': 'build/build3.less'
}
},
repo: {
files: {
'css/datepicker.css': 'build/build_standalone.less',
'css/datepicker3.css': 'build/build_standalone3.less'
}
}
},
uglify: {
options: {
compress: true,
mangle: true
},
main: {
options: {
sourceMap: function(dest){
return dest.replace('.min.js', '.js.map');
}
},
files: {
'_build/bootstrap-datepicker.min.js': 'js/bootstrap-datepicker.js',
'_build/bootstrap-datepicker.locales.min.js': 'js/locales/*.js'
}
},
locales: {
files: [{
expand: true,
cwd: 'js/locales/',
src: ['*.js', '!*.min.js'],
dest: '_build/locales/',
rename: function(dest, name){
return dest + name.replace(/\.js$/, '.min.js');
}
}]
}
},
cssmin: {
all: {
files: {
'_build/datepicker.standalone.min.css': '_build/datepicker.standalone.css',
'_build/datepicker.min.css': '_build/datepicker.css',
'_build/datepicker3.standalone.min.css': '_build/datepicker3.standalone.css',
'_build/datepicker3.min.css': '_build/datepicker3.css'
}
}
},
clean: ['_build']
});
grunt.registerTask('lint', 'Lint all js files with jshint and jscs', ['jshint', 'jscs']);
grunt.registerTask('test', 'Lint files and run unit tests', ['lint', 'qunit']);
grunt.registerTask('finish', 'Prepares repo for commit [test, less:repo, screenshots]', ['test', 'less:repo', 'screenshots']);
grunt.registerTask('dist', 'Builds minified files', ['less:css', 'less:standalone', 'cssmin', 'uglify']);
grunt.registerTask('screenshots', 'Rebuilds automated docs screenshots', function(){
var phantomjs = require('phantomjs').path;
grunt.file.recurse('docs/_static/screenshots/', function(abspath){
grunt.file.delete(abspath);
});
grunt.file.recurse('docs/_screenshots/', function(abspath, root, subdir, filename){
if (!/.html$/.test(filename))
return;
subdir = subdir || '';
var outdir = "docs/_static/screenshots/" + subdir,
outfile = outdir + filename.replace(/.html$/, '.png');
if (!grunt.file.exists(outdir))
grunt.file.mkdir(outdir);
grunt.util.spawn({
cmd: phantomjs,
args: ['docs/_screenshots/script/screenshot.js', abspath, outfile]
});
});
});
}; | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/Gruntfile.js | Gruntfile.js |
Changelog
=========
1.3.0
-----
New features:
* Bootstrap 3 support. Added build files `build/build_standalone3.less` and `build/build3.less`, and source files `less/datepicker3.less` and `css/datepicker3.css` (built from `build_standalone3.less`).
* Multi-date functionality. This required rethinking several areas of the picker:
* The internals have been modified to be completely multidate-centric.
* Attributes and methods availabel on events have changed, but the old attributes and functions will still work.
* Keyboard navigation has been revamped, as it didn't work at all properly with multidate selection.
* The picker now explicitly supports "no selected date".
Non-API changes:
* Keyboard navigation has been changed. See `docs/keyboard.rst`.
* Empty pickers in a range picker setup will be populated with the first date selected by the user to make finding the next date easier.
Bug squashed:
* Jan 1, 1970 is now highlighted when selected
* `touchstart` added to document-bound picker-closing events (alongside `mousedown`)
* Fixed a display bug with component add-on icons being vertically higher than they should have been.
* Input is refocused after clicking the picker.
* `changeDate` event is triggered when `setDate` is called.
Locale changes:
* Added Ukrainian, Belgium-Dutch, Welsh, Galician, Vietnamese, and Azerbaijani
* `clear` for German, Danish, Italian, and Romanian
* Fixed `weekStart` and `format` for Norwegian
* `weekStart` and `format` for Georgian
* Tweaks for Latvian, French, Vietnamese, Swedish, and Croatian
* De-duplicated Ukrainian files from `uk` and `ua` to just `ua`
Repository changes:
* Documentation has been moved from the base `README.md` file to the `docs/` folder, and been re-written to use sphinx docs. The docs are now viewable online at http://bootstrap-datepicker.readthedocs.org/. The [gh-pages](http://eternicode.github.io/bootstrap-datepicker/) branch has been reduced to the sandbox demo.
* Changed the js file header to point at repo/demo/docs urls instead of eyecon.ro
* The css files are now the output of the standalone build scripts instead of `build/build.less` etc.
* `composer.json` now supports component-installer
* Added [JSHint](http://www.jshint.com/docs/) and [JSCS](https://github.com/mdevils/node-jscs) configurations
1.2.0
-----
New features:
* Google Closure Compiler Compatibility
* Smart orientation by default, and explicit picker orientation with the `orientation` option
* Text inside the picker is no longer user-selectable
* Packagist/Composer support (I think...)
* No longer depends on glyphicons for arrows
* `clearDate` event added, fired when the date is cleared
Bug squashed:
* `noConflict` fixed
* Fix for large years causing an infinite loop in date parsing
* Fixed cases where `changeYear` and `changeMonth` events were not being triggered
* `component.js` moved to `bower.js`
* Falsey values for `startDate` and `endDate` translate to `-Infinity` and `Infinity`, respectively (effectively, falsey values mean "no bounds")
* Fixed `autoclose` for non-input, non-component elements
* Fixed 50% param in `mix()` less function -- expands compatibility with less compilers
* Fixed `update` method to update the selected date
* `beforeShowDay` was getting UTC dates, now it gets local dates (all dates that developers are given should be in local time, not UTC).
* `startDate` and `endDate` were a bit confused when given `new Date()` -- they would not allow today to be selected (the range should be inclusive), they would change whether it was selectable based on local time, etc. These quirks should be fixed now. They both also now expect local dates (which will then be time-zeroed and converted to UTC).
* Fixed selected date not being automatically constrained to the specified range when `setStartDate` and `setEndDate` were called.
* No longer uses jQuery's `.size()` (deprecated in favor of `.length`)
* `changeDate` triggered during manual user input
* `change` event fired when input value changed, it wasn't in some cases
Locale changes:
* Added Arabic, Norwegian, Georgian
* `clear` for French
* `today` and `clear` for Bahasa
* `today` and `clear` for Portuguese (both `pt` and `pt-BR`)
* `format` for Turkish
* `format` and `weekStart` for Swedish
* `format` and `weekStart` for Simplified Chinese; `today`, `format`, and `weekStart` for Traditional Chinese
* Fixed typo in Serbian latin (`rs-latin`)
* More appropriate use of Traditional Chinese habit in `zh-TW`
1.1.3
----------
Clicking the clear button now triggers the input's `change` and datepicker's `changeDate` events.
Fixed a bug that broke the event-attached `format` function.
1.1.2
----------
Botched release, no change from 1.1.1
1.1.1
----------
Fixes a bug when setting startDate or endDate during initialization.
1.1.0
----------
New features:
* Date range picker.
* Data API / noConflict.
* `getDate` and `setDate` methods.
* `format` method for events; this allows you to easily format the `date` associated with the event.
* New options:
* `beforeShowDay` option: a dev-provided function that can enable/disable dates, add css classes, and add tooltips.
* `clearBtn`, a button for resetting the picker.
Internal changes:
* Cleaner and more reliable method for extracting options from all potential sources (defaults, locale overrides, data-attrs, and instantiation options, in that order). This also populates `$.fn.datepicker.defaults` with the default values, and uses this hash as the actual source of defaults, meaning you can globally change the default value for a given option.
Bugs squashed:
* Resolved a conflict with bootstrap's native `.switch` class.
* Fixed a bug with components where they would be stuck with a stale value when editing the value manually.
* The `date` attributes on events are now local dates instead of internal UTC dates.
* Separate `Date` objects for internal selected and view date references.
* Clicking multiple times inside inputs no longer hides the picker.
Minor improvements:
* Better text color for highlighted "today" date.
* Last year in decade view now marked as "new" instead of "old".
* Formats now properly handle trailing separators.
Locale changes:
* Added Albanian, Estonian, and Macedonian
* Added `weekStart` for Russian
* Added `weekStart` and `format` for Finnish
Potentially backward-incompatible changes:
* Options revamp:
* This fixes bugs in the correlation of some data-attrs to their associated option names. If you use `data-date-weekstart`, `data-date-startdate`, or `data-date-enddate`, you should update these to `data-date-week-start`, `data-date-start-date`, or `data-date-end-date`, respectively.
* All options for datepicker are now properties on the datepicker's `o` property; options are no longer stored on the Datepicker instance itself. If you have code that accesses options stored on the datepicker instance (eg, `datepicker.format`), you will need to update it to access those options via the `o` property (eg, `datepicker.o.format`). "Raw" options are available via the `_o` property.
1.0.2
----------
Small optimizations release
* Reduced the number of times `update` is called on initialization.
* Datepicker now detaches the picker dropdown when it is hidden, and appends it when shown. This removes the picker from the DOM when it is not in use.
* No longer listens to document/window events unless picker is visible.
v1.0.1
------
* Support for [Bower](http://twitter.github.com/bower/)
* Component pickers are now aligned under the input, not the add-on element.
* Japanese locale now has "today" and "format".
* "remove" method removes `.data().date` if the datepicker is on a non-input.
* Events on initialized elements are no longer blocked from bubbling up the DOM (jQuery.live et al can now catch the events).
* Component triggers now include `.btn` in addition to `.add-on`.
* Updates to README contents.
v1.0.0
------
Initial release:
* format option
* weekStart option
* calendarWeeks option
* startDate / endDate options
* daysOfWeekDisabled option
* autoclose option
* startView / mnViewMode options
* todayBtn / todayHighlight options
* keyboardNavigation option
* language option
* forceParse option
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/CHANGELOG.md | CHANGELOG.md |
Methods
=======
Methods are called on a datepicker by call the ``datepicker`` function with a string first argument, followed by any arguments the method takes::
$('.datepicker').datepicker('method', arg1, arg2);
remove
------
Arguments: None
Remove the datepicker. Removes attached events, internal attached objects, and added HTML elements.
show
----
Arguments: None
Show the picker.
hide
----
Arguments: None
Hide the picker.
update
------
Arguments:
* date (String|Date, optional)
Update the datepicker with given argument or the current input value.
If ``date`` is provided and is a Date object, it is assumed to be a "local" date object, and will be converted to UTC for internal use.
::
$('.datepicker').datepicker('update');
$('.datepicker').datepicker('update', '2011-03-05');
$('.datepicker').datepicker('update', new Date(2011, 2, 5));
setDate
-------
Arguments:
* date (Date)
Sets the internal date. ``date`` is assumed to be a "local" date object, and will be converted to UTC for internal use.
setUTCDate
----------
Arguments:
* date (Date)
Sets the internal date. ``date`` is assumed to be a UTC date object, and will not be converted.
setDates
--------
Arguments:
* date[, date[, ...]] (Date)
or
* [date[, date[, ...]]] (Array)
Sets the internal date list; accepts multiple dates or a single array of dates as arguments. Each ``date`` is assumed to be a "local" date object, and will be converted to UTC for internal use. For use with multidate pickers.
setUTCDates
-----------
Arguments:
* date[, date[, ...]] (Date)
or
* [date[, date[, ...]]] (Array)
Sets the internal date list. Each ``date`` is assumed to be a UTC date object, and will not be converted. For use with multidate pickers.
getDate
-------
Arguments: None
Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.
getUTCDate
----------
Arguments: None
Returns the internal UTC date object, as-is and unconverted to local time, of the first datepicker in the selection. For multidate pickers, returns the latest date selected.
getDates
--------
Arguments: None
Returns a list of localized date objects representing the internal date objects of the first datepicker in the selection. For use with multidate pickers.
getUTCDates
-----------
Arguments: None
Returns the internal list of UTC date objects, as they are and unconverted to local time, of the first datepicker in the selection. For use with multidate pickers.
setStartDate
------------
Arguments:
* startDate (Date)
Sets a new lower date limit on the datepicker. See :ref:`startdate` for valid values.
Omit startDate (or provide an otherwise falsey value) to unset the limit.
setEndDate
----------
Arguments:
* endDate (Date)
Sets a new upper date limit on the datepicker. See :ref:`enddate` for valid values.
Omit endDate (or provide an otherwise falsey value) to unset the limit.
setDaysOfWeekDisabled
---------------------
Arguments:
* daysOfWeekDisabled (String|Array)
Sets the days of week that should be disabled. See :ref:`daysofweekdisabled` for valid values.
Omit daysOfWeekDisabled (or provide an otherwise falsey value) to unset the disabled days.
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/methods.rst | methods.rst |
bootstrap-datepicker
====================
Bootstrap-datepicker provides a flexible datepicker widget in the Twitter bootstrap style.
.. figure:: _static/screenshots/demo_head.png
:align: center
This is a fork of Stefan Petre's `original code <http://www.eyecon.ro/bootstrap-datepicker/>`_; thanks go to him for getting this thing started!
Please note that this fork is not used on Stefan's page at this time, nor is it maintained or contributed to by him.
Versions are incremented according to `semver <http://semver.org/>`_.
`Online Demo <http://eternicode.github.io/bootstrap-datepicker/>`_
Requirements
------------
* `Bootstrap`_ 2.0.4+
* `jQuery`_ 1.7.1+
.. _Bootstrap: http://twitter.github.com/bootstrap/
.. _jQuery: http://jquery.com/
These are the specific versions bootstrap-datepicker is tested against (``js`` files) and built against (``css`` files). Use other versions at your own risk.
Dependencies
------------
Requires bootstrap's dropdown component (``dropdowns.less``) for some styles, and bootstrap's sprites (``sprites.less`` and associated images) for arrows.
A standalone .css file (including necessary dropdown styles and alternative, text-based arrows) can be generated by running ``build/build_standalone.less`` through the ``lessc`` compiler::
$ lessc build/build_standalone.less datepicker.css
Usage
-----
Call the datepicker via javascript::
$('.datepicker').datepicker()
Data API
^^^^^^^^
As with bootstrap's own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript. For most datepickers, simply set ``data-provide="datepicker"`` on the element you want to initialize, and it will be intialized lazily, in true bootstrap fashion. For inline datepickers, use ``data-provide="datepicker-inline"``; these will be immediately initialized on page load, and cannot be lazily loaded.
.. code-block:: html
<input data-provide="datepicker">
You can disable datepicker's data-api in the same way as you would disable other bootstrap plugins::
$(document).off('.datepicker.data-api');
Configuration
^^^^^^^^^^^^^
:doc:`options` are passed to the ``datepicker`` function via an options hash at instantiation::
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
startDate: '-3d'
})
Most options may be provided as data-attributes on the target element:
.. code-block:: html
<input class="datepicker" data-date-format="mm/dd/yyyy">
::
$('.datepicker').datepicker({
startDate: '-3d'
})
Defaults for all options can be modified directly by changing values in the ``$.fn.datepicker.defaults`` hash::
$.fn.datepicker.defaults.format = "mm/dd/yyyy";
$('.datepicker').datepicker({
startDate: '-3d'
})
No Conflict mode
^^^^^^^^^^^^^^^^
``$.fn.datepicker.noConflict`` provides a way to avoid conflict with other jQuery datepicker plugins::
var datepicker = $.fn.datepicker.noConflict(); // return $.fn.datepicker to previously assigned value
$.fn.bootstrapDP = datepicker; // give $().bootstrapDP the bootstrap-datepicker functionality
Table of Contents
-----------------
.. toctree::
markup
options
methods
events
keyboard
i18n
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/index.rst | index.rst |
Keyboard support
================
The datepicker includes keyboard navigation. The "focused date" is kept track of and highlighted (as with mouse hover) during keyboard nav, and is cleared when a date is toggled or the picker is hidden.
up, down, left, right arrow keys
--------------------------------
By themselves, left/right will move focus backward/forward one day, up/down will move focus back/forward one week.
With the shift key, up/left will move focus backward one month, down/right will move focus forward one month.
With the ctrl key, up/left will move focus backward one year, down/right will move focus forward one year.
Shift+ctrl behaves the same as ctrl -- that is, it does not change both month and year simultaneously, only the year.
enter
-----
When the picker is visible, enter will toggle the focused date (if there is one). When the picker is not visible, enter will have normal effects -- submitting the current form, etc.
When the date is deselected, the ``clearDate`` event is triggered; otherwise, the ``changeDate`` event is triggered. If ``autoclose`` is enabled, the picker will be hidden after selection or deselection.
escape
------
The escape key can be used to clear the focused date and hide and re-show the datepicker; hiding the picker is necessary if the user wants to manually edit the value.
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/keyboard.rst | keyboard.rst |
Documentation
=============
Project documentation is built using [Sphinx docs](http://sphinx-doc.org/), which uses [ReST](http://docutils.sf.net/rst.html) for markup. This allows the docs to cover a vast amount of topics without using a thousand-line README file.
Sphinx docs is pip-installable via `pip install sphinx`. Once installed, open a command line in the docs folder and run `make html`; the output files will be placed in the `_build/html/` directory, and can be browsed (locally) with any browser.
The docs can also be found online at http://bootstrap-datepicker.readthedocs.org/.
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/REAME.md | REAME.md |
Markup
=======
The following are examples of supported markup. On their own, these will not provide a datepicker widget; you will need to instantiate the datepicker on the markup.
input
-----
The simplest case: focusing the input (clicking or tabbing into it) will show the picker.
.. code-block:: html
<input type="text" value="02-16-2012">
.. figure:: _static/screenshots/markup_input.png
:align: center
component
---------
Adding the ``date`` class to an ``input-append`` or ``input-prepend`` bootstrap component will allow the ``add-on`` elements to trigger the picker.
.. code-block:: html
<div class="input-append date">
<input type="text" value="12-02-2012">
<span class="add-on"><i class="icon-th"></i></span>
</div>
.. figure:: _static/screenshots/markup_component.png
:align: center
.. _daterange:
date-range
----------
Using the ``input-daterange`` construct with multiple child inputs will instantiate one picker per input and link them together to allow selecting ranges.
.. code-block:: html
<div class="input-daterange">
<input type="text" class="input-small" value="2012-04-05" />
<span class="add-on">to</span>
<input type="text" class="input-small" value="2012-04-19" />
</div>
.. figure:: _static/screenshots/markup_daterange.png
:align: center
inline or embedded
------------------
Instantiating the datepicker on a simple div will give an embedded picker that is always visible.
.. code-block:: html
<div data-date="12/03/2012"></div>
.. figure:: _static/screenshots/markup_inline.png
:align: center
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/markup.rst | markup.rst |
Options
=======
All options that take a "Date" can handle a ``Date`` object; a String formatted according to the given ``format``; or a timedelta relative to today, eg "-1d", "+6m +1y", etc, where valid units are "d" (day), "w" (week), "m" (month), and "y" (year).
Most options can be provided via data-attributes. An option can be converted to a data-attribute by taking its name, replacing each uppercase letter with its lowercase equivalent preceded by a dash, and prepending "data-date-" to the result. For example, ``startDate`` would be ``data-date-start-date``, ``format`` would be ``data-date-format``, and ``daysOfWeekDisabled`` would be ``data-date-days-of-week-disabled``.
autoclose
---------
Boolean. Default: false
Whether or not to close the datepicker immediately when a date is selected.
beforeShowDay
-------------
Function(Date). Default: $.noop
A function that takes a date as a parameter and returns one of the following values:
* undefined to have no effect
* A Boolean, indicating whether or not this date is selectable
* A String representing additional CSS classes to apply to the date's cell
* An object with the following properties:
* ``enabled``: same as the Boolean value above
* ``classes``: same as the String value above
* ``tooltip``: a tooltip to apply to this date, via the ``title`` HTML attribute
calendarWeeks
-------------
Boolean. Default: false
Whether or not to show week numbers to the left of week rows.
.. figure:: _static/screenshots/option_calendarweeks.png
:align: center
clearBtn
--------
Boolean. Default: false
If true, displays a "Clear" button at the bottom of the datepicker to clear the input value. If "autoclose" is also set to true, this button will also close the datepicker.
.. figure:: _static/screenshots/option_clearbtn.png
:align: center
.. _daysofweekdisabled:
daysOfWeekDisabled
------------------
String, Array. Default: '', []
Days of the week that should be disabled. Values are 0 (Sunday) to 6 (Saturday). Multiple values should be comma-separated. Example: disable weekends: ``'0,6'`` or ``[0,6]``.
.. figure:: _static/screenshots/option_daysofweekdisabled.png
:align: center
.. _enddate:
endDate
-------
Date. Default: End of time
The latest date that may be selected; all later dates will be disabled.
.. figure:: _static/screenshots/option_enddate.png
:align: center
forceParse
----------
Boolean. Default: true
Whether or not to force parsing of the input value when the picker is closed. That is, when an invalid date is left in the input field by the user, the picker will forcibly parse that value, and set the input's value to the new, valid date, conforming to the given `format`.
format
------
String. Default: "mm/dd/yyyy"
The date format, combination of d, dd, D, DD, m, mm, M, MM, yy, yyyy.
* d, dd: Numeric date, no leading zero and leading zero, respectively. Eg, 5, 05.
* D, DD: Abbreviated and full weekday names, respectively. Eg, Mon, Monday.
* m, mm: Numeric month, no leading zero and leading zero, respectively. Eg, 7, 07.
* M, MM: Abbreviated and full month names, respectively. Eg, Jan, January
* yy, yyyy: 2- and 4-digit years, respectively. Eg, 12, 2012.
inputs
------
Array. Default: None
A list of inputs to be used in a range picker, which will be attached to the selected element. Allows for explicitly creating a range picker on a non-standard element.
keyboardNavigation
------------------
Boolean. Default: true
Whether or not to allow date navigation by arrow keys.
language
--------
String. Default: "en"
The IETF code (eg "en" for English, "pt-BR" for Brazilian Portuguese) of the language to use for month and day names. These will also be used as the input's value (and subsequently sent to the server in the case of form submissions). If a full code (eg "de-DE") is supplied the picker will first check for an "de-DE" language and if not found will fallback and check for a "de" language. If an unknown language code is given, English will be used. See :doc:`i18n`.
.. figure:: _static/screenshots/option_language.png
:align: center
minViewMode
-----------
Number, String. Default: 0, "days"
Set a limit for the view mode. Accepts: "days" or 0, "months" or 1, and "years" or 2.
Gives the ability to pick only a month or an year. The day is set to the 1st for "months", and the month is set to January for "years".
multidate
---------
Boolean, Number. Default: false
Enable multidate picking. Each date in month view acts as a toggle button, keeping track of which dates the user has selected in order. If a number is given, the picker will limit how many dates can be selected to that number, dropping the oldest dates from the list when the number is exceeded. ``true`` equates to no limit. The input's value (if present) is set to a string generated by joining the dates, formatted, with ``multidateSeparator``.
For selecting 2 dates as a range please see :ref:`daterange`
.. figure:: _static/screenshots/option_multidate.png
:align: center
multidateSeparator
------------------
String. Default: ","
The string that will appear between dates when generating the input's value. When parsing the input's value for a multidate picker, this will also be used to split the incoming string to separate multiple formatted dates; as such, it is highly recommended that you not use a string that could be a substring of a formatted date (eg, using '-' to separate dates when your format is 'yyyy-mm-dd').
orientation
-----------
String. Default: "auto"
A space-separated string consisting of one or two of "left" or "right", "top" or "bottom", and "auto" (may be omitted); for example, "top left", "bottom" (horizontal orientation will default to "auto"), "right" (vertical orientation will default to "auto"), "auto top". Allows for fixed placement of the picker popup.
"orientation" refers to the location of the picker popup's "anchor"; you can also think of it as the location of the trigger element (input, component, etc) relative to the picker.
"auto" triggers "smart orientation" of the picker. Horizontal orientation will default to "left" and left offset will be tweaked to keep the picker inside the browser viewport; vertical orientation will simply choose "top" or "bottom", whichever will show more of the picker in the viewport.
.. _startdate:
startDate
---------
Date. Default: Beginning of time
The earliest date that may be selected; all earlier dates will be disabled.
.. figure:: _static/screenshots/option_startdate.png
:align: center
startView
---------
Number, String. Default: 0, "month"
The view that the datepicker should show when it is opened. Accepts values of 0 or "month" for month view (the default), 1 or "year" for the 12-month overview, and 2 or "decade" for the 10-year overview. Useful for date-of-birth datepickers.
todayBtn
--------
Boolean, "linked". Default: false
If true or "linked", displays a "Today" button at the bottom of the datepicker to select the current date. If true, the "Today" button will only move the current date into view; if "linked", the current date will also be selected.
.. figure:: _static/screenshots/option_todaybtn.png
:align: center
todayHighlight
--------------
Boolean. Default: false
If true, highlights the current date.
.. figure:: _static/screenshots/option_todayhighlight.png
:align: center
weekStart
---------
Integer. Default: 0
Day of the week start. 0 (Sunday) to 6 (Saturday)
.. figure:: _static/screenshots/option_weekstart.png
:align: center
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/options.rst | options.rst |
I18N
====
The plugin supports i18n for the month and weekday names and the ``weekStart`` option. The default is English ("en"); other available translations are available in the ``js/locales/`` directory, simply include your desired locale after the plugin. To add more languages, simply add a key to ``$.fn.datepicker.dates``, before calling ``.datepicker()``. Example::
$.fn.datepicker.dates['en'] = {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
};
Right-to-left languages may also include ``rtl: true`` to make the calendar display appropriately.
If your browser (or those of your users) is displaying characters wrong, chances are the browser is loading the javascript file with a non-unicode encoding. Simply add ``charset="UTF-8"`` to your ``script`` tag:
.. code-block:: html
<script type="text/javascript" src="bootstrap-datepicker.XX.js" charset="UTF-8"></script>
::
$('.datepicker').datepicker({
language: 'XX'
});
.. figure:: _static/screenshots/option_language.png
:align: center
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/i18n.rst | i18n.rst |
Events
======
Datepicker triggers a number of events in certain circumstances. All events have extra data attached to the event object that is passed to any event handlers::
$('.datepicker').datepicker()
.on(picker_event, function(e){
# `e` here contains the extra attributes
});
* ``date``: the relevant Date object, in local timezone. For a multidate picker, this will be the latest date picked.
* ``dates``: an Array of Date objects, in local timezone, when using a multidate picker.
* ``format([ix], [format])``: a function to make formatting ``date`` easier. ``ix`` can be the index of a Date in the ``dates`` array to format; if absent, the last date selected will be used. ``format`` can be any format string that datepicker supports; if absent, the format set on the datepicker will be used. Both arguments are optional.
show
----
Fired when the date picker is displayed.
hide
----
Fired when the date picker is hidden.
clearDate
---------
Fired when the date is cleared, normally when the "clear" button (enabled with the ``clearBtn`` option) is pressed.
changeDate
----------
Fired when the date is changed.
changeYear
----------
Fired when the *view* year is changed from decade view.
changeMonth
-----------
Fired when the *view* month is changed from year view.
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/events.rst | events.rst |
window.HTMLImports=window.HTMLImports||{flags:{}},function(a){var b=(a.path,a.xhr),c=function(a,b){this.cache={},this.onload=a,this.oncomplete=b,this.inflight=0,this.pending={}};c.prototype={addNodes:function(a){this.inflight+=a.length,d(a,this.require,this),this.checkDone()},require:function(a){var b=a.src||a.href;a.__nodeUrl=b,this.dedupe(b,a)||this.fetch(b,a)},dedupe:function(a,b){return this.pending[a]?(this.pending[a].push(b),!0):this.cache[a]?(this.onload(a,b,this.cache[a]),this.tail(),!0):(this.pending[a]=[b],!1)},fetch:function(a,c){var d=function(b,d){this.receive(a,c,b,d)}.bind(this);b.load(a,d)},receive:function(a,b,c,d){c||(this.cache[a]=d),this.pending[a].forEach(function(b){c||this.onload(a,b,d),this.tail()},this),this.pending[a]=null},tail:function(){--this.inflight,this.checkDone()},checkDone:function(){this.inflight||this.oncomplete()}},b=b||{async:!0,ok:function(a){return a.status>=200&&a.status<300||304===a.status||0===a.status},load:function(c,d,e){var f=new XMLHttpRequest;return(a.flags.debug||a.flags.bust)&&(c+="?"+Math.random()),f.open("GET",c,b.async),f.addEventListener("readystatechange",function(){4===f.readyState&&d.call(e,!b.ok(f)&&f,f.response||f.responseText,c)}),f.send(),f},loadDocument:function(a,b,c){this.load(a,b,c).responseType="document"}};var d=Array.prototype.forEach.call.bind(Array.prototype.forEach);a.xhr=b,a.Loader=c}(window.HTMLImports),function(a){function b(a){return c(a,j)}function c(a,b){return"link"===a.localName&&a.getAttribute("rel")===b}function d(a){return"script"===a.localName}function e(a,b){var c=a;c instanceof Document||(c=document.implementation.createHTMLDocument(j)),c._URL=b;var d=c.createElement("base");return d.setAttribute("href",b),c.baseURI||(c.baseURI=b),c.head.appendChild(d),a instanceof Document||(c.body.innerHTML=a),window.HTMLTemplateElement&&HTMLTemplateElement.bootstrap&&HTMLTemplateElement.bootstrap(c),c}function f(a,b){function c(){k==l&&requestAnimationFrame(a)}function d(){k++,c()}b=b||o;var e=HTMLImports.isIE?"complete":"interactive",h="complete"===b.readyState||b.readyState===e;if(!h){var i=function(){("complete"===b.readyState||b.readyState===e)&&(b.removeEventListener("readystatechange",i),f(a,b))};return void b.addEventListener("readystatechange",i)}var j=b.querySelectorAll("link[rel=import]"),k=0,l=j.length;if(l)for(var m,n=0;l>n&&(m=j[n]);n++)g(m)?d.call(m):(m.addEventListener("load",d),m.addEventListener("error",d));else c()}function g(a){return i?a.import&&"loading"!==a.import.readyState:a.__importParsed}var h="import"in document.createElement("link"),i=!a.flags.imports&&h,j="import";if(!i){{var k,l=a.Loader,m=(a.xhr,"stylesheet"),n={documents:{},cache:{},preloadSelectors:["link[rel="+j+"]","template","script[src]:not([type])",'script[src][type="text/javascript"]'].join(","),loader:function(a){if(k&&k.inflight){var b=k.oncomplete;return k.oncomplete=function(){b(),a()},k}return k=new l(n.loaded,a),k.cache=n.cache,k},load:function(a,b){k=n.loader(b),n.preload(a)},preload:function(a){var b=this.marshalNodes(a);k.addNodes(b)},marshalNodes:function(a){var b=a.querySelectorAll(n.preloadSelectors);return b=this.filterMainDocumentNodes(a,b),b=this.extractTemplateNodes(b)},filterMainDocumentNodes:function(a,b){return a===document&&(b=Array.prototype.filter.call(b,function(a){return!d(a)})),b},extractTemplateNodes:function(a){var b=[];return a=Array.prototype.filter.call(a,function(a){if("template"===a.localName){if(a.content){var c=a.content.querySelectorAll("link[rel="+m+"]");c.length&&(b=b.concat(Array.prototype.slice.call(c,0)))}return!1}return!0}),b.length&&(a=a.concat(b)),a},loaded:function(a,c,d){if(b(c)){var f=n.documents[a];f||(f=e(d,a),n.documents[a]=f,n.preload(f)),c.import=c.content=d=f}c.__resource=d}};Array.prototype.forEach.call.bind(Array.prototype.forEach)}a.importer=n}var o=window.ShadowDOMPolyfill?wrap(document):document;Object.defineProperty(o,"_currentScript",{get:function(){return HTMLImports.currentScript||o.currentScript},writeable:!0,configurable:!0}),a.hasNative=h,a.useNative=i,a.whenImportsReady=f,a.IMPORT_LINK_TYPE=j,a.isImportLoaded=g}(window.HTMLImports),function(a){function b(a){var b=a.ownerDocument.createElement("style");return b.textContent=a.textContent,g.resolveUrlsInStyle(b),b}function c(a,b){this.doc=a,this.doc.__loadTracker=this,this.callback=b}function d(a){return"link"===a.localName&&a.getAttribute("rel")===h}function e(a){return a.parentNode&&!f(a)}function f(a){return a.ownerDocument===document||a.ownerDocument.impl===document}var g=a.path,h="import",i=/Trident/.test(navigator.userAgent),j={selectors:["link[rel="+h+"]","link[rel=stylesheet]","style","script:not([type])",'script[type="text/javascript"]'],map:{link:"parseLink",script:"parseScript",style:"parseStyle"},parse:function(a,b){if(a.__importParsed)b&&b();else{a.__importParsed=!0;for(var d,e=new c(a,b),f=a.querySelectorAll(j.selectors),g=a.scripts?a.scripts.length:0,h=0;h<f.length&&(d=f[h]);h++)j[j.map[d.localName]](d),a.scripts&&g!==a.scripts.length&&(g=a.scripts.length,f=a.querySelectorAll(j.selectors));e.open()}},parseLink:function(a){if(d(a)){if(this.trackElement(a),a.__resource?j.parse(a.__resource,function(){a.dispatchEvent(new CustomEvent("load",{bubbles:!1}))}):a.dispatchEvent(new CustomEvent("error",{bubbles:!1})),a.__pending)for(var b;a.__pending.length;)b=a.__pending.shift(),b&&b({target:a});a.__importParsed=!0}else e(a)&&(a.href=a.href),this.parseGeneric(a)},trackElement:function(a){i&&"style"===a.localName||a.ownerDocument.__loadTracker.require(a)},parseStyle:function(a){a=e(a)?b(a):a,this.parseGeneric(a)},parseGeneric:function(a){f(a)||(this.trackElement(a),document.head.appendChild(a))},parseScript:function(b){if(e(b)){var c=(b.__resource||b.textContent).trim();if(c){var d=b.__nodeUrl;if(!d){d=b.ownerDocument.baseURI;var f="["+Math.floor(1e3*(Math.random()+1))+"]",g=c.match(/Polymer\(['"]([^'"]*)/);f=g&&g[1]||f,d+="/"+f+".js"}c+="\n//# sourceURL="+d+"\n",a.currentScript=b,eval.call(window,c),a.currentScript=null}}}},k=/(url\()([^)]*)(\))/g,l=/(@import[\s]*)([^;]*)(;)/g,g={resolveUrlsInStyle:function(a){var b=a.ownerDocument,c=b.createElement("a");return a.textContent=this.resolveUrlsInCssText(a.textContent,c),a},resolveUrlsInCssText:function(a,b){var c=this.replaceUrls(a,b,k);return c=this.replaceUrls(c,b,l)},replaceUrls:function(a,b,c){return a.replace(c,function(a,c,d,e){var f=d.replace(/["']/g,"");return b.href=f,f=b.href,c+"'"+f+"'"+e})}};c.prototype={pending:0,isOpen:!1,open:function(){this.isOpen=!0,this.checkDone()},add:function(){this.pending++},require:function(a){this.add();var b=this,c=function(a){b.receive(a)};if(d(a))a.__pending=a.__pending||[],a.__pending.push(c);else for(var e,f=["load","error"],g=0,h=f.length;h>g&&(e=f[g]);g++)a.addEventListener(e,c)},receive:function(){this.pending--,this.checkDone()},checkDone:function(){this.isOpen&&this.pending<=0&&this.callback&&(this.isOpen=!1,this.callback())}};Array.prototype.forEach.call.bind(Array.prototype.forEach);a.parser=j,a.path=g,a.isIE=i}(HTMLImports),function(){function a(){HTMLImports.ready=!0,HTMLImports.readyTime=(new Date).getTime(),c.dispatchEvent(new CustomEvent("HTMLImportsLoaded",{bubbles:!0}))}function b(){HTMLImports.useNative||HTMLImports.importer.load(c,function(){HTMLImports.parser.parse(c)})}"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(a,b){var c=document.createEvent("HTMLEvents");return c.initEvent(a,b.bubbles===!1?!1:!0,b.cancelable===!1?!1:!0,b.detail),c});var c=window.ShadowDOMPolyfill?window.ShadowDOMPolyfill.wrapIfNeeded(document):document;HTMLImports.useNative||("complete"===document.readyState||"interactive"===document.readyState&&!window.attachEvent?b():document.addEventListener("DOMContentLoaded",b)),HTMLImports.whenImportsReady(function(){a()})}();
//# sourceMappingURL=html-imports.min.map | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/_screenshots/script/html-imports.min.js | html-imports.min.js |
var sys = require('system'),
page = new WebPage();
page.viewportSize = {
width: 800,
height: 600
};
page.open(sys.args[1], function(status){
if (status !== 'success'){
console.log('Bad status: %s', status);
phantom.exit(1);
}
window.setTimeout(function(){
var box = page.evaluate(function(){
var lefts, rights, tops, bottoms,
padding = 10, // px
selection, show;
// Call setup method
if (window.setup)
window.setup();
// Show all pickers, or only those marked for showing
show = $('body').data('show');
show = show ? $(show) : $('*');
show
.filter(function(){
return 'datepicker' in $(this).data();
})
.datepicker('show');
// Get bounds of selected elements
selection = $($('body').data('capture'));
tops = selection.map(function(){
return $(this).offset().top;
}).toArray();
lefts = selection.map(function(){
return $(this).offset().left;
}).toArray();
bottoms = selection.map(function(){
return $(this).offset().top + $(this).outerHeight();
}).toArray();
rights = selection.map(function(){
return $(this).offset().left + $(this).outerWidth();
}).toArray();
// Convert bounds to single bounding box
var b = {
top: Math.min.apply(Math, tops),
left: Math.min.apply(Math, lefts)
};
b['width'] = Math.max.apply(Math, rights) - b.left;
b['height'] = Math.max.apply(Math, bottoms) - b.top;
// Return bounding box
return {
top: Math.max(b.top - padding, 0),
left: Math.max(b.left - padding, 0),
width: b.width + 2 * padding,
height: b.height + 2 * padding
};
});
page.clipRect = box;
page.render(sys.args[2]);
phantom.exit();
}, 1);
}); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/docs/_screenshots/script/screenshot.js | screenshot.js |
(function($, undefined){
var $window = $(window);
function UTCDate(){
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday(){
var today = new Date();
return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
}
function alias(method){
return function(){
return this[method].apply(this, arguments);
};
}
var DateArray = (function(){
var extras = {
get: function(i){
return this.slice(i)[0];
},
contains: function(d){
// Array.indexOf is not cross-browser;
// $.inArray doesn't work with Dates
var val = d && d.valueOf();
for (var i=0, l=this.length; i < l; i++)
if (this[i].valueOf() === val)
return i;
return -1;
},
remove: function(i){
this.splice(i,1);
},
replace: function(new_array){
if (!new_array)
return;
if (!$.isArray(new_array))
new_array = [new_array];
this.clear();
this.push.apply(this, new_array);
},
clear: function(){
this.length = 0;
},
copy: function(){
var a = new DateArray();
a.replace(this);
return a;
}
};
return function(){
var a = [];
a.push.apply(a, arguments);
$.extend(a, extras);
return a;
};
})();
// Picker object
var Datepicker = function(element, options){
this.dates = new DateArray();
this.viewDate = UTCToday();
this.focusDate = null;
this._process_options(options);
this.element = $(element);
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if (this.component && this.component.length === 0)
this.component = false;
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if (this.isInline){
this.picker.addClass('datepicker-inline').appendTo(this.element);
}
else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl){
this.picker.addClass('datepicker-rtl');
}
this.viewMode = this.o.startView;
if (this.o.calendarWeeks)
this.picker.find('tfoot th.today, tfoot th.clear')
.attr('colspan', function(i, val){
return parseInt(val) + 1;
});
this._allow_update = false;
this.setStartDate(this._o.startDate);
this.setEndDate(this._o.endDate);
this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if (this.isInline){
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_process_options: function(opts){
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
switch (o.startView){
case 2:
case 'decade':
o.startView = 2;
break;
case 1:
case 'year':
o.startView = 1;
break;
default:
o.startView = 0;
}
switch (o.minViewMode){
case 1:
case 'months':
o.minViewMode = 1;
break;
case 2:
case 'years':
o.minViewMode = 2;
break;
default:
o.minViewMode = 0;
}
o.startView = Math.max(o.startView, o.minViewMode);
// true, false, or Number > 0
if (o.multidate !== true){
o.multidate = Number(o.multidate) || false;
if (o.multidate !== false)
o.multidate = Math.max(0, o.multidate);
else
o.multidate = 1;
}
o.multidateSeparator = String(o.multidateSeparator);
o.weekStart %= 7;
o.weekEnd = ((o.weekStart + 6) % 7);
var format = DPGlobal.parseFormat(o.format);
if (o.startDate !== -Infinity){
if (!!o.startDate){
if (o.startDate instanceof Date)
o.startDate = this._local_to_utc(this._zero_time(o.startDate));
else
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
}
else {
o.startDate = -Infinity;
}
}
if (o.endDate !== Infinity){
if (!!o.endDate){
if (o.endDate instanceof Date)
o.endDate = this._local_to_utc(this._zero_time(o.endDate));
else
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
}
else {
o.endDate = Infinity;
}
}
o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
if (!$.isArray(o.daysOfWeekDisabled))
o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function(d){
return parseInt(d, 10);
});
var plc = String(o.orientation).toLowerCase().split(/\s+/g),
_plc = o.orientation.toLowerCase();
plc = $.grep(plc, function(word){
return (/^auto|left|right|top|bottom$/).test(word);
});
o.orientation = {x: 'auto', y: 'auto'};
if (!_plc || _plc === 'auto')
; // no action
else if (plc.length === 1){
switch (plc[0]){
case 'top':
case 'bottom':
o.orientation.y = plc[0];
break;
case 'left':
case 'right':
o.orientation.x = plc[0];
break;
}
}
else {
_plc = $.grep(plc, function(word){
return (/^left|right$/).test(word);
});
o.orientation.x = _plc[0] || 'auto';
_plc = $.grep(plc, function(word){
return (/^top|bottom$/).test(word);
});
o.orientation.y = _plc[0] || 'auto';
}
},
_events: [],
_secondaryEvents: [],
_applyEvents: function(evs){
for (var i=0, el, ch, ev; i < evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.on(ev, ch);
}
},
_unapplyEvents: function(evs){
for (var i=0, el, ev, ch; i < evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.off(ev, ch);
}
},
_buildEvents: function(){
if (this.isInput){ // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput){ // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')){ // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._events.push(
// Component: listen for blur on element descendants
[this.element, '*', {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}],
// Input: listen for blur on element
[this.element, {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}]
);
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
'mousedown touchstart': $.proxy(function(e){
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).length ||
this.picker.is(e.target) ||
this.picker.find(e.target).length
)){
this.hide();
}
}, this)
}]
];
},
_attachEvents: function(){
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function(){
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function(){
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function(){
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function(event, altdate){
var date = altdate || this.dates.get(-1),
local_date = this._utc_to_local(date);
this.element.trigger({
type: event,
date: local_date,
dates: $.map(this.dates, this._utc_to_local),
format: $.proxy(function(ix, format){
if (arguments.length === 0){
ix = this.dates.length - 1;
format = this.o.format;
}
else if (typeof ix === 'string'){
format = ix;
ix = this.dates.length - 1;
}
format = format || this.o.format;
var date = this.dates.get(ix);
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function(){
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.place();
this._attachSecondaryEvents();
this._trigger('show');
},
hide: function(){
if (this.isInline)
return;
if (!this.picker.is(':visible'))
return;
this.focusDate = null;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.o.startView;
this.showMode();
if (
this.o.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this._trigger('hide');
},
remove: function(){
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput){
delete this.element.data().date;
}
},
_utc_to_local: function(utc){
return utc && new Date(utc.getTime() + (utc.getTimezoneOffset()*60000));
},
_local_to_utc: function(local){
return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
},
_zero_time: function(local){
return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
},
_zero_utc_time: function(utc){
return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
},
getDates: function(){
return $.map(this.dates, this._utc_to_local);
},
getUTCDates: function(){
return $.map(this.dates, function(d){
return new Date(d);
});
},
getDate: function(){
return this._utc_to_local(this.getUTCDate());
},
getUTCDate: function(){
return new Date(this.dates.get(-1));
},
setDates: function(){
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, args);
this._trigger('changeDate');
this.setValue();
},
setUTCDates: function(){
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, $.map(args, this._utc_to_local));
this._trigger('changeDate');
this.setValue();
},
setDate: alias('setDates'),
setUTCDate: alias('setUTCDates'),
setValue: function(){
var formatted = this.getFormattedDate();
if (!this.isInput){
if (this.component){
this.element.find('input').val(formatted).change();
}
}
else {
this.element.val(formatted).change();
}
},
getFormattedDate: function(format){
if (format === undefined)
format = this.o.format;
var lang = this.o.language;
return $.map(this.dates, function(d){
return DPGlobal.formatDate(d, format, lang);
}).join(this.o.multidateSeparator);
},
setStartDate: function(startDate){
this._process_options({startDate: startDate});
this.update();
this.updateNavArrows();
},
setEndDate: function(endDate){
this._process_options({endDate: endDate});
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function(daysOfWeekDisabled){
this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
this.update();
this.updateNavArrows();
},
place: function(){
if (this.isInline)
return;
var calendarWidth = this.picker.outerWidth(),
calendarHeight = this.picker.outerHeight(),
visualPadding = 10,
windowWidth = $window.width(),
windowHeight = $window.height(),
scrollTop = $window.scrollTop();
var parentsZindex = [];
this.element.parents().each(function() {
var itemZIndex = $(this).css('z-index');
if ( itemZIndex !== 'auto' && itemZIndex !== 0 ) parentsZindex.push( parseInt( itemZIndex ) );
});
var zIndex = Math.max.apply( Math, parentsZindex ) + 10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
var left = offset.left,
top = offset.top;
this.picker.removeClass(
'datepicker-orient-top datepicker-orient-bottom '+
'datepicker-orient-right datepicker-orient-left'
);
if (this.o.orientation.x !== 'auto'){
this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
if (this.o.orientation.x === 'right')
left -= calendarWidth - width;
}
// auto x orientation is best-placement: if it crosses a window
// edge, fudge it sideways
else {
// Default to left
this.picker.addClass('datepicker-orient-left');
if (offset.left < 0)
left -= offset.left - visualPadding;
else if (offset.left + calendarWidth > windowWidth)
left = windowWidth - calendarWidth - visualPadding;
}
// auto y orientation is best-situation: top or bottom, no fudging,
// decision based on which shows more of the calendar
var yorient = this.o.orientation.y,
top_overflow, bottom_overflow;
if (yorient === 'auto'){
top_overflow = -scrollTop + offset.top - calendarHeight;
bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
yorient = 'top';
else
yorient = 'bottom';
}
this.picker.addClass('datepicker-orient-' + yorient);
if (yorient === 'top')
top += height;
else
top -= calendarHeight + parseInt(this.picker.css('padding-top'));
this.picker.css({
top: top,
left: left,
zIndex: zIndex
});
},
_allow_update: true,
update: function(){
if (!this._allow_update)
return;
var oldDates = this.dates.copy(),
dates = [],
fromArgs = false;
if (arguments.length){
$.each(arguments, $.proxy(function(i, date){
if (date instanceof Date)
date = this._local_to_utc(date);
dates.push(date);
}, this));
fromArgs = true;
}
else {
dates = this.isInput
? this.element.val()
: this.element.data('date') || this.element.find('input').val();
if (dates && this.o.multidate)
dates = dates.split(this.o.multidateSeparator);
else
dates = [dates];
delete this.element.data().date;
}
dates = $.map(dates, $.proxy(function(date){
return DPGlobal.parseDate(date, this.o.format, this.o.language);
}, this));
dates = $.grep(dates, $.proxy(function(date){
return (
date < this.o.startDate ||
date > this.o.endDate ||
!date
);
}, this), true);
this.dates.replace(dates);
if (this.dates.length)
this.viewDate = new Date(this.dates.get(-1));
else if (this.viewDate < this.o.startDate)
this.viewDate = new Date(this.o.startDate);
else if (this.viewDate > this.o.endDate)
this.viewDate = new Date(this.o.endDate);
if (fromArgs){
// setting date by clicking
this.setValue();
}
else if (dates.length){
// setting date by typing
if (String(oldDates) !== String(this.dates))
this._trigger('changeDate');
}
if (!this.dates.length && oldDates.length)
this._trigger('clearDate');
this.fill();
},
fillDow: function(){
var dowCnt = this.o.weekStart,
html = '<tr>';
if (this.o.calendarWeeks){
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.o.weekStart + 7){
html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '',
i = 0;
while (i < 12){
html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function(range){
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function(d){
return d.valueOf();
});
this.fill();
},
getClassNames: function(date){
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
today = new Date();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){
cls.push('old');
}
else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){
cls.push('new');
}
if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
cls.push('focused');
// Compare internal UTC date with local today, not UTC today
if (this.o.todayHighlight &&
date.getUTCFullYear() === today.getFullYear() &&
date.getUTCMonth() === today.getMonth() &&
date.getUTCDate() === today.getDate()){
cls.push('today');
}
if (this.dates.contains(date) !== -1)
cls.push('active');
if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1){
cls.push('disabled');
}
if (this.range){
if (date > this.range[0] && date < this.range[this.range.length-1]){
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) !== -1){
cls.push('selected');
}
}
return cls;
},
fill: function(){
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
todaytxt = dates[this.o.language].today || dates['en'].today || '',
cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
tooltip;
if (isNaN(year) || isNaN(month)) return;
this.picker.find('.datepicker-days thead th.datepicker-switch')
.text(dates[this.o.language].months[month]+' '+year);
this.picker.find('tfoot th.today')
.text(todaytxt)
.toggle(this.o.todayBtn !== false);
this.picker.find('tfoot th.clear')
.text(cleartxt)
.toggle(this.o.clearBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month-1, 28),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while (prevMonth.valueOf() < nextMonth){
if (prevMonth.getUTCDay() === this.o.weekStart){
html.push('<tr>');
if (this.o.calendarWeeks){
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">'+ calWeek +'</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
if (this.o.beforeShowDay !== $.noop){
var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof(before) === 'boolean')
before = {enabled: before};
else if (typeof(before) === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
}
clsName = $.unique(clsName);
html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
tooltip = null;
if (prevMonth.getUTCDay() === this.o.weekEnd){
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
$.each(this.dates, function(i, d){
if (d.getUTCFullYear() === year)
months.eq(d.getUTCMonth()).addClass('active');
});
if (year < startYear || year > endYear){
months.addClass('disabled');
}
if (year === startYear){
months.slice(0, startMonth).addClass('disabled');
}
if (year === endYear){
months.slice(endMonth+1).addClass('disabled');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
var years = $.map(this.dates, function(d){
return d.getUTCFullYear();
}),
classes;
for (var i = -1; i < 11; i++){
classes = ['year'];
if (i === -1)
classes.push('old');
else if (i === 10)
classes.push('new');
if ($.inArray(year, years) !== -1)
classes.push('active');
if (year < startYear || year > endYear)
classes.push('disabled');
html += '<span class="' + classes.join(' ') + '">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function(){
if (!this._allow_update)
return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode){
case 0:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()){
this.picker.find('.prev').css({visibility: 'hidden'});
}
else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()){
this.picker.find('.next').css({visibility: 'hidden'});
}
else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()){
this.picker.find('.prev').css({visibility: 'hidden'});
}
else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()){
this.picker.find('.next').css({visibility: 'hidden'});
}
else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function(e){
e.preventDefault();
var target = $(e.target).closest('span, td, th'),
year, month, day;
if (target.length === 1){
switch (target[0].nodeName.toLowerCase()){
case 'th':
switch (target[0].className){
case 'datepicker-switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1);
switch (this.viewMode){
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
if (this.viewMode === 1)
this._trigger('changeYear', this.viewDate);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.o.todayBtn === 'linked' ? null : 'view';
this._setDate(date, which);
break;
case 'clear':
var element;
if (this.isInput)
element = this.element;
else if (this.component)
element = this.element.find('input');
if (element)
element.val("").change();
this.update();
this._trigger('changeDate');
if (this.o.autoclose)
this.hide();
break;
}
break;
case 'span':
if (!target.is('.disabled')){
this.viewDate.setUTCDate(1);
if (target.is('.month')){
day = 1;
month = target.parent().find('span').index(target);
year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1){
this._setDate(UTCDate(year, month, day));
}
}
else {
day = 1;
month = 0;
year = parseInt(target.text(), 10)||0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2){
this._setDate(UTCDate(year, month, day));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
day = parseInt(target.text(), 10)||1;
year = this.viewDate.getUTCFullYear();
month = this.viewDate.getUTCMonth();
if (target.is('.old')){
if (month === 0){
month = 11;
year -= 1;
}
else {
month -= 1;
}
}
else if (target.is('.new')){
if (month === 11){
month = 0;
year += 1;
}
else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day));
}
break;
}
}
if (this.picker.is(':visible') && this._focused_from){
$(this._focused_from).focus();
}
delete this._focused_from;
},
_toggle_multidate: function(date){
var ix = this.dates.contains(date);
if (!date){
this.dates.clear();
}
if (this.o.multidate === 1 && ix === 0){
// single datepicker, don't remove selected date
}
else if (ix !== -1){
this.dates.remove(ix);
}
else {
this.dates.push(date);
}
if (typeof this.o.multidate === 'number')
while (this.dates.length > this.o.multidate)
this.dates.remove(0);
},
_setDate: function(date, which){
if (!which || which === 'date')
this._toggle_multidate(date && new Date(date));
if (!which || which === 'view')
this.viewDate = date && new Date(date);
this.fill();
this.setValue();
this._trigger('changeDate');
var element;
if (this.isInput){
element = this.element;
}
else if (this.component){
element = this.element.find('input');
}
if (element){
element.change();
}
if (this.o.autoclose && (!which || which === 'date')){
this.hide();
}
},
moveMonth: function(date, dir){
if (!date)
return undefined;
if (!dir)
return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag === 1){
test = dir === -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function(){
return new_date.getUTCMonth() === month;
}
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function(){
return new_date.getUTCMonth() !== new_month;
};
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
}
else {
// For magnitudes >1, move one month at a time...
for (var i=0; i < mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){
return new_month !== new_date.getUTCMonth();
};
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
dateWithinRange: function(date){
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function(e){
if (this.picker.is(':not(:visible)')){
if (e.keyCode === 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, newDate, newViewDate,
focusDate = this.focusDate || this.viewDate;
switch (e.keyCode){
case 27: // escape
if (this.focusDate){
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
}
else
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.o.keyboardNavigation)
break;
dir = e.keyCode === 37 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
}
else if (e.shiftKey){
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
}
else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 38: // up
case 40: // down
if (!this.o.keyboardNavigation)
break;
dir = e.keyCode === 38 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
}
else if (e.shiftKey){
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
}
else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir * 7);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 32: // spacebar
// Spacebar is used in manually typing dates in some formats.
// As such, its behavior should not be hijacked.
break;
case 13: // enter
focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
if (this.o.keyboardNavigation) {
this._toggle_multidate(focusDate);
dateChanged = true;
}
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.setValue();
this.fill();
if (this.picker.is(':visible')){
e.preventDefault();
if (this.o.autoclose)
this.hide();
}
break;
case 9: // tab
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
this.hide();
break;
}
if (dateChanged){
if (this.dates.length)
this._trigger('changeDate');
else
this._trigger('clearDate');
var element;
if (this.isInput){
element = this.element;
}
else if (this.component){
element = this.element.find('input');
}
if (element){
element.change();
}
}
},
showMode: function(dir){
if (dir){
this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker
.find('>div')
.hide()
.filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName)
.css('display', 'block');
this.updateNavArrows();
}
};
var DateRangePicker = function(element, options){
this.element = $(element);
this.inputs = $.map(options.inputs, function(i){
return i.jquery ? i[0] : i;
});
delete options.inputs;
$(this.inputs)
.datepicker(options)
.bind('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function(i){
return $(i).data('datepicker');
});
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function(){
this.dates = $.map(this.pickers, function(i){
return i.getUTCDate();
});
this.updateRanges();
},
updateRanges: function(){
var range = $.map(this.dates, function(d){
return d.valueOf();
});
$.each(this.pickers, function(i, p){
p.setRange(range);
});
},
dateUpdated: function(e){
// `this.updating` is a workaround for preventing infinite recursion
// between `changeDate` triggering and `setUTCDate` calling. Until
// there is a better mechanism.
if (this.updating)
return;
this.updating = true;
var dp = $(e.target).data('datepicker'),
new_date = dp.getUTCDate(),
i = $.inArray(e.target, this.inputs),
l = this.inputs.length;
if (i === -1)
return;
$.each(this.pickers, function(i, p){
if (!p.getUTCDate())
p.setUTCDate(new_date);
});
if (new_date < this.dates[i]){
// Date being moved earlier/left
while (i >= 0 && new_date < this.dates[i]){
this.pickers[i--].setUTCDate(new_date);
}
}
else if (new_date > this.dates[i]){
// Date being moved later/right
while (i < l && new_date > this.dates[i]){
this.pickers[i++].setUTCDate(new_date);
}
}
this.updateDates();
delete this.updating;
},
remove: function(){
$.map(this.pickers, function(p){ p.remove(); });
delete this.element.data().datepicker;
}
};
function opts_from_el(el, prefix){
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
prefix = new RegExp('^' + prefix.toLowerCase());
function re_lower(_,a){
return a.toLowerCase();
}
for (var key in data)
if (prefix.test(key)){
inkey = key.replace(replace, re_lower);
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang){
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function(i,k){
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
$.fn.datepicker = function(option){
var args = Array.apply(null, arguments);
args.shift();
var internal_return;
this.each(function(){
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option === 'object' && option;
if (!data){
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.is('.input-daterange') || opts.inputs){
var ropts = {
inputs: opts.inputs || $this.find('input').toArray()
};
$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
}
else {
$this.data('datepicker', (data = new Datepicker(this, opts)));
}
}
if (typeof option === 'string' && typeof data[option] === 'function'){
internal_return = data[option].apply(data, args);
if (internal_return !== undefined)
return false;
}
});
if (internal_return !== undefined)
return internal_return;
else
return this;
};
var defaults = $.fn.datepicker.defaults = {
autoclose: false,
beforeShowDay: $.noop,
calendarWeeks: false,
clearBtn: false,
daysOfWeekDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function(year){
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function(year, month){
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(format){
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language){
if (!date)
return undefined;
if (date instanceof Date)
return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir, i;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)){
date = new Date();
for (i=0; i < parts.length; i++){
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]){
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
parts = date && date.match(this.nonpunctuation) || [];
date = new Date();
var parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){
return d.setUTCFullYear(v);
},
yy: function(d,v){
return d.setUTCFullYear(2000+v);
},
m: function(d,v){
if (isNaN(d))
return d;
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() !== v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){
return d.setUTCDate(v);
}
},
val, filtered;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length !== fparts.length){
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
function match_part(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m === p;
}
if (parts.length === fparts.length){
var cnt;
for (i=0, cnt = fparts.length; i < cnt; i++){
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)){
switch (part){
case 'MM':
filtered = $(dates[language].months).filter(match_part);
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(match_part);
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
var _date, s;
for (i=0; i < setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])){
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function(date, format, language){
if (!date)
return '';
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
date = [];
var seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i <= cnt; i++){
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">«</th>'+
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next">»</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot>'+
'<tr>'+
'<th colspan="7" class="today"></th>'+
'</tr>'+
'<tr>'+
'<th colspan="7" class="clear"></th>'+
'</tr>'+
'</tfoot>'
};
DPGlobal.template = '<div class="datepicker">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function(){
$.fn.datepicker = old;
return this;
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function(e){
var $this = $(this);
if ($this.data('datepicker'))
return;
e.preventDefault();
// component click requires us to explicitly show it
$this.datepicker('show');
}
);
$(function(){
$('[data-provide="datepicker-inline"]').datepicker();
});
}(window.jQuery)); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/bootstrap-datepicker/js/bootstrap-datepicker.js | bootstrap-datepicker.js |
Timeago is a jQuery plugin that makes it easy to support automatically updating
fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago") from ISO 8601
formatted dates and times embedded in your HTML (à la microformats).
**If you like this project, please help by donating.**
* Gittip: https://www.gittip.com/rmm5t/
* Bitcoin: `1wzBnMjWVZfpiFMc5i2nzKT7sCBaZNfLK`
## Usage
First, load jQuery and the plugin:
```html
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery.timeago.js" type="text/javascript"></script>
```
Now, let's attach it to your timestamps on DOM ready - put this in the head
section:
```html
<script type="text/javascript">
jQuery(document).ready(function() {
$("abbr.timeago").timeago();
});
</script>
```
This will turn all abbr elements with a class of timeago and an ISO 8601
timestamp in the title (conforming to the
[datetime design pattern microformat](http://microformats.org/wiki/datetime-design-pattern)):
```html
<abbr class="timeago" title="2011-12-17T09:24:17Z">December 17, 2011</abbr>
```
into something like this:
```html
<abbr class="timeago" title="December 17, 2011">about 1 day ago</abbr>
```
HTML5 `<time>` elements are also supported:
```html
<time class="timeago" datetime="2011-12-17T09:24:17Z">December 17, 2011</time>
```
As time passes, the timestamps will automatically update.
**For more usage and examples**: [http://timeago.yarp.com/](http://timeago.yarp.com/)
**For different language configurations**: visit the [`locales`](https://github.com/rmm5t/jquery-timeago/tree/master/locales) directory.
## Changes
| Version | Notes |
|---------|---------------------------------------------------------------------------------|
| 1.3.x | ([compare][compare-1.3]) Added updateFromDOM function; bug fixes; bower support |
| 1.2.x | ([compare][compare-1.2]) Added cutoff setting |
| 1.1.x | ([compare][compare-1.1]) Added update function |
| 1.0.x | ([compare][compare-1.0]) locale updates; bug fixes; AMD wrapper |
| 0.11.x | ([compare][compare-0.11]) natural rounding; locale updates; |
| 0.10.x | ([compare][compare-0.10]) locale updates |
| 0.9.x | ([compare][compare-0.9]) microsecond support; bug fixes |
| 0.8.x | ([compare][compare-0.8]) `<time>` element support; bug fixes |
| 0.7.x | ([compare][compare-0.7]) locale function overrides; unit tests |
| ... | ... |
[compare-1.3]: https://github.com/rmm5t/jquery-timeago/compare/v1.2.0...v1.3.2
[compare-1.2]: https://github.com/rmm5t/jquery-timeago/compare/v1.1.0...v1.2.0
[compare-1.1]: https://github.com/rmm5t/jquery-timeago/compare/v1.0.2...v1.1.0
[compare-1.0]: https://github.com/rmm5t/jquery-timeago/compare/v0.11.4...v1.0.2
[compare-0.11]: https://github.com/rmm5t/jquery-timeago/compare/v0.10.1...v0.11.4
[compare-0.10]: https://github.com/rmm5t/jquery-timeago/compare/v0.9.3...v0.10.1
[compare-0.9]: https://github.com/rmm5t/jquery-timeago/compare/v0.8.2...v0.9.3
[compare-0.8]: https://github.com/rmm5t/jquery-timeago/compare/v0.7.2...v0.8.2
[compare-0.7]: https://github.com/rmm5t/jquery-timeago/compare/v0.6.2...v0.7.2
## Author
[Ryan McGeary](http://ryan.mcgeary.org) ([@rmm5t](http://twitter.com/rmm5t))
## Other
[MIT License](http://www.opensource.org/licenses/mit-license.php)
Copyright (c) 2008-2013, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org) | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery-timeago/README.markdown | README.markdown |
## Want to Contribute?
Found an issue? Thank you for helping out by reporting it. Please describe the
problem, what you tried, what you expected to see, and what you actually
experienced. Please [re-read the documentation](http://timeago.yarp.com/) to
make sure you're using the API as designed, but if you found something that's
broken, we really appreciate your efforts in letting us know. Bonus points for
submitting a failing test case to help us diagnose and potentially fix the
issue.
## Want to Contribute?
Awesome. We love help, but before getting started, please read:
**[Don't "Push" Your Pull Requests](http://www.igvita.com/2011/12/19/dont-push-your-pull-requests/)**
## Ready for a Pull-Request?
1. Fork the repo.
2. Run the tests. Run `rake` or open `open test/index.html`. We only take pull
requests with passing tests, and it's great to know that you started from a
clean slate.
3. Add a test for your change. Only refactoring and documentation change
require no new tests. If you are adding functionality or fixing a bug, we
need a test!
4. Make the test pass.
5. Push to your fork (hopefully this comes from a topical branch) and submit a
pull request.
At this point you're waiting on us. Please keep in mind that OSS maintainers
are often very busy. We'll do our best to at least comment on issues and
pull-requests as soon as possible, but sometimes life gets in the way. We may
also suggest some changes or improvements or alternatives.
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery-timeago/CONTRIBUTING.md | CONTRIBUTING.md |
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.timeago = function(timestamp) {
if (timestamp instanceof Date) {
return inWords(timestamp);
} else if (typeof timestamp === "string") {
return inWords($.timeago.parse(timestamp));
} else if (typeof timestamp === "number") {
return inWords(new Date(timestamp));
} else {
return inWords($.timeago.datetime(timestamp));
}
};
var $t = $.timeago;
$.extend($.timeago, {
settings: {
refreshMillis: 60000,
allowFuture: false,
localeTitle: false,
cutoff: 0,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years",
wordSeparator: " ",
numbers: []
}
},
inWords: function(distanceMillis) {
var $l = this.settings.strings;
var prefix = $l.prefixAgo;
var suffix = $l.suffixAgo;
if (this.settings.allowFuture) {
if (distanceMillis < 0) {
prefix = $l.prefixFromNow;
suffix = $l.suffixFromNow;
}
}
var seconds = Math.abs(distanceMillis) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var years = days / 365;
function substitute(stringOrFunction, number) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
var value = ($l.numbers && $l.numbers[number]) || number;
return string.replace(/%d/i, value);
}
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
var separator = $l.wordSeparator || "";
if ($l.wordSeparator === undefined) { separator = " "; }
return $.trim([prefix, words, suffix].join(separator));
},
parse: function(iso8601) {
var s = $.trim(iso8601);
s = s.replace(/\.\d+/,""); // remove milliseconds
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900
return new Date(s);
},
datetime: function(elem) {
var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
return $t.parse(iso8601);
},
isTime: function(elem) {
// jQuery's `is()` doesn't play well with HTML5 in IE
return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
}
});
// functions that can be called via $(el).timeago('action')
// init is default when no action is given
// functions are called with context of a single element
var functions = {
init: function(){
var refresh_el = $.proxy(refresh, this);
refresh_el();
var $s = $t.settings;
if ($s.refreshMillis > 0) {
this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis);
}
},
update: function(time){
var parsedTime = $t.parse(time);
$(this).data('timeago', { datetime: parsedTime });
if($t.settings.localeTitle) $(this).attr("title", parsedTime.toLocaleString());
refresh.apply(this);
},
updateFromDOM: function(){
$(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ? $(this).attr("datetime") : $(this).attr("title") ) });
refresh.apply(this);
},
dispose: function () {
if (this._timeagoInterval) {
window.clearInterval(this._timeagoInterval);
this._timeagoInterval = null;
}
}
};
$.fn.timeago = function(action, options) {
var fn = action ? functions[action] : functions.init;
if(!fn){
throw new Error("Unknown function name '"+ action +"' for timeago");
}
// each over objects here and call the requested function
this.each(function(){
fn.call(this, options);
});
return this;
};
function refresh() {
var data = prepareData(this);
var $s = $t.settings;
if (!isNaN(data.datetime)) {
if ( $s.cutoff == 0 || distance(data.datetime) < $s.cutoff) {
$(this).text(inWords(data.datetime));
}
}
return this;
}
function prepareData(element) {
element = $(element);
if (!element.data("timeago")) {
element.data("timeago", { datetime: $t.datetime(element) });
var text = $.trim(element.text());
if ($t.settings.localeTitle) {
element.attr("title", element.data('timeago').datetime.toLocaleString());
} else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
element.attr("title", text);
}
}
return element.data("timeago");
}
function inWords(date) {
return $t.inWords(distance(date));
}
function distance(date) {
return (new Date().getTime() - date.getTime());
}
// fix for IE6 suckage
document.createElement("abbr");
document.createElement("time");
})); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery-timeago/jquery.timeago.js | jquery.timeago.js |
(function() {
function numpf(n, a) {
return a[plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5];
}
jQuery.timeago.settings.strings = {
prefixAgo: "منذ",
prefixFromNow: "بعد",
suffixAgo: null,
suffixFromNow: null, // null OR "من الآن"
second: function(value) { return numpf(value, [
'أقل من ثانية',
'ثانية واحدة',
'ثانيتين',
'%d ثوانٍ',
'%d ثانية',
'%d ثانية']); },
seconds: function(value) { return numpf(value, [
'أقل من ثانية',
'ثانية واحدة',
'ثانيتين',
'%d ثوانٍ',
'%d ثانية',
'%d ثانية']); },
minute: function(value) { return numpf(value, [
'أقل من دقيقة',
'دقيقة واحدة',
'دقيقتين',
'%d دقائق',
'%d دقيقة',
'دقيقة']); },
minutes: function(value) { return numpf(value, [
'أقل من دقيقة',
'دقيقة واحدة',
'دقيقتين',
'%d دقائق',
'%d دقيقة',
'دقيقة']); },
hour: function(value) { return numpf(value, [
'أقل من ساعة',
'ساعة واحدة',
'ساعتين',
'%d ساعات',
'%d ساعة',
'%d ساعة']); },
hours: function(value) { return numpf(value, [
'أقل من ساعة',
'ساعة واحدة',
'ساعتين',
'%d ساعات',
'%d ساعة',
'%d ساعة']); },
day: function(value) { return numpf(value, [
'أقل من يوم',
'يوم واحد',
'يومين',
'%d أيام',
'%d يومًا',
'%d يوم']); },
days: function(value) { return numpf(value, [
'أقل من يوم',
'يوم واحد',
'يومين',
'%d أيام',
'%d يومًا',
'%d يوم']); },
month: function(value) { return numpf(value, [
'أقل من شهر',
'شهر واحد',
'شهرين',
'%d أشهر',
'%d شهرًا',
'%d شهر']); },
months: function(value) { return numpf(value, [
'أقل من شهر',
'شهر واحد',
'شهرين',
'%d أشهر',
'%d شهرًا',
'%d شهر']); },
year: function(value) { return numpf(value, [
'أقل من عام',
'عام واحد',
'%d عامين',
'%d أعوام',
'%d عامًا']);
},
years: function(value) { return numpf(value, [
'أقل من عام',
'عام واحد',
'عامين',
'%d أعوام',
'%d عامًا',
'%d عام']);}
};
})(); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery-timeago/locales/jquery.timeago.ar.js | jquery.timeago.ar.js |
# Locale override examples for timeago
You can represent time statements in most western languages where
a prefix and/or suffix is used.
The default case is to use suffix only (as in English), which you
do by providing the `suffixAgo` and `suffixFromNow` settings in
the strings hash (earlier versions of timeago used the deprecated
`ago` and `fromNow` options). If present, they are used.
2 minutes [suffixAgo]
2 minutes [suffixFromNow]
In case you want to use prefix only instead of
suffix (e.g. Greek), you provide the `prefixAgo` and
`prefixFromNow` options in the strings hash and leave `suffixAgo`
and `suffixFromNow` empty or null.
[prefixAgo] 2 minutes
[prefixFromNow] 2 minutes
For languages where you want to use a prefix only for future
tense and prefix/suffix for past tense (for example swedish), you
can combine the prefix and suffixes as needed.
[prefixAgo] 2 minutes [suffixAgo]
[prefixFromNow] 2 minutes
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery-timeago/locales/README.md | README.md |
var requirejs, require, define;
(function (global) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.1.22',
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,
isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
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]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
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;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
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];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
function defaultOnError(err) {
throw err;
}
//Allow getting a global that is expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
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') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite an existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
//Defaults. Do not set a default for map
//config to speed up normalize(), which
//will run faster if there is no default.
waitSeconds: 7,
baseUrl: './',
paths: {},
bundles: {},
pkgs: {},
shim: {},
config: {}
},
registry = {},
//registry of just enabled modules, to speed
//cycle breaking code when lots of modules
//are registered, but not activated.
enabledRegistry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
bundlesMap = {},
requireCounter = 1,
unnormalizedCounter = 1;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; i < ary.length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
baseParts = (baseName && baseName.split('/')),
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name) {
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
// Starts with a '.' so need the baseName
if (name[0].charAt(0) === '.' && baseParts) {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
name = normalizedBaseParts.concat(name);
}
trimDots(name);
name = name.join('/');
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = getOwn(mapValue, nameSegment);
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break outerLoop;
}
}
}
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
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('/');
}
}
// If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : 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) {
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
//Custom require that does not do map translation, since
//ID is "absolute", already mapped/resolved.
context.makeRequire(null, {
skipMap: true
})([id]);
return true;
}
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
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];
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix, nameParts,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
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);
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
// If nested plugin references, then do not try to
// normalize, as it will not normalize correctly. This
// places a restriction on resourceIds, and the longer
// term solution is not to normalize until plugins are
// loaded and all normalizations to allow for async
// loading of a loader plugin. But for now, fixes the
// common uses. Details in #1131
normalizedName = name.indexOf('!') === -1 ?
normalize(name, parentName, applyMap) :
name;
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
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) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
each(globalDefQueue, function(queueItem) {
var id = queueItem[0];
if (typeof id === 'string') {
context.defQueueMap[id] = true;
}
defQueue.push(queueItem);
});
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 (defined[mod.map.id] = 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 () {
return getOwn(config.config, mod.map.id) || {};
},
exports: mod.exports || (mod.exports = {})
});
}
}
};
function cleanRegistry(id) {
//Clean up machinery used for waiting modules.
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);
//Only force things that have not completed
//being defined, so still in the registry,
//and only if it has not been matched up
//in the module already.
if (dep && !mod.depMatched[i] && !processed[depId]) {
if (getOwn(traced, depId)) {
mod.defineDep(i, defined[depId]);
mod.check(); //pass false?
} else {
breakCycle(dep, traced, processed);
}
}
});
processed[id] = true;
}
}
function checkLoaded() {
var err, usingPathFallback,
waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = [],
reqCalls = [],
stillLoading = false,
needCycleCheck = true;
//Do not bother if this call was a result of a cycle break.
if (inCheckLoaded) {
return;
}
inCheckLoaded = true;
//Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) {
var map = mod.map,
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
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) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
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;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
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 the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
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) {
// Only fetch if not already in the defQueue.
if (!hasProp(context.defQueueMap, id)) {
this.fetch();
}
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
// Favor return value over exports. If node/cjs in play,
// then will not have a return value anyway. Favor
// module.exports assignment over exports object.
if (this.map.isDefine && exports === undefined) {
cjsModule = this.module;
if (cjsModule) {
exports = cjsModule.exports;
} else if (this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
// If there is an error listener, favor passing
// to that instead of throwing an error. However,
// only do it for define()'d modules. require
// errbacks should not be called for failures in
// their callbacks (#699). However if a global
// onError is set, use that.
if ((this.events.error && this.map.isDefine) ||
req.onError !== defaultOnError) {
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 if (typeof console !== 'undefined' &&
console.error) {
// Log the error for debugging. If promises could be
// used, this would be different, but making do.
console.error(err);
} else {
// Do not want to completely lose the error. While this
// will mess up processing and lead to similar results
// as bug 1440, it at least surfaces the error.
req.onError(err);
}
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
var resLoadMaps = [];
each(this.depMaps, function (depMap) {
resLoadMaps.push(depMap.normalizedMap || depMap);
});
req.onResourceLoad(context, this.map, resLoadMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
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,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
bundleId = getOwn(bundlesMap, this.map.id),
name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, {
enableBuildCallback: true
});
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) {
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
//prefix and name should already be normalized, no need
//for applying map config again either.
normalizedMap = makeModuleMap(map.prefix + '!' + name,
this.map.parentMap);
on(normalizedMap,
'defined', bind(this, function (value) {
this.map.normalizedMap = normalizedMap;
this.init([], function () { return value; }, null, {
enabled: true,
ignore: true
});
}));
normalizedMod = getOwn(registry, normalizedMap.id);
if (normalizedMod) {
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(normalizedMap);
if (this.events.error) {
normalizedMod.on('error', bind(this, function (err) {
this.emit('error', err);
}));
}
normalizedMod.enable();
}
return;
}
//If a paths config, then just load that file instead to
//resolve the plugin, as it is built into that paths layer.
if (bundleId) {
this.map.url = context.nameToUrl(bundleId);
this.load();
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];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
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;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
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;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
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) {
if (this.undefed) {
return;
}
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', bind(this, this.errback));
} else if (this.events.error) {
// No direct errback on this module, but something
// else is listening for errors, so be sure to
// propagate the error correctly.
on(depMap, 'error', bind(this, function(err) {
this.emit('error', err);
}));
}
}
id = depMap.id;
mod = registry[id];
//Skip special modules like 'require', 'exports', 'module'
//Also, don't call enable if it is already enabled,
//important in circular dependency cases.
if (!hasProp(handlers, id) && mod && !mod.enabled) {
context.enable(depMap, this);
}
}));
//Enable each plugin that is used in
//a dependency
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') {
//Now that the error handler was triggered, remove
//the listeners, since this broken Module instance
//can stay around for a while in the registry.
delete this.events[name];
}
}
};
function callGetModule(args) {
//Skip modules already defined.
if (!hasProp(defined, args[0])) {
getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
}
}
function removeListener(node, func, name, ieName) {
//Favor detachEvent because of IE9
//issue, see attachEvent/addEventListener comment elsewhere
//in this file.
if (node.detachEvent && !isOpera) {
//Probably IE. If not it will throw an error, which will be
//useful to know.
if (ieName) {
node.detachEvent(ieName, func);
}
} else {
node.removeEventListener(name, func, false);
}
}
/**
* Given an event from a script node, get the requirejs info from it,
* and then removes the event listeners on the node.
* @param {Event} evt
* @returns {Object}
*/
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
function intakeDefines() {
var args;
//Any defined modules in the global queue, intake them now.
takeGlobalQueue();
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' +
args[args.length - 1]));
} else {
//args are id, deps, factory. Should be normalized by the
//define() function.
callGetModule(args);
}
}
context.defQueueMap = {};
}
context = {
config: config,
contextName: contextName,
registry: registry,
defined: defined,
urlFetched: urlFetched,
defQueue: defQueue,
defQueueMap: {},
Module: Module,
makeModuleMap: makeModuleMap,
nextTick: req.nextTick,
onError: onError,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
//Save off the paths since they require special processing,
//they are additive.
var shim = config.shim,
objs = {
paths: true,
bundles: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (!config[prop]) {
config[prop] = {};
}
mixin(config[prop], value, true, true);
} else {
config[prop] = value;
}
});
//Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
each(value, function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
//Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
//Normalize the structure
if (isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = context.makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
//Adjust packages if necessary.
if (cfg.packages) {
each(cfg.packages, function (pkgObj) {
var location, name;
pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj;
name = pkgObj.name;
location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
//Save pointer to main module ID for pkg name.
//Remove leading dot in main, so main paths are normalized,
//and remove any trailing .js, since different package
//envs have different conventions: some use a module name,
//some use a file name.
config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '');
});
}
//If there are any "waiting to execute" modules in the registry,
//update the maps for them, since their info, like URLs to load,
//may have changed.
eachProp(registry, function (mod, id) {
//If module already has init called, since it is too
//late to modify them, and ignore unnormalized ones
//since they are transient.
if (!mod.inited && !mod.map.unnormalized) {
mod.map = makeModuleMap(id, null, true);
}
});
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
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)) {
//Invalid call
return onError(makeError('requireargs', 'Invalid require call'), errback);
}
//If require|exports|module are requested, get the
//value for them from the special handlers. Caveat:
//this only works while module is being defined.
if (relMap && hasProp(handlers, deps)) {
return handlers[deps](registry[relMap.id]);
}
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
if (req.get) {
return req.get(context, deps, relMap, localRequire);
}
//Normalize module name, if it contains . or ..
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];
}
//Grab defines waiting in the global queue.
intakeDefines();
//Mark all the dependencies as needing to be loaded.
context.nextTick(function () {
//Some defines could have been added since the
//require call, collect them.
intakeDefines();
requireMod = getModule(makeModuleMap(null, relMap));
//Store if map config should be applied to this require
//call for dependencies.
requireMod.skipMap = options.skipMap;
requireMod.init(deps, callback, errback, {
enabled: true
});
checkLoaded();
});
return localRequire;
}
mixin(localRequire, {
isBrowser: isBrowser,
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt) {
var ext,
index = moduleNamePlusExt.lastIndexOf('.'),
segment = moduleNamePlusExt.split('/')[0],
isRelative = segment === '.' || segment === '..';
//Have a file extension alias, and it is not the
//dots from a relative path.
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);
}
});
//Only allow undef on top level require calls
if (!relMap) {
localRequire.undef = function (id) {
//Bind any waiting define() calls to this context,
//fix for #408
takeGlobalQueue();
var map = makeModuleMap(id, relMap, true),
mod = getOwn(registry, id);
mod.undefed = true;
removeScript(id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
//Clean queued defines too. Go backwards
//in array so that the splices do not
//mess up the iteration.
eachReverse(defQueue, function(args, i) {
if (args[0] === id) {
defQueue.splice(i, 1);
}
});
delete context.defQueueMap[id];
if (mod) {
//Hold on to listeners in case the
//module will be attempted to be reloaded
//using a different config.
if (mod.events.defined) {
undefEvents[id] = mod.events;
}
cleanRegistry(id);
}
};
}
return localRequire;
},
/**
* Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overridden by
* the optimizer. Not shown here to keep code compact.
*/
enable: function (depMap) {
var mod = getOwn(registry, depMap.id);
if (mod) {
getModule(depMap).enable();
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
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 already found an anonymous module and bound it
//to this name, then this is some other anon module
//waiting for its completeLoad to fire.
if (found) {
break;
}
found = true;
} else if (args[0] === moduleName) {
//Found matching define call for this script!
found = true;
}
callGetModule(args);
}
context.defQueueMap = {};
//Do this after the cycle of callGetModule in case the result
//of those calls/init calls changes the registry.
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 {
//A script that does not call define(), so just simulate
//the call for it.
callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
}
}
checkLoaded();
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
* Note that it **does not** call normalize on the moduleName,
* it is assumed to have already been normalized. This is an
* internal API, not a public one. Use toUrl for the public API.
*/
nameToUrl: function (moduleName, ext, skipExt) {
var paths, syms, i, parentModule, url,
parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return context.nameToUrl(bundleId, ext, skipExt);
}
//If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
//or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked.
url = moduleName + (ext || '');
} else {
//A module that needs to be converted to a path.
paths = config.paths;
syms = moduleName.split('/');
//For each module name segment, see if there is a path
//registered for it. Start with most specific name
//and work up from it.
for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/');
parentPath = getOwn(paths, parentModule);
if (parentPath) {
//If an array, it means there are a few choices,
//Choose the one that is desired
if (isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
break;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callback function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
var parents = [];
eachProp(registry, function(value, key) {
if (key.indexOf('_@r') !== 0) {
each(value.depMaps, function(depMap) {
if (depMap.id === data.id) {
parents.push(key);
}
return true;
});
}
});
return onError(makeError('scripterror', 'Script error for "' + data.id +
(parents.length ?
'", needed by: ' + parents.join(', ') :
'"'), evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
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);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = defaultOnError;
/**
* Creates the node for the load command. Only used in browser envs.
*/
req.createNode = function (config, moduleName, url) {
var 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;
return node;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = req.createNode(config, moduleName, url);
if (config.onNodeCreated) {
config.onNodeCreated(node, config, moduleName, url);
}
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/jrburke/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/jrburke/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation is that a build has been done so
//that only one script needs to be loaded anyway. This may need
//to be reevaluated if other use cases become common.
importScripts(url);
//Account for anonymous modules
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;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser && !cfg.skipDataMain) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Preserve dataMain in case it is a path (i.e. contains '?')
mainScript = dataMain;
//Set final baseUrl if there is not already an explicit one.
if (!cfg.baseUrl) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = mainScript.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
}
//Strip off any trailing .js since mainScript is now
//like a module name.
mainScript = mainScript.replace(jsSuffixRegExp, '');
//If mainScript is still a path, fall back to dataMain
if (req.jsExtRegExp.test(mainScript)) {
mainScript = dataMain;
}
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = null;
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
deps = [];
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
if (context) {
context.defQueue.push([name, deps, callback]);
context.defQueueMap[name] = true;
} else {
globalDefQueue.push([name, deps, callback]);
}
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this)); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/requirejs/require.js | require.js |
!function(){var a,AbstractChosen,Chosen,SelectParser,b,c={}.hasOwnProperty,d=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a};SelectParser=function(){function SelectParser(){this.options_index=0,this.parsed=[]}return SelectParser.prototype.add_node=function(a){return"OPTGROUP"===a.nodeName.toUpperCase()?this.add_group(a):this.add_option(a)},SelectParser.prototype.add_group=function(a){var b,c,d,e,f,g;for(b=this.parsed.length,this.parsed.push({array_index:b,group:!0,label:this.escapeExpression(a.label),children:0,disabled:a.disabled}),f=a.childNodes,g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(this.add_option(c,b,a.disabled));return g},SelectParser.prototype.add_option=function(a,b,c){return"OPTION"===a.nodeName.toUpperCase()?(""!==a.text?(null!=b&&(this.parsed[b].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:a.value,text:a.text,html:a.innerHTML,selected:a.selected,disabled:c===!0?c:a.disabled,group_array_index:b,classes:a.className,style:a.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1):void 0},SelectParser.prototype.escapeExpression=function(a){var b,c;return null==a||a===!1?"":/[\&\<\>\"\'\`]/.test(a)?(b={"<":"<",">":">",'"':""","'":"'","`":"`"},c=/&(?!\w+;)|[\<\>\"\'\`]/g,a.replace(c,function(a){return b[a]||"&"})):a},SelectParser}(),SelectParser.select_to_array=function(a){var b,c,d,e,f;for(c=new SelectParser,f=a.childNodes,d=0,e=f.length;e>d;d++)b=f[d],c.add_node(b);return c.parsed},AbstractChosen=function(){function AbstractChosen(a,b){this.form_field=a,this.options=null!=b?b:{},AbstractChosen.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers())}return AbstractChosen.prototype.set_default_values=function(){var a=this;return this.click_test_action=function(b){return a.test_active_click(b)},this.activate_action=function(b){return a.activate_field(b)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0},AbstractChosen.prototype.set_default_text=function(){return this.default_text=this.form_field.getAttribute("data-placeholder")?this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.options.placeholder_text_multiple||this.options.placeholder_text||AbstractChosen.default_multiple_text:this.options.placeholder_text_single||this.options.placeholder_text||AbstractChosen.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||AbstractChosen.default_no_result_text},AbstractChosen.prototype.mouse_enter=function(){return this.mouse_on_container=!0},AbstractChosen.prototype.mouse_leave=function(){return this.mouse_on_container=!1},AbstractChosen.prototype.input_focus=function(){var a=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return a.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},AbstractChosen.prototype.input_blur=function(){var a=this;return this.mouse_on_container?void 0:(this.active_field=!1,setTimeout(function(){return a.blur_test()},100))},AbstractChosen.prototype.results_option_build=function(a){var b,c,d,e,f;for(b="",f=this.results_data,d=0,e=f.length;e>d;d++)c=f[d],b+=c.group?this.result_add_group(c):this.result_add_option(c),(null!=a?a.first:void 0)&&(c.selected&&this.is_multiple?this.choice_build(c):c.selected&&!this.is_multiple&&this.single_set_selected_text(c.text));return b},AbstractChosen.prototype.result_add_option=function(a){var b,c;return a.search_match?this.include_option_in_results(a)?(b=[],a.disabled||a.selected&&this.is_multiple||b.push("active-result"),!a.disabled||a.selected&&this.is_multiple||b.push("disabled-result"),a.selected&&b.push("result-selected"),null!=a.group_array_index&&b.push("group-option"),""!==a.classes&&b.push(a.classes),c=document.createElement("li"),c.className=b.join(" "),c.style.cssText=a.style,c.setAttribute("data-option-array-index",a.array_index),c.innerHTML=a.search_text,this.outerHTML(c)):"":""},AbstractChosen.prototype.result_add_group=function(a){var b;return a.search_match||a.group_match?a.active_options>0?(b=document.createElement("li"),b.className="group-result",b.innerHTML=a.search_text,this.outerHTML(b)):"":""},AbstractChosen.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},AbstractChosen.prototype.reset_single_select_options=function(){var a,b,c,d,e;for(d=this.results_data,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.selected?e.push(a.selected=!1):e.push(void 0);return e},AbstractChosen.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},AbstractChosen.prototype.results_search=function(){return this.results_showing?this.winnow_results():this.results_show()},AbstractChosen.prototype.winnow_results=function(){var a,b,c,d,e,f,g,h,i,j,k,l,m;for(this.no_results_clear(),e=0,g=this.get_search_text(),a=g.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),d=this.search_contains?"":"^",c=new RegExp(d+a,"i"),j=new RegExp(a,"i"),m=this.results_data,k=0,l=m.length;l>k;k++)b=m[k],b.search_match=!1,f=null,this.include_option_in_results(b)&&(b.group&&(b.group_match=!1,b.active_options=0),null!=b.group_array_index&&this.results_data[b.group_array_index]&&(f=this.results_data[b.group_array_index],0===f.active_options&&f.search_match&&(e+=1),f.active_options+=1),(!b.group||this.group_search)&&(b.search_text=b.group?b.label:b.html,b.search_match=this.search_string_match(b.search_text,c),b.search_match&&!b.group&&(e+=1),b.search_match?(g.length&&(h=b.search_text.search(j),i=b.search_text.substr(0,h+g.length)+"</em>"+b.search_text.substr(h+g.length),b.search_text=i.substr(0,h)+"<em>"+i.substr(h)),null!=f&&(f.group_match=!0)):null!=b.group_array_index&&this.results_data[b.group_array_index].search_match&&(b.search_match=!0)));return this.result_clear_highlight(),1>e&&g.length?(this.update_results_content(""),this.no_results(g)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},AbstractChosen.prototype.search_string_match=function(a,b){var c,d,e,f;if(b.test(a))return!0;if(this.enable_split_word_search&&(a.indexOf(" ")>=0||0===a.indexOf("["))&&(d=a.replace(/\[|\]/g,"").split(" "),d.length))for(e=0,f=d.length;f>e;e++)if(c=d[e],b.test(c))return!0},AbstractChosen.prototype.choices_count=function(){var a,b,c,d;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,d=this.form_field.options,b=0,c=d.length;c>b;b++)a=d[b],a.selected&&(this.selected_option_count+=1);return this.selected_option_count},AbstractChosen.prototype.choices_click=function(a){return a.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},AbstractChosen.prototype.keyup_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),b){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(a.preventDefault(),this.results_showing)return this.result_select(a);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},AbstractChosen.prototype.clipboard_event_checker=function(){var a=this;return setTimeout(function(){return a.results_search()},50)},AbstractChosen.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},AbstractChosen.prototype.include_option_in_results=function(a){return this.is_multiple&&!this.display_selected_options&&a.selected?!1:!this.display_disabled_options&&a.disabled?!1:a.empty?!1:!0},AbstractChosen.prototype.search_results_touchstart=function(a){return this.touch_started=!0,this.search_results_mouseover(a)},AbstractChosen.prototype.search_results_touchmove=function(a){return this.touch_started=!1,this.search_results_mouseout(a)},AbstractChosen.prototype.search_results_touchend=function(a){return this.touch_started?this.search_results_mouseup(a):void 0},AbstractChosen.prototype.outerHTML=function(a){var b;return a.outerHTML?a.outerHTML:(b=document.createElement("div"),b.appendChild(a),b.innerHTML)},AbstractChosen.browser_is_supported=function(){return"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:/iP(od|hone)/i.test(window.navigator.userAgent)?!1:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!1:!0},AbstractChosen.default_multiple_text="Select Some Options",AbstractChosen.default_single_text="Select an Option",AbstractChosen.default_no_result_text="No results match",AbstractChosen}(),a=jQuery,a.fn.extend({chosen:function(b){return AbstractChosen.browser_is_supported()?this.each(function(){var c,d;c=a(this),d=c.data("chosen"),"destroy"===b&&d?d.destroy():d||c.data("chosen",new Chosen(this,b))}):this}}),Chosen=function(c){function Chosen(){return b=Chosen.__super__.constructor.apply(this,arguments)}return d(Chosen,c),Chosen.prototype.setup=function(){return this.form_field_jq=a(this.form_field),this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")},Chosen.prototype.set_up_html=function(){var b,c;return b=["chosen-container"],b.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&b.push(this.form_field.className),this.is_rtl&&b.push("chosen-rtl"),c={"class":b.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(c.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=a("<div />",c),this.is_multiple?this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'):this.container.html('<a class="chosen-single chosen-default" tabindex="-1"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'),this.form_field_jq.hide().after(this.container),this.dropdown=this.container.find("div.chosen-drop").first(),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chosen-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chosen-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chosen-search").first(),this.selected_item=this.container.find(".chosen-single").first()),this.results_build(),this.set_tab_index(),this.set_label_behavior(),this.form_field_jq.trigger("chosen:ready",{chosen:this})},Chosen.prototype.register_observers=function(){var a=this;return this.container.bind("mousedown.chosen",function(b){a.container_mousedown(b)}),this.container.bind("mouseup.chosen",function(b){a.container_mouseup(b)}),this.container.bind("mouseenter.chosen",function(b){a.mouse_enter(b)}),this.container.bind("mouseleave.chosen",function(b){a.mouse_leave(b)}),this.search_results.bind("mouseup.chosen",function(b){a.search_results_mouseup(b)}),this.search_results.bind("mouseover.chosen",function(b){a.search_results_mouseover(b)}),this.search_results.bind("mouseout.chosen",function(b){a.search_results_mouseout(b)}),this.search_results.bind("mousewheel.chosen DOMMouseScroll.chosen",function(b){a.search_results_mousewheel(b)}),this.search_results.bind("touchstart.chosen",function(b){a.search_results_touchstart(b)}),this.search_results.bind("touchmove.chosen",function(b){a.search_results_touchmove(b)}),this.search_results.bind("touchend.chosen",function(b){a.search_results_touchend(b)}),this.form_field_jq.bind("chosen:updated.chosen",function(b){a.results_update_field(b)}),this.form_field_jq.bind("chosen:activate.chosen",function(b){a.activate_field(b)}),this.form_field_jq.bind("chosen:open.chosen",function(b){a.container_mousedown(b)}),this.form_field_jq.bind("chosen:close.chosen",function(b){a.input_blur(b)}),this.search_field.bind("blur.chosen",function(b){a.input_blur(b)}),this.search_field.bind("keyup.chosen",function(b){a.keyup_checker(b)}),this.search_field.bind("keydown.chosen",function(b){a.keydown_checker(b)}),this.search_field.bind("focus.chosen",function(b){a.input_focus(b)}),this.search_field.bind("cut.chosen",function(b){a.clipboard_event_checker(b)}),this.search_field.bind("paste.chosen",function(b){a.clipboard_event_checker(b)}),this.is_multiple?this.search_choices.bind("click.chosen",function(b){a.choices_click(b)}):this.container.bind("click.chosen",function(a){a.preventDefault()})},Chosen.prototype.destroy=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.search_field[0].tabIndex&&(this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex),this.container.remove(),this.form_field_jq.removeData("chosen"),this.form_field_jq.show()},Chosen.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field_jq[0].disabled,this.is_disabled?(this.container.addClass("chosen-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus.chosen",this.activate_action),this.close_field()):(this.container.removeClass("chosen-disabled"),this.search_field[0].disabled=!1,this.is_multiple?void 0:this.selected_item.bind("focus.chosen",this.activate_action))},Chosen.prototype.container_mousedown=function(b){return this.is_disabled||(b&&"mousedown"===b.type&&!this.results_showing&&b.preventDefault(),null!=b&&a(b.target).hasClass("search-choice-close"))?void 0:(this.active_field?this.is_multiple||!b||a(b.target)[0]!==this.selected_item[0]&&!a(b.target).parents("a.chosen-single").length||(b.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),a(this.container[0].ownerDocument).bind("click.chosen",this.click_test_action),this.results_show()),this.activate_field())},Chosen.prototype.container_mouseup=function(a){return"ABBR"!==a.target.nodeName||this.is_disabled?void 0:this.results_reset(a)},Chosen.prototype.search_results_mousewheel=function(a){var b;return a.originalEvent&&(b=-a.originalEvent.wheelDelta||a.originalEvent.detail),null!=b?(a.preventDefault(),"DOMMouseScroll"===a.type&&(b=40*b),this.search_results.scrollTop(b+this.search_results.scrollTop())):void 0},Chosen.prototype.blur_test=function(){return!this.active_field&&this.container.hasClass("chosen-container-active")?this.close_field():void 0},Chosen.prototype.close_field=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},Chosen.prototype.activate_field=function(){return this.container.addClass("chosen-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},Chosen.prototype.test_active_click=function(b){var c;return c=a(b.target).closest(".chosen-container"),c.length&&this.container[0]===c[0]?this.active_field=!0:this.close_field()},Chosen.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=SelectParser.select_to_array(this.form_field),this.is_multiple?this.search_choices.find("li.search-choice").remove():this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field[0].readOnly=!0,this.container.addClass("chosen-container-single-nosearch")):(this.search_field[0].readOnly=!1,this.container.removeClass("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},Chosen.prototype.result_do_highlight=function(a){var b,c,d,e,f;if(a.length){if(this.result_clear_highlight(),this.result_highlight=a,this.result_highlight.addClass("highlighted"),d=parseInt(this.search_results.css("maxHeight"),10),f=this.search_results.scrollTop(),e=d+f,c=this.result_highlight.position().top+this.search_results.scrollTop(),b=c+this.result_highlight.outerHeight(),b>=e)return this.search_results.scrollTop(b-d>0?b-d:0);if(f>c)return this.search_results.scrollTop(c)}},Chosen.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},Chosen.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.container.addClass("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results(),this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this}))},Chosen.prototype.update_results_content=function(a){return this.search_results.html(a)},Chosen.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClass("chosen-with-drop"),this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},Chosen.prototype.set_tab_index=function(){var a;return this.form_field.tabIndex?(a=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field[0].tabIndex=a):void 0},Chosen.prototype.set_label_behavior=function(){var b=this;return this.form_field_label=this.form_field_jq.parents("label"),!this.form_field_label.length&&this.form_field.id.length&&(this.form_field_label=a("label[for='"+this.form_field.id+"']")),this.form_field_label.length>0?this.form_field_label.bind("click.chosen",function(a){return b.is_multiple?b.container_mousedown(a):b.activate_field()}):void 0},Chosen.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},Chosen.prototype.search_results_mouseup=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c.length?(this.result_highlight=c,this.result_select(b),this.search_field.focus()):void 0},Chosen.prototype.search_results_mouseover=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c?this.result_do_highlight(c):void 0},Chosen.prototype.search_results_mouseout=function(b){return a(b.target).hasClass("active-result")?this.result_clear_highlight():void 0},Chosen.prototype.choice_build=function(b){var c,d,e=this;return c=a("<li />",{"class":"search-choice"}).html("<span>"+b.html+"</span>"),b.disabled?c.addClass("search-choice-disabled"):(d=a("<a />",{"class":"search-choice-close","data-option-array-index":b.array_index}),d.bind("click.chosen",function(a){return e.choice_destroy_link_click(a)}),c.append(d)),this.search_container.before(c)},Chosen.prototype.choice_destroy_link_click=function(b){return b.preventDefault(),b.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(a(b.target))},Chosen.prototype.choice_destroy=function(a){return this.result_deselect(a[0].getAttribute("data-option-array-index"))?(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1&&this.results_hide(),a.parents("li").first().remove(),this.search_field_scale()):void 0},Chosen.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change"),this.active_field?this.results_hide():void 0},Chosen.prototype.results_reset_cleanup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.selected_item.find("abbr").remove()},Chosen.prototype.result_select=function(a){var b,c;return this.result_highlight?(b=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?b.removeClass("active-result"):this.reset_single_select_options(),c=this.results_data[b[0].getAttribute("data-option-array-index")],c.selected=!0,this.form_field.options[c.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(c):this.single_set_selected_text(c.text),(a.metaKey||a.ctrlKey)&&this.is_multiple||this.results_hide(),this.search_field.val(""),(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[c.options_index].value}),this.current_selectedIndex=this.form_field.selectedIndex,this.search_field_scale())):void 0},Chosen.prototype.single_set_selected_text=function(a){return null==a&&(a=this.default_text),a===this.default_text?this.selected_item.addClass("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClass("chosen-default")),this.selected_item.find("span").text(a)},Chosen.prototype.result_deselect=function(a){var b;return b=this.results_data[a],this.form_field.options[b.options_index].disabled?!1:(b.selected=!1,this.form_field.options[b.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[b.options_index].value}),this.search_field_scale(),!0)},Chosen.prototype.single_deselect_control_build=function(){return this.allow_single_deselect?(this.selected_item.find("abbr").length||this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>'),this.selected_item.addClass("chosen-single-with-deselect")):void 0},Chosen.prototype.get_search_text=function(){return this.search_field.val()===this.default_text?"":a("<div/>").text(a.trim(this.search_field.val())).html()},Chosen.prototype.winnow_results_set_highlight=function(){var a,b;return b=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),a=b.length?b.first():this.search_results.find(".active-result").first(),null!=a?this.result_do_highlight(a):void 0},Chosen.prototype.no_results=function(b){var c;return c=a('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),c.find("span").first().html(b),this.search_results.append(c),this.form_field_jq.trigger("chosen:no_results",{chosen:this})},Chosen.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},Chosen.prototype.keydown_arrow=function(){var a;return this.results_showing&&this.result_highlight?(a=this.result_highlight.nextAll("li.active-result").first())?this.result_do_highlight(a):void 0:this.results_show()},Chosen.prototype.keyup_arrow=function(){var a;return this.results_showing||this.is_multiple?this.result_highlight?(a=this.result_highlight.prevAll("li.active-result"),a.length?this.result_do_highlight(a.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},Chosen.prototype.keydown_backstroke=function(){var a;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke()):(a=this.search_container.siblings("li.search-choice").last(),a.length&&!a.hasClass("search-choice-disabled")?(this.pending_backstroke=a,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")):void 0)},Chosen.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},Chosen.prototype.keydown_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),8!==b&&this.pending_backstroke&&this.clear_backstroke(),b){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(a),this.mouse_on_container=!1;break;case 13:a.preventDefault();break;case 38:a.preventDefault(),this.keyup_arrow();break;case 40:a.preventDefault(),this.keydown_arrow()}},Chosen.prototype.search_field_scale=function(){var b,c,d,e,f,g,h,i,j;if(this.is_multiple){for(d=0,h=0,f="position:absolute; left: -1000px; top: -1000px; display:none;",g=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],i=0,j=g.length;j>i;i++)e=g[i],f+=e+":"+this.search_field.css(e)+";";return b=a("<div />",{style:f}),b.text(this.search_field.val()),a("body").append(b),h=b.width()+25,b.remove(),c=this.container.outerWidth(),h>c-10&&(h=c-10),this.search_field.css({width:h+"px"})}},Chosen}(AbstractChosen)}.call(this); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/chosen/chosen.jquery.min.js | chosen.jquery.min.js |
(function() {
var $, AbstractChosen, Chosen, SelectParser, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
SelectParser = (function() {
function SelectParser() {
this.options_index = 0;
this.parsed = [];
}
SelectParser.prototype.add_node = function(child) {
if (child.nodeName.toUpperCase() === "OPTGROUP") {
return this.add_group(child);
} else {
return this.add_option(child);
}
};
SelectParser.prototype.add_group = function(group) {
var group_position, option, _i, _len, _ref, _results;
group_position = this.parsed.length;
this.parsed.push({
array_index: group_position,
group: true,
label: this.escapeExpression(group.label),
children: 0,
disabled: group.disabled
});
_ref = group.childNodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
_results.push(this.add_option(option, group_position, group.disabled));
}
return _results;
};
SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
if (option.nodeName.toUpperCase() === "OPTION") {
if (option.text !== "") {
if (group_position != null) {
this.parsed[group_position].children += 1;
}
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
value: option.value,
text: option.text,
html: option.innerHTML,
selected: option.selected,
disabled: group_disabled === true ? group_disabled : option.disabled,
group_array_index: group_position,
classes: option.className,
style: option.style.cssText
});
} else {
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
empty: true
});
}
return this.options_index += 1;
}
};
SelectParser.prototype.escapeExpression = function(text) {
var map, unsafe_chars;
if ((text == null) || text === false) {
return "";
}
if (!/[\&\<\>\"\'\`]/.test(text)) {
return text;
}
map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
};
unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g;
return text.replace(unsafe_chars, function(chr) {
return map[chr] || "&";
});
};
return SelectParser;
})();
SelectParser.select_to_array = function(select) {
var child, parser, _i, _len, _ref;
parser = new SelectParser();
_ref = select.childNodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
parser.add_node(child);
}
return parser.parsed;
};
AbstractChosen = (function() {
function AbstractChosen(form_field, options) {
this.form_field = form_field;
this.options = options != null ? options : {};
if (!AbstractChosen.browser_is_supported()) {
return;
}
this.is_multiple = this.form_field.multiple;
this.set_default_text();
this.set_default_values();
this.setup();
this.set_up_html();
this.register_observers();
}
AbstractChosen.prototype.set_default_values = function() {
var _this = this;
this.click_test_action = function(evt) {
return _this.test_active_click(evt);
};
this.activate_action = function(evt) {
return _this.activate_field(evt);
};
this.active_field = false;
this.mouse_on_container = false;
this.results_showing = false;
this.result_highlighted = null;
this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
this.disable_search_threshold = this.options.disable_search_threshold || 0;
this.disable_search = this.options.disable_search || false;
this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
this.group_search = this.options.group_search != null ? this.options.group_search : true;
this.search_contains = this.options.search_contains || false;
this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
this.max_selected_options = this.options.max_selected_options || Infinity;
this.inherit_select_classes = this.options.inherit_select_classes || false;
this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
return this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
};
AbstractChosen.prototype.set_default_text = function() {
if (this.form_field.getAttribute("data-placeholder")) {
this.default_text = this.form_field.getAttribute("data-placeholder");
} else if (this.is_multiple) {
this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
} else {
this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
}
return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
};
AbstractChosen.prototype.mouse_enter = function() {
return this.mouse_on_container = true;
};
AbstractChosen.prototype.mouse_leave = function() {
return this.mouse_on_container = false;
};
AbstractChosen.prototype.input_focus = function(evt) {
var _this = this;
if (this.is_multiple) {
if (!this.active_field) {
return setTimeout((function() {
return _this.container_mousedown();
}), 50);
}
} else {
if (!this.active_field) {
return this.activate_field();
}
}
};
AbstractChosen.prototype.input_blur = function(evt) {
var _this = this;
if (!this.mouse_on_container) {
this.active_field = false;
return setTimeout((function() {
return _this.blur_test();
}), 100);
}
};
AbstractChosen.prototype.results_option_build = function(options) {
var content, data, _i, _len, _ref;
content = '';
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
if (data.group) {
content += this.result_add_group(data);
} else {
content += this.result_add_option(data);
}
if (options != null ? options.first : void 0) {
if (data.selected && this.is_multiple) {
this.choice_build(data);
} else if (data.selected && !this.is_multiple) {
this.single_set_selected_text(data.text);
}
}
}
return content;
};
AbstractChosen.prototype.result_add_option = function(option) {
var classes, option_el;
if (!option.search_match) {
return '';
}
if (!this.include_option_in_results(option)) {
return '';
}
classes = [];
if (!option.disabled && !(option.selected && this.is_multiple)) {
classes.push("active-result");
}
if (option.disabled && !(option.selected && this.is_multiple)) {
classes.push("disabled-result");
}
if (option.selected) {
classes.push("result-selected");
}
if (option.group_array_index != null) {
classes.push("group-option");
}
if (option.classes !== "") {
classes.push(option.classes);
}
option_el = document.createElement("li");
option_el.className = classes.join(" ");
option_el.style.cssText = option.style;
option_el.setAttribute("data-option-array-index", option.array_index);
option_el.innerHTML = option.search_text;
return this.outerHTML(option_el);
};
AbstractChosen.prototype.result_add_group = function(group) {
var group_el;
if (!(group.search_match || group.group_match)) {
return '';
}
if (!(group.active_options > 0)) {
return '';
}
group_el = document.createElement("li");
group_el.className = "group-result";
group_el.innerHTML = group.search_text;
return this.outerHTML(group_el);
};
AbstractChosen.prototype.results_update_field = function() {
this.set_default_text();
if (!this.is_multiple) {
this.results_reset_cleanup();
}
this.result_clear_highlight();
this.results_build();
if (this.results_showing) {
return this.winnow_results();
}
};
AbstractChosen.prototype.reset_single_select_options = function() {
var result, _i, _len, _ref, _results;
_ref = this.results_data;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
result = _ref[_i];
if (result.selected) {
_results.push(result.selected = false);
} else {
_results.push(void 0);
}
}
return _results;
};
AbstractChosen.prototype.results_toggle = function() {
if (this.results_showing) {
return this.results_hide();
} else {
return this.results_show();
}
};
AbstractChosen.prototype.results_search = function(evt) {
if (this.results_showing) {
return this.winnow_results();
} else {
return this.results_show();
}
};
AbstractChosen.prototype.winnow_results = function() {
var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
this.no_results_clear();
results = 0;
searchText = this.get_search_text();
escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
regexAnchor = this.search_contains ? "" : "^";
regex = new RegExp(regexAnchor + escapedSearchText, 'i');
zregex = new RegExp(escapedSearchText, 'i');
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
option.search_match = false;
results_group = null;
if (this.include_option_in_results(option)) {
if (option.group) {
option.group_match = false;
option.active_options = 0;
}
if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
results_group = this.results_data[option.group_array_index];
if (results_group.active_options === 0 && results_group.search_match) {
results += 1;
}
results_group.active_options += 1;
}
if (!(option.group && !this.group_search)) {
option.search_text = option.group ? option.label : option.html;
option.search_match = this.search_string_match(option.search_text, regex);
if (option.search_match && !option.group) {
results += 1;
}
if (option.search_match) {
if (searchText.length) {
startpos = option.search_text.search(zregex);
text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
}
if (results_group != null) {
results_group.group_match = true;
}
} else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
option.search_match = true;
}
}
}
}
this.result_clear_highlight();
if (results < 1 && searchText.length) {
this.update_results_content("");
return this.no_results(searchText);
} else {
this.update_results_content(this.results_option_build());
return this.winnow_results_set_highlight();
}
};
AbstractChosen.prototype.search_string_match = function(search_string, regex) {
var part, parts, _i, _len;
if (regex.test(search_string)) {
return true;
} else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) {
parts = search_string.replace(/\[|\]/g, "").split(" ");
if (parts.length) {
for (_i = 0, _len = parts.length; _i < _len; _i++) {
part = parts[_i];
if (regex.test(part)) {
return true;
}
}
}
}
};
AbstractChosen.prototype.choices_count = function() {
var option, _i, _len, _ref;
if (this.selected_option_count != null) {
return this.selected_option_count;
}
this.selected_option_count = 0;
_ref = this.form_field.options;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
if (option.selected) {
this.selected_option_count += 1;
}
}
return this.selected_option_count;
};
AbstractChosen.prototype.choices_click = function(evt) {
evt.preventDefault();
if (!(this.results_showing || this.is_disabled)) {
return this.results_show();
}
};
AbstractChosen.prototype.keyup_checker = function(evt) {
var stroke, _ref;
stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
this.search_field_scale();
switch (stroke) {
case 8:
if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
return this.keydown_backstroke();
} else if (!this.pending_backstroke) {
this.result_clear_highlight();
return this.results_search();
}
break;
case 13:
evt.preventDefault();
if (this.results_showing) {
return this.result_select(evt);
}
break;
case 27:
if (this.results_showing) {
this.results_hide();
}
return true;
case 9:
case 38:
case 40:
case 16:
case 91:
case 17:
break;
default:
return this.results_search();
}
};
AbstractChosen.prototype.clipboard_event_checker = function(evt) {
var _this = this;
return setTimeout((function() {
return _this.results_search();
}), 50);
};
AbstractChosen.prototype.container_width = function() {
if (this.options.width != null) {
return this.options.width;
} else {
return "" + this.form_field.offsetWidth + "px";
}
};
AbstractChosen.prototype.include_option_in_results = function(option) {
if (this.is_multiple && (!this.display_selected_options && option.selected)) {
return false;
}
if (!this.display_disabled_options && option.disabled) {
return false;
}
if (option.empty) {
return false;
}
return true;
};
AbstractChosen.prototype.search_results_touchstart = function(evt) {
this.touch_started = true;
return this.search_results_mouseover(evt);
};
AbstractChosen.prototype.search_results_touchmove = function(evt) {
this.touch_started = false;
return this.search_results_mouseout(evt);
};
AbstractChosen.prototype.search_results_touchend = function(evt) {
if (this.touch_started) {
return this.search_results_mouseup(evt);
}
};
AbstractChosen.prototype.outerHTML = function(element) {
var tmp;
if (element.outerHTML) {
return element.outerHTML;
}
tmp = document.createElement("div");
tmp.appendChild(element);
return tmp.innerHTML;
};
AbstractChosen.browser_is_supported = function() {
if (window.navigator.appName === "Microsoft Internet Explorer") {
return document.documentMode >= 8;
}
if (/iP(od|hone)/i.test(window.navigator.userAgent)) {
return false;
}
if (/Android/i.test(window.navigator.userAgent)) {
if (/Mobile/i.test(window.navigator.userAgent)) {
return false;
}
}
return true;
};
AbstractChosen.default_multiple_text = "Select Some Options";
AbstractChosen.default_single_text = "Select an Option";
AbstractChosen.default_no_result_text = "No results match";
return AbstractChosen;
})();
$ = jQuery;
$.fn.extend({
chosen: function(options) {
if (!AbstractChosen.browser_is_supported()) {
return this;
}
return this.each(function(input_field) {
var $this, chosen;
$this = $(this);
chosen = $this.data('chosen');
if (options === 'destroy' && chosen) {
chosen.destroy();
} else if (!chosen) {
$this.data('chosen', new Chosen(this, options));
}
});
}
});
Chosen = (function(_super) {
__extends(Chosen, _super);
function Chosen() {
_ref = Chosen.__super__.constructor.apply(this, arguments);
return _ref;
}
Chosen.prototype.setup = function() {
this.form_field_jq = $(this.form_field);
this.current_selectedIndex = this.form_field.selectedIndex;
return this.is_rtl = this.form_field_jq.hasClass("chosen-rtl");
};
Chosen.prototype.set_up_html = function() {
var container_classes, container_props;
container_classes = ["chosen-container"];
container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
if (this.inherit_select_classes && this.form_field.className) {
container_classes.push(this.form_field.className);
}
if (this.is_rtl) {
container_classes.push("chosen-rtl");
}
container_props = {
'class': container_classes.join(' '),
'style': "width: " + (this.container_width()) + ";",
'title': this.form_field.title
};
if (this.form_field.id.length) {
container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
}
this.container = $("<div />", container_props);
if (this.is_multiple) {
this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>');
} else {
this.container.html('<a class="chosen-single chosen-default" tabindex="-1"><span>' + this.default_text + '</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>');
}
this.form_field_jq.hide().after(this.container);
this.dropdown = this.container.find('div.chosen-drop').first();
this.search_field = this.container.find('input').first();
this.search_results = this.container.find('ul.chosen-results').first();
this.search_field_scale();
this.search_no_results = this.container.find('li.no-results').first();
if (this.is_multiple) {
this.search_choices = this.container.find('ul.chosen-choices').first();
this.search_container = this.container.find('li.search-field').first();
} else {
this.search_container = this.container.find('div.chosen-search').first();
this.selected_item = this.container.find('.chosen-single').first();
}
this.results_build();
this.set_tab_index();
this.set_label_behavior();
return this.form_field_jq.trigger("chosen:ready", {
chosen: this
});
};
Chosen.prototype.register_observers = function() {
var _this = this;
this.container.bind('mousedown.chosen', function(evt) {
_this.container_mousedown(evt);
});
this.container.bind('mouseup.chosen', function(evt) {
_this.container_mouseup(evt);
});
this.container.bind('mouseenter.chosen', function(evt) {
_this.mouse_enter(evt);
});
this.container.bind('mouseleave.chosen', function(evt) {
_this.mouse_leave(evt);
});
this.search_results.bind('mouseup.chosen', function(evt) {
_this.search_results_mouseup(evt);
});
this.search_results.bind('mouseover.chosen', function(evt) {
_this.search_results_mouseover(evt);
});
this.search_results.bind('mouseout.chosen', function(evt) {
_this.search_results_mouseout(evt);
});
this.search_results.bind('mousewheel.chosen DOMMouseScroll.chosen', function(evt) {
_this.search_results_mousewheel(evt);
});
this.search_results.bind('touchstart.chosen', function(evt) {
_this.search_results_touchstart(evt);
});
this.search_results.bind('touchmove.chosen', function(evt) {
_this.search_results_touchmove(evt);
});
this.search_results.bind('touchend.chosen', function(evt) {
_this.search_results_touchend(evt);
});
this.form_field_jq.bind("chosen:updated.chosen", function(evt) {
_this.results_update_field(evt);
});
this.form_field_jq.bind("chosen:activate.chosen", function(evt) {
_this.activate_field(evt);
});
this.form_field_jq.bind("chosen:open.chosen", function(evt) {
_this.container_mousedown(evt);
});
this.form_field_jq.bind("chosen:close.chosen", function(evt) {
_this.input_blur(evt);
});
this.search_field.bind('blur.chosen', function(evt) {
_this.input_blur(evt);
});
this.search_field.bind('keyup.chosen', function(evt) {
_this.keyup_checker(evt);
});
this.search_field.bind('keydown.chosen', function(evt) {
_this.keydown_checker(evt);
});
this.search_field.bind('focus.chosen', function(evt) {
_this.input_focus(evt);
});
this.search_field.bind('cut.chosen', function(evt) {
_this.clipboard_event_checker(evt);
});
this.search_field.bind('paste.chosen', function(evt) {
_this.clipboard_event_checker(evt);
});
if (this.is_multiple) {
return this.search_choices.bind('click.chosen', function(evt) {
_this.choices_click(evt);
});
} else {
return this.container.bind('click.chosen', function(evt) {
evt.preventDefault();
});
}
};
Chosen.prototype.destroy = function() {
$(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action);
if (this.search_field[0].tabIndex) {
this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex;
}
this.container.remove();
this.form_field_jq.removeData('chosen');
return this.form_field_jq.show();
};
Chosen.prototype.search_field_disabled = function() {
this.is_disabled = this.form_field_jq[0].disabled;
if (this.is_disabled) {
this.container.addClass('chosen-disabled');
this.search_field[0].disabled = true;
if (!this.is_multiple) {
this.selected_item.unbind("focus.chosen", this.activate_action);
}
return this.close_field();
} else {
this.container.removeClass('chosen-disabled');
this.search_field[0].disabled = false;
if (!this.is_multiple) {
return this.selected_item.bind("focus.chosen", this.activate_action);
}
}
};
Chosen.prototype.container_mousedown = function(evt) {
if (!this.is_disabled) {
if (evt && evt.type === "mousedown" && !this.results_showing) {
evt.preventDefault();
}
if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) {
if (!this.active_field) {
if (this.is_multiple) {
this.search_field.val("");
}
$(this.container[0].ownerDocument).bind('click.chosen', this.click_test_action);
this.results_show();
} else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) {
evt.preventDefault();
this.results_toggle();
}
return this.activate_field();
}
}
};
Chosen.prototype.container_mouseup = function(evt) {
if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
return this.results_reset(evt);
}
};
Chosen.prototype.search_results_mousewheel = function(evt) {
var delta;
if (evt.originalEvent) {
delta = -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
}
if (delta != null) {
evt.preventDefault();
if (evt.type === 'DOMMouseScroll') {
delta = delta * 40;
}
return this.search_results.scrollTop(delta + this.search_results.scrollTop());
}
};
Chosen.prototype.blur_test = function(evt) {
if (!this.active_field && this.container.hasClass("chosen-container-active")) {
return this.close_field();
}
};
Chosen.prototype.close_field = function() {
$(this.container[0].ownerDocument).unbind("click.chosen", this.click_test_action);
this.active_field = false;
this.results_hide();
this.container.removeClass("chosen-container-active");
this.clear_backstroke();
this.show_search_field_default();
return this.search_field_scale();
};
Chosen.prototype.activate_field = function() {
this.container.addClass("chosen-container-active");
this.active_field = true;
this.search_field.val(this.search_field.val());
return this.search_field.focus();
};
Chosen.prototype.test_active_click = function(evt) {
var active_container;
active_container = $(evt.target).closest('.chosen-container');
if (active_container.length && this.container[0] === active_container[0]) {
return this.active_field = true;
} else {
return this.close_field();
}
};
Chosen.prototype.results_build = function() {
this.parsing = true;
this.selected_option_count = null;
this.results_data = SelectParser.select_to_array(this.form_field);
if (this.is_multiple) {
this.search_choices.find("li.search-choice").remove();
} else if (!this.is_multiple) {
this.single_set_selected_text();
if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
this.search_field[0].readOnly = true;
this.container.addClass("chosen-container-single-nosearch");
} else {
this.search_field[0].readOnly = false;
this.container.removeClass("chosen-container-single-nosearch");
}
}
this.update_results_content(this.results_option_build({
first: true
}));
this.search_field_disabled();
this.show_search_field_default();
this.search_field_scale();
return this.parsing = false;
};
Chosen.prototype.result_do_highlight = function(el) {
var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
if (el.length) {
this.result_clear_highlight();
this.result_highlight = el;
this.result_highlight.addClass("highlighted");
maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
visible_top = this.search_results.scrollTop();
visible_bottom = maxHeight + visible_top;
high_top = this.result_highlight.position().top + this.search_results.scrollTop();
high_bottom = high_top + this.result_highlight.outerHeight();
if (high_bottom >= visible_bottom) {
return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
} else if (high_top < visible_top) {
return this.search_results.scrollTop(high_top);
}
}
};
Chosen.prototype.result_clear_highlight = function() {
if (this.result_highlight) {
this.result_highlight.removeClass("highlighted");
}
return this.result_highlight = null;
};
Chosen.prototype.results_show = function() {
if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
this.form_field_jq.trigger("chosen:maxselected", {
chosen: this
});
return false;
}
this.container.addClass("chosen-with-drop");
this.results_showing = true;
this.search_field.focus();
this.search_field.val(this.search_field.val());
this.winnow_results();
return this.form_field_jq.trigger("chosen:showing_dropdown", {
chosen: this
});
};
Chosen.prototype.update_results_content = function(content) {
return this.search_results.html(content);
};
Chosen.prototype.results_hide = function() {
if (this.results_showing) {
this.result_clear_highlight();
this.container.removeClass("chosen-with-drop");
this.form_field_jq.trigger("chosen:hiding_dropdown", {
chosen: this
});
}
return this.results_showing = false;
};
Chosen.prototype.set_tab_index = function(el) {
var ti;
if (this.form_field.tabIndex) {
ti = this.form_field.tabIndex;
this.form_field.tabIndex = -1;
return this.search_field[0].tabIndex = ti;
}
};
Chosen.prototype.set_label_behavior = function() {
var _this = this;
this.form_field_label = this.form_field_jq.parents("label");
if (!this.form_field_label.length && this.form_field.id.length) {
this.form_field_label = $("label[for='" + this.form_field.id + "']");
}
if (this.form_field_label.length > 0) {
return this.form_field_label.bind('click.chosen', function(evt) {
if (_this.is_multiple) {
return _this.container_mousedown(evt);
} else {
return _this.activate_field();
}
});
}
};
Chosen.prototype.show_search_field_default = function() {
if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
this.search_field.val(this.default_text);
return this.search_field.addClass("default");
} else {
this.search_field.val("");
return this.search_field.removeClass("default");
}
};
Chosen.prototype.search_results_mouseup = function(evt) {
var target;
target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
if (target.length) {
this.result_highlight = target;
this.result_select(evt);
return this.search_field.focus();
}
};
Chosen.prototype.search_results_mouseover = function(evt) {
var target;
target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
if (target) {
return this.result_do_highlight(target);
}
};
Chosen.prototype.search_results_mouseout = function(evt) {
if ($(evt.target).hasClass("active-result" || $(evt.target).parents('.active-result').first())) {
return this.result_clear_highlight();
}
};
Chosen.prototype.choice_build = function(item) {
var choice, close_link,
_this = this;
choice = $('<li />', {
"class": "search-choice"
}).html("<span>" + item.html + "</span>");
if (item.disabled) {
choice.addClass('search-choice-disabled');
} else {
close_link = $('<a />', {
"class": 'search-choice-close',
'data-option-array-index': item.array_index
});
close_link.bind('click.chosen', function(evt) {
return _this.choice_destroy_link_click(evt);
});
choice.append(close_link);
}
return this.search_container.before(choice);
};
Chosen.prototype.choice_destroy_link_click = function(evt) {
evt.preventDefault();
evt.stopPropagation();
if (!this.is_disabled) {
return this.choice_destroy($(evt.target));
}
};
Chosen.prototype.choice_destroy = function(link) {
if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) {
this.show_search_field_default();
if (this.is_multiple && this.choices_count() > 0 && this.search_field.val().length < 1) {
this.results_hide();
}
link.parents('li').first().remove();
return this.search_field_scale();
}
};
Chosen.prototype.results_reset = function() {
this.reset_single_select_options();
this.form_field.options[0].selected = true;
this.single_set_selected_text();
this.show_search_field_default();
this.results_reset_cleanup();
this.form_field_jq.trigger("change");
if (this.active_field) {
return this.results_hide();
}
};
Chosen.prototype.results_reset_cleanup = function() {
this.current_selectedIndex = this.form_field.selectedIndex;
return this.selected_item.find("abbr").remove();
};
Chosen.prototype.result_select = function(evt) {
var high, item;
if (this.result_highlight) {
high = this.result_highlight;
this.result_clear_highlight();
if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
this.form_field_jq.trigger("chosen:maxselected", {
chosen: this
});
return false;
}
if (this.is_multiple) {
high.removeClass("active-result");
} else {
this.reset_single_select_options();
}
item = this.results_data[high[0].getAttribute("data-option-array-index")];
item.selected = true;
this.form_field.options[item.options_index].selected = true;
this.selected_option_count = null;
if (this.is_multiple) {
this.choice_build(item);
} else {
this.single_set_selected_text(item.text);
}
if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) {
this.results_hide();
}
this.search_field.val("");
if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
this.form_field_jq.trigger("change", {
'selected': this.form_field.options[item.options_index].value
});
}
this.current_selectedIndex = this.form_field.selectedIndex;
return this.search_field_scale();
}
};
Chosen.prototype.single_set_selected_text = function(text) {
if (text == null) {
text = this.default_text;
}
if (text === this.default_text) {
this.selected_item.addClass("chosen-default");
} else {
this.single_deselect_control_build();
this.selected_item.removeClass("chosen-default");
}
return this.selected_item.find("span").text(text);
};
Chosen.prototype.result_deselect = function(pos) {
var result_data;
result_data = this.results_data[pos];
if (!this.form_field.options[result_data.options_index].disabled) {
result_data.selected = false;
this.form_field.options[result_data.options_index].selected = false;
this.selected_option_count = null;
this.result_clear_highlight();
if (this.results_showing) {
this.winnow_results();
}
this.form_field_jq.trigger("change", {
deselected: this.form_field.options[result_data.options_index].value
});
this.search_field_scale();
return true;
} else {
return false;
}
};
Chosen.prototype.single_deselect_control_build = function() {
if (!this.allow_single_deselect) {
return;
}
if (!this.selected_item.find("abbr").length) {
this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");
}
return this.selected_item.addClass("chosen-single-with-deselect");
};
Chosen.prototype.get_search_text = function() {
if (this.search_field.val() === this.default_text) {
return "";
} else {
return $('<div/>').text($.trim(this.search_field.val())).html();
}
};
Chosen.prototype.winnow_results_set_highlight = function() {
var do_high, selected_results;
selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
if (do_high != null) {
return this.result_do_highlight(do_high);
}
};
Chosen.prototype.no_results = function(terms) {
var no_results_html;
no_results_html = $('<li class="no-results">' + this.results_none_found + ' "<span></span>"</li>');
no_results_html.find("span").first().html(terms);
this.search_results.append(no_results_html);
return this.form_field_jq.trigger("chosen:no_results", {
chosen: this
});
};
Chosen.prototype.no_results_clear = function() {
return this.search_results.find(".no-results").remove();
};
Chosen.prototype.keydown_arrow = function() {
var next_sib;
if (this.results_showing && this.result_highlight) {
next_sib = this.result_highlight.nextAll("li.active-result").first();
if (next_sib) {
return this.result_do_highlight(next_sib);
}
} else {
return this.results_show();
}
};
Chosen.prototype.keyup_arrow = function() {
var prev_sibs;
if (!this.results_showing && !this.is_multiple) {
return this.results_show();
} else if (this.result_highlight) {
prev_sibs = this.result_highlight.prevAll("li.active-result");
if (prev_sibs.length) {
return this.result_do_highlight(prev_sibs.first());
} else {
if (this.choices_count() > 0) {
this.results_hide();
}
return this.result_clear_highlight();
}
}
};
Chosen.prototype.keydown_backstroke = function() {
var next_available_destroy;
if (this.pending_backstroke) {
this.choice_destroy(this.pending_backstroke.find("a").first());
return this.clear_backstroke();
} else {
next_available_destroy = this.search_container.siblings("li.search-choice").last();
if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) {
this.pending_backstroke = next_available_destroy;
if (this.single_backstroke_delete) {
return this.keydown_backstroke();
} else {
return this.pending_backstroke.addClass("search-choice-focus");
}
}
}
};
Chosen.prototype.clear_backstroke = function() {
if (this.pending_backstroke) {
this.pending_backstroke.removeClass("search-choice-focus");
}
return this.pending_backstroke = null;
};
Chosen.prototype.keydown_checker = function(evt) {
var stroke, _ref1;
stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode;
this.search_field_scale();
if (stroke !== 8 && this.pending_backstroke) {
this.clear_backstroke();
}
switch (stroke) {
case 8:
this.backstroke_length = this.search_field.val().length;
break;
case 9:
if (this.results_showing && !this.is_multiple) {
this.result_select(evt);
}
this.mouse_on_container = false;
break;
case 13:
evt.preventDefault();
break;
case 38:
evt.preventDefault();
this.keyup_arrow();
break;
case 40:
evt.preventDefault();
this.keydown_arrow();
break;
}
};
Chosen.prototype.search_field_scale = function() {
var div, f_width, h, style, style_block, styles, w, _i, _len;
if (this.is_multiple) {
h = 0;
w = 0;
style_block = "position:absolute; left: -1000px; top: -1000px; display:none;";
styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
for (_i = 0, _len = styles.length; _i < _len; _i++) {
style = styles[_i];
style_block += style + ":" + this.search_field.css(style) + ";";
}
div = $('<div />', {
'style': style_block
});
div.text(this.search_field.val());
$('body').append(div);
w = div.width() + 25;
div.remove();
f_width = this.container.outerWidth();
if (w > f_width - 10) {
w = f_width - 10;
}
return this.search_field.css({
'width': w + 'px'
});
}
};
return Chosen;
})(AbstractChosen);
}).call(this); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/chosen/chosen.jquery.js | chosen.jquery.js |
(function() {
var AbstractChosen, SelectParser, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
SelectParser = (function() {
function SelectParser() {
this.options_index = 0;
this.parsed = [];
}
SelectParser.prototype.add_node = function(child) {
if (child.nodeName.toUpperCase() === "OPTGROUP") {
return this.add_group(child);
} else {
return this.add_option(child);
}
};
SelectParser.prototype.add_group = function(group) {
var group_position, option, _i, _len, _ref, _results;
group_position = this.parsed.length;
this.parsed.push({
array_index: group_position,
group: true,
label: this.escapeExpression(group.label),
children: 0,
disabled: group.disabled
});
_ref = group.childNodes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
_results.push(this.add_option(option, group_position, group.disabled));
}
return _results;
};
SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
if (option.nodeName.toUpperCase() === "OPTION") {
if (option.text !== "") {
if (group_position != null) {
this.parsed[group_position].children += 1;
}
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
value: option.value,
text: option.text,
html: option.innerHTML,
selected: option.selected,
disabled: group_disabled === true ? group_disabled : option.disabled,
group_array_index: group_position,
classes: option.className,
style: option.style.cssText
});
} else {
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
empty: true
});
}
return this.options_index += 1;
}
};
SelectParser.prototype.escapeExpression = function(text) {
var map, unsafe_chars;
if ((text == null) || text === false) {
return "";
}
if (!/[\&\<\>\"\'\`]/.test(text)) {
return text;
}
map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
};
unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g;
return text.replace(unsafe_chars, function(chr) {
return map[chr] || "&";
});
};
return SelectParser;
})();
SelectParser.select_to_array = function(select) {
var child, parser, _i, _len, _ref;
parser = new SelectParser();
_ref = select.childNodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
parser.add_node(child);
}
return parser.parsed;
};
AbstractChosen = (function() {
function AbstractChosen(form_field, options) {
this.form_field = form_field;
this.options = options != null ? options : {};
if (!AbstractChosen.browser_is_supported()) {
return;
}
this.is_multiple = this.form_field.multiple;
this.set_default_text();
this.set_default_values();
this.setup();
this.set_up_html();
this.register_observers();
}
AbstractChosen.prototype.set_default_values = function() {
var _this = this;
this.click_test_action = function(evt) {
return _this.test_active_click(evt);
};
this.activate_action = function(evt) {
return _this.activate_field(evt);
};
this.active_field = false;
this.mouse_on_container = false;
this.results_showing = false;
this.result_highlighted = null;
this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
this.disable_search_threshold = this.options.disable_search_threshold || 0;
this.disable_search = this.options.disable_search || false;
this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
this.group_search = this.options.group_search != null ? this.options.group_search : true;
this.search_contains = this.options.search_contains || false;
this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
this.max_selected_options = this.options.max_selected_options || Infinity;
this.inherit_select_classes = this.options.inherit_select_classes || false;
this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
return this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
};
AbstractChosen.prototype.set_default_text = function() {
if (this.form_field.getAttribute("data-placeholder")) {
this.default_text = this.form_field.getAttribute("data-placeholder");
} else if (this.is_multiple) {
this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
} else {
this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
}
return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
};
AbstractChosen.prototype.mouse_enter = function() {
return this.mouse_on_container = true;
};
AbstractChosen.prototype.mouse_leave = function() {
return this.mouse_on_container = false;
};
AbstractChosen.prototype.input_focus = function(evt) {
var _this = this;
if (this.is_multiple) {
if (!this.active_field) {
return setTimeout((function() {
return _this.container_mousedown();
}), 50);
}
} else {
if (!this.active_field) {
return this.activate_field();
}
}
};
AbstractChosen.prototype.input_blur = function(evt) {
var _this = this;
if (!this.mouse_on_container) {
this.active_field = false;
return setTimeout((function() {
return _this.blur_test();
}), 100);
}
};
AbstractChosen.prototype.results_option_build = function(options) {
var content, data, _i, _len, _ref;
content = '';
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
if (data.group) {
content += this.result_add_group(data);
} else {
content += this.result_add_option(data);
}
if (options != null ? options.first : void 0) {
if (data.selected && this.is_multiple) {
this.choice_build(data);
} else if (data.selected && !this.is_multiple) {
this.single_set_selected_text(data.text);
}
}
}
return content;
};
AbstractChosen.prototype.result_add_option = function(option) {
var classes, option_el;
if (!option.search_match) {
return '';
}
if (!this.include_option_in_results(option)) {
return '';
}
classes = [];
if (!option.disabled && !(option.selected && this.is_multiple)) {
classes.push("active-result");
}
if (option.disabled && !(option.selected && this.is_multiple)) {
classes.push("disabled-result");
}
if (option.selected) {
classes.push("result-selected");
}
if (option.group_array_index != null) {
classes.push("group-option");
}
if (option.classes !== "") {
classes.push(option.classes);
}
option_el = document.createElement("li");
option_el.className = classes.join(" ");
option_el.style.cssText = option.style;
option_el.setAttribute("data-option-array-index", option.array_index);
option_el.innerHTML = option.search_text;
return this.outerHTML(option_el);
};
AbstractChosen.prototype.result_add_group = function(group) {
var group_el;
if (!(group.search_match || group.group_match)) {
return '';
}
if (!(group.active_options > 0)) {
return '';
}
group_el = document.createElement("li");
group_el.className = "group-result";
group_el.innerHTML = group.search_text;
return this.outerHTML(group_el);
};
AbstractChosen.prototype.results_update_field = function() {
this.set_default_text();
if (!this.is_multiple) {
this.results_reset_cleanup();
}
this.result_clear_highlight();
this.results_build();
if (this.results_showing) {
return this.winnow_results();
}
};
AbstractChosen.prototype.reset_single_select_options = function() {
var result, _i, _len, _ref, _results;
_ref = this.results_data;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
result = _ref[_i];
if (result.selected) {
_results.push(result.selected = false);
} else {
_results.push(void 0);
}
}
return _results;
};
AbstractChosen.prototype.results_toggle = function() {
if (this.results_showing) {
return this.results_hide();
} else {
return this.results_show();
}
};
AbstractChosen.prototype.results_search = function(evt) {
if (this.results_showing) {
return this.winnow_results();
} else {
return this.results_show();
}
};
AbstractChosen.prototype.winnow_results = function() {
var escapedSearchText, option, regex, regexAnchor, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
this.no_results_clear();
results = 0;
searchText = this.get_search_text();
escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
regexAnchor = this.search_contains ? "" : "^";
regex = new RegExp(regexAnchor + escapedSearchText, 'i');
zregex = new RegExp(escapedSearchText, 'i');
_ref = this.results_data;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
option.search_match = false;
results_group = null;
if (this.include_option_in_results(option)) {
if (option.group) {
option.group_match = false;
option.active_options = 0;
}
if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
results_group = this.results_data[option.group_array_index];
if (results_group.active_options === 0 && results_group.search_match) {
results += 1;
}
results_group.active_options += 1;
}
if (!(option.group && !this.group_search)) {
option.search_text = option.group ? option.label : option.html;
option.search_match = this.search_string_match(option.search_text, regex);
if (option.search_match && !option.group) {
results += 1;
}
if (option.search_match) {
if (searchText.length) {
startpos = option.search_text.search(zregex);
text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
}
if (results_group != null) {
results_group.group_match = true;
}
} else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
option.search_match = true;
}
}
}
}
this.result_clear_highlight();
if (results < 1 && searchText.length) {
this.update_results_content("");
return this.no_results(searchText);
} else {
this.update_results_content(this.results_option_build());
return this.winnow_results_set_highlight();
}
};
AbstractChosen.prototype.search_string_match = function(search_string, regex) {
var part, parts, _i, _len;
if (regex.test(search_string)) {
return true;
} else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) {
parts = search_string.replace(/\[|\]/g, "").split(" ");
if (parts.length) {
for (_i = 0, _len = parts.length; _i < _len; _i++) {
part = parts[_i];
if (regex.test(part)) {
return true;
}
}
}
}
};
AbstractChosen.prototype.choices_count = function() {
var option, _i, _len, _ref;
if (this.selected_option_count != null) {
return this.selected_option_count;
}
this.selected_option_count = 0;
_ref = this.form_field.options;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
if (option.selected) {
this.selected_option_count += 1;
}
}
return this.selected_option_count;
};
AbstractChosen.prototype.choices_click = function(evt) {
evt.preventDefault();
if (!(this.results_showing || this.is_disabled)) {
return this.results_show();
}
};
AbstractChosen.prototype.keyup_checker = function(evt) {
var stroke, _ref;
stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
this.search_field_scale();
switch (stroke) {
case 8:
if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
return this.keydown_backstroke();
} else if (!this.pending_backstroke) {
this.result_clear_highlight();
return this.results_search();
}
break;
case 13:
evt.preventDefault();
if (this.results_showing) {
return this.result_select(evt);
}
break;
case 27:
if (this.results_showing) {
this.results_hide();
}
return true;
case 9:
case 38:
case 40:
case 16:
case 91:
case 17:
break;
default:
return this.results_search();
}
};
AbstractChosen.prototype.clipboard_event_checker = function(evt) {
var _this = this;
return setTimeout((function() {
return _this.results_search();
}), 50);
};
AbstractChosen.prototype.container_width = function() {
if (this.options.width != null) {
return this.options.width;
} else {
return "" + this.form_field.offsetWidth + "px";
}
};
AbstractChosen.prototype.include_option_in_results = function(option) {
if (this.is_multiple && (!this.display_selected_options && option.selected)) {
return false;
}
if (!this.display_disabled_options && option.disabled) {
return false;
}
if (option.empty) {
return false;
}
return true;
};
AbstractChosen.prototype.search_results_touchstart = function(evt) {
this.touch_started = true;
return this.search_results_mouseover(evt);
};
AbstractChosen.prototype.search_results_touchmove = function(evt) {
this.touch_started = false;
return this.search_results_mouseout(evt);
};
AbstractChosen.prototype.search_results_touchend = function(evt) {
if (this.touch_started) {
return this.search_results_mouseup(evt);
}
};
AbstractChosen.prototype.outerHTML = function(element) {
var tmp;
if (element.outerHTML) {
return element.outerHTML;
}
tmp = document.createElement("div");
tmp.appendChild(element);
return tmp.innerHTML;
};
AbstractChosen.browser_is_supported = function() {
if (window.navigator.appName === "Microsoft Internet Explorer") {
return document.documentMode >= 8;
}
if (/iP(od|hone)/i.test(window.navigator.userAgent)) {
return false;
}
if (/Android/i.test(window.navigator.userAgent)) {
if (/Mobile/i.test(window.navigator.userAgent)) {
return false;
}
}
return true;
};
AbstractChosen.default_multiple_text = "Select Some Options";
AbstractChosen.default_single_text = "Select an Option";
AbstractChosen.default_no_result_text = "No results match";
return AbstractChosen;
})();
this.Chosen = (function(_super) {
__extends(Chosen, _super);
function Chosen() {
_ref = Chosen.__super__.constructor.apply(this, arguments);
return _ref;
}
Chosen.prototype.setup = function() {
this.current_selectedIndex = this.form_field.selectedIndex;
return this.is_rtl = this.form_field.hasClassName("chosen-rtl");
};
Chosen.prototype.set_default_values = function() {
Chosen.__super__.set_default_values.call(this);
this.single_temp = new Template('<a class="chosen-single chosen-default" tabindex="-1"><span>#{default}</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>');
this.multi_temp = new Template('<ul class="chosen-choices"><li class="search-field"><input type="text" value="#{default}" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>');
return this.no_results_temp = new Template('<li class="no-results">' + this.results_none_found + ' "<span>#{terms}</span>"</li>');
};
Chosen.prototype.set_up_html = function() {
var container_classes, container_props;
container_classes = ["chosen-container"];
container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
if (this.inherit_select_classes && this.form_field.className) {
container_classes.push(this.form_field.className);
}
if (this.is_rtl) {
container_classes.push("chosen-rtl");
}
container_props = {
'class': container_classes.join(' '),
'style': "width: " + (this.container_width()) + ";",
'title': this.form_field.title
};
if (this.form_field.id.length) {
container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
}
this.container = this.is_multiple ? new Element('div', container_props).update(this.multi_temp.evaluate({
"default": this.default_text
})) : new Element('div', container_props).update(this.single_temp.evaluate({
"default": this.default_text
}));
this.form_field.hide().insert({
after: this.container
});
this.dropdown = this.container.down('div.chosen-drop');
this.search_field = this.container.down('input');
this.search_results = this.container.down('ul.chosen-results');
this.search_field_scale();
this.search_no_results = this.container.down('li.no-results');
if (this.is_multiple) {
this.search_choices = this.container.down('ul.chosen-choices');
this.search_container = this.container.down('li.search-field');
} else {
this.search_container = this.container.down('div.chosen-search');
this.selected_item = this.container.down('.chosen-single');
}
this.results_build();
this.set_tab_index();
this.set_label_behavior();
return this.form_field.fire("chosen:ready", {
chosen: this
});
};
Chosen.prototype.register_observers = function() {
var _this = this;
this.container.observe("mousedown", function(evt) {
return _this.container_mousedown(evt);
});
this.container.observe("mouseup", function(evt) {
return _this.container_mouseup(evt);
});
this.container.observe("mouseenter", function(evt) {
return _this.mouse_enter(evt);
});
this.container.observe("mouseleave", function(evt) {
return _this.mouse_leave(evt);
});
this.search_results.observe("mouseup", function(evt) {
return _this.search_results_mouseup(evt);
});
this.search_results.observe("mouseover", function(evt) {
return _this.search_results_mouseover(evt);
});
this.search_results.observe("mouseout", function(evt) {
return _this.search_results_mouseout(evt);
});
this.search_results.observe("mousewheel", function(evt) {
return _this.search_results_mousewheel(evt);
});
this.search_results.observe("DOMMouseScroll", function(evt) {
return _this.search_results_mousewheel(evt);
});
this.search_results.observe("touchstart", function(evt) {
return _this.search_results_touchstart(evt);
});
this.search_results.observe("touchmove", function(evt) {
return _this.search_results_touchmove(evt);
});
this.search_results.observe("touchend", function(evt) {
return _this.search_results_touchend(evt);
});
this.form_field.observe("chosen:updated", function(evt) {
return _this.results_update_field(evt);
});
this.form_field.observe("chosen:activate", function(evt) {
return _this.activate_field(evt);
});
this.form_field.observe("chosen:open", function(evt) {
return _this.container_mousedown(evt);
});
this.form_field.observe("chosen:close", function(evt) {
return _this.input_blur(evt);
});
this.search_field.observe("blur", function(evt) {
return _this.input_blur(evt);
});
this.search_field.observe("keyup", function(evt) {
return _this.keyup_checker(evt);
});
this.search_field.observe("keydown", function(evt) {
return _this.keydown_checker(evt);
});
this.search_field.observe("focus", function(evt) {
return _this.input_focus(evt);
});
this.search_field.observe("cut", function(evt) {
return _this.clipboard_event_checker(evt);
});
this.search_field.observe("paste", function(evt) {
return _this.clipboard_event_checker(evt);
});
if (this.is_multiple) {
return this.search_choices.observe("click", function(evt) {
return _this.choices_click(evt);
});
} else {
return this.container.observe("click", function(evt) {
return evt.preventDefault();
});
}
};
Chosen.prototype.destroy = function() {
this.container.ownerDocument.stopObserving("click", this.click_test_action);
this.form_field.stopObserving();
this.container.stopObserving();
this.search_results.stopObserving();
this.search_field.stopObserving();
if (this.form_field_label != null) {
this.form_field_label.stopObserving();
}
if (this.is_multiple) {
this.search_choices.stopObserving();
this.container.select(".search-choice-close").each(function(choice) {
return choice.stopObserving();
});
} else {
this.selected_item.stopObserving();
}
if (this.search_field.tabIndex) {
this.form_field.tabIndex = this.search_field.tabIndex;
}
this.container.remove();
return this.form_field.show();
};
Chosen.prototype.search_field_disabled = function() {
this.is_disabled = this.form_field.disabled;
if (this.is_disabled) {
this.container.addClassName('chosen-disabled');
this.search_field.disabled = true;
if (!this.is_multiple) {
this.selected_item.stopObserving("focus", this.activate_action);
}
return this.close_field();
} else {
this.container.removeClassName('chosen-disabled');
this.search_field.disabled = false;
if (!this.is_multiple) {
return this.selected_item.observe("focus", this.activate_action);
}
}
};
Chosen.prototype.container_mousedown = function(evt) {
if (!this.is_disabled) {
if (evt && evt.type === "mousedown" && !this.results_showing) {
evt.stop();
}
if (!((evt != null) && evt.target.hasClassName("search-choice-close"))) {
if (!this.active_field) {
if (this.is_multiple) {
this.search_field.clear();
}
this.container.ownerDocument.observe("click", this.click_test_action);
this.results_show();
} else if (!this.is_multiple && evt && (evt.target === this.selected_item || evt.target.up("a.chosen-single"))) {
this.results_toggle();
}
return this.activate_field();
}
}
};
Chosen.prototype.container_mouseup = function(evt) {
if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
return this.results_reset(evt);
}
};
Chosen.prototype.search_results_mousewheel = function(evt) {
var delta;
delta = -evt.wheelDelta || evt.detail;
if (delta != null) {
evt.preventDefault();
if (evt.type === 'DOMMouseScroll') {
delta = delta * 40;
}
return this.search_results.scrollTop = delta + this.search_results.scrollTop;
}
};
Chosen.prototype.blur_test = function(evt) {
if (!this.active_field && this.container.hasClassName("chosen-container-active")) {
return this.close_field();
}
};
Chosen.prototype.close_field = function() {
this.container.ownerDocument.stopObserving("click", this.click_test_action);
this.active_field = false;
this.results_hide();
this.container.removeClassName("chosen-container-active");
this.clear_backstroke();
this.show_search_field_default();
return this.search_field_scale();
};
Chosen.prototype.activate_field = function() {
this.container.addClassName("chosen-container-active");
this.active_field = true;
this.search_field.value = this.search_field.value;
return this.search_field.focus();
};
Chosen.prototype.test_active_click = function(evt) {
if (evt.target.up('.chosen-container') === this.container) {
return this.active_field = true;
} else {
return this.close_field();
}
};
Chosen.prototype.results_build = function() {
this.parsing = true;
this.selected_option_count = null;
this.results_data = SelectParser.select_to_array(this.form_field);
if (this.is_multiple) {
this.search_choices.select("li.search-choice").invoke("remove");
} else if (!this.is_multiple) {
this.single_set_selected_text();
if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
this.search_field.readOnly = true;
this.container.addClassName("chosen-container-single-nosearch");
} else {
this.search_field.readOnly = false;
this.container.removeClassName("chosen-container-single-nosearch");
}
}
this.update_results_content(this.results_option_build({
first: true
}));
this.search_field_disabled();
this.show_search_field_default();
this.search_field_scale();
return this.parsing = false;
};
Chosen.prototype.result_do_highlight = function(el) {
var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
this.result_clear_highlight();
this.result_highlight = el;
this.result_highlight.addClassName("highlighted");
maxHeight = parseInt(this.search_results.getStyle('maxHeight'), 10);
visible_top = this.search_results.scrollTop;
visible_bottom = maxHeight + visible_top;
high_top = this.result_highlight.positionedOffset().top;
high_bottom = high_top + this.result_highlight.getHeight();
if (high_bottom >= visible_bottom) {
return this.search_results.scrollTop = (high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0;
} else if (high_top < visible_top) {
return this.search_results.scrollTop = high_top;
}
};
Chosen.prototype.result_clear_highlight = function() {
if (this.result_highlight) {
this.result_highlight.removeClassName('highlighted');
}
return this.result_highlight = null;
};
Chosen.prototype.results_show = function() {
if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
this.form_field.fire("chosen:maxselected", {
chosen: this
});
return false;
}
this.container.addClassName("chosen-with-drop");
this.results_showing = true;
this.search_field.focus();
this.search_field.value = this.search_field.value;
this.winnow_results();
return this.form_field.fire("chosen:showing_dropdown", {
chosen: this
});
};
Chosen.prototype.update_results_content = function(content) {
return this.search_results.update(content);
};
Chosen.prototype.results_hide = function() {
if (this.results_showing) {
this.result_clear_highlight();
this.container.removeClassName("chosen-with-drop");
this.form_field.fire("chosen:hiding_dropdown", {
chosen: this
});
}
return this.results_showing = false;
};
Chosen.prototype.set_tab_index = function(el) {
var ti;
if (this.form_field.tabIndex) {
ti = this.form_field.tabIndex;
this.form_field.tabIndex = -1;
return this.search_field.tabIndex = ti;
}
};
Chosen.prototype.set_label_behavior = function() {
var _this = this;
this.form_field_label = this.form_field.up("label");
if (this.form_field_label == null) {
this.form_field_label = $$("label[for='" + this.form_field.id + "']").first();
}
if (this.form_field_label != null) {
return this.form_field_label.observe("click", function(evt) {
if (_this.is_multiple) {
return _this.container_mousedown(evt);
} else {
return _this.activate_field();
}
});
}
};
Chosen.prototype.show_search_field_default = function() {
if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
this.search_field.value = this.default_text;
return this.search_field.addClassName("default");
} else {
this.search_field.value = "";
return this.search_field.removeClassName("default");
}
};
Chosen.prototype.search_results_mouseup = function(evt) {
var target;
target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result");
if (target) {
this.result_highlight = target;
this.result_select(evt);
return this.search_field.focus();
}
};
Chosen.prototype.search_results_mouseover = function(evt) {
var target;
target = evt.target.hasClassName("active-result") ? evt.target : evt.target.up(".active-result");
if (target) {
return this.result_do_highlight(target);
}
};
Chosen.prototype.search_results_mouseout = function(evt) {
if (evt.target.hasClassName('active-result') || evt.target.up('.active-result')) {
return this.result_clear_highlight();
}
};
Chosen.prototype.choice_build = function(item) {
var choice, close_link,
_this = this;
choice = new Element('li', {
"class": "search-choice"
}).update("<span>" + item.html + "</span>");
if (item.disabled) {
choice.addClassName('search-choice-disabled');
} else {
close_link = new Element('a', {
href: '#',
"class": 'search-choice-close',
rel: item.array_index
});
close_link.observe("click", function(evt) {
return _this.choice_destroy_link_click(evt);
});
choice.insert(close_link);
}
return this.search_container.insert({
before: choice
});
};
Chosen.prototype.choice_destroy_link_click = function(evt) {
evt.preventDefault();
evt.stopPropagation();
if (!this.is_disabled) {
return this.choice_destroy(evt.target);
}
};
Chosen.prototype.choice_destroy = function(link) {
if (this.result_deselect(link.readAttribute("rel"))) {
this.show_search_field_default();
if (this.is_multiple && this.choices_count() > 0 && this.search_field.value.length < 1) {
this.results_hide();
}
link.up('li').remove();
return this.search_field_scale();
}
};
Chosen.prototype.results_reset = function() {
this.reset_single_select_options();
this.form_field.options[0].selected = true;
this.single_set_selected_text();
this.show_search_field_default();
this.results_reset_cleanup();
if (typeof Event.simulate === 'function') {
this.form_field.simulate("change");
}
if (this.active_field) {
return this.results_hide();
}
};
Chosen.prototype.results_reset_cleanup = function() {
var deselect_trigger;
this.current_selectedIndex = this.form_field.selectedIndex;
deselect_trigger = this.selected_item.down("abbr");
if (deselect_trigger) {
return deselect_trigger.remove();
}
};
Chosen.prototype.result_select = function(evt) {
var high, item;
if (this.result_highlight) {
high = this.result_highlight;
this.result_clear_highlight();
if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
this.form_field.fire("chosen:maxselected", {
chosen: this
});
return false;
}
if (this.is_multiple) {
high.removeClassName("active-result");
} else {
this.reset_single_select_options();
}
high.addClassName("result-selected");
item = this.results_data[high.getAttribute("data-option-array-index")];
item.selected = true;
this.form_field.options[item.options_index].selected = true;
this.selected_option_count = null;
if (this.is_multiple) {
this.choice_build(item);
} else {
this.single_set_selected_text(item.text);
}
if (!((evt.metaKey || evt.ctrlKey) && this.is_multiple)) {
this.results_hide();
}
this.search_field.value = "";
if (typeof Event.simulate === 'function' && (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex)) {
this.form_field.simulate("change");
}
this.current_selectedIndex = this.form_field.selectedIndex;
return this.search_field_scale();
}
};
Chosen.prototype.single_set_selected_text = function(text) {
if (text == null) {
text = this.default_text;
}
if (text === this.default_text) {
this.selected_item.addClassName("chosen-default");
} else {
this.single_deselect_control_build();
this.selected_item.removeClassName("chosen-default");
}
return this.selected_item.down("span").update(text);
};
Chosen.prototype.result_deselect = function(pos) {
var result_data;
result_data = this.results_data[pos];
if (!this.form_field.options[result_data.options_index].disabled) {
result_data.selected = false;
this.form_field.options[result_data.options_index].selected = false;
this.selected_option_count = null;
this.result_clear_highlight();
if (this.results_showing) {
this.winnow_results();
}
if (typeof Event.simulate === 'function') {
this.form_field.simulate("change");
}
this.search_field_scale();
return true;
} else {
return false;
}
};
Chosen.prototype.single_deselect_control_build = function() {
if (!this.allow_single_deselect) {
return;
}
if (!this.selected_item.down("abbr")) {
this.selected_item.down("span").insert({
after: "<abbr class=\"search-choice-close\"></abbr>"
});
}
return this.selected_item.addClassName("chosen-single-with-deselect");
};
Chosen.prototype.get_search_text = function() {
if (this.search_field.value === this.default_text) {
return "";
} else {
return this.search_field.value.strip().escapeHTML();
}
};
Chosen.prototype.winnow_results_set_highlight = function() {
var do_high;
if (!this.is_multiple) {
do_high = this.search_results.down(".result-selected.active-result");
}
if (do_high == null) {
do_high = this.search_results.down(".active-result");
}
if (do_high != null) {
return this.result_do_highlight(do_high);
}
};
Chosen.prototype.no_results = function(terms) {
this.search_results.insert(this.no_results_temp.evaluate({
terms: terms
}));
return this.form_field.fire("chosen:no_results", {
chosen: this
});
};
Chosen.prototype.no_results_clear = function() {
var nr, _results;
nr = null;
_results = [];
while (nr = this.search_results.down(".no-results")) {
_results.push(nr.remove());
}
return _results;
};
Chosen.prototype.keydown_arrow = function() {
var next_sib;
if (this.results_showing && this.result_highlight) {
next_sib = this.result_highlight.next('.active-result');
if (next_sib) {
return this.result_do_highlight(next_sib);
}
} else {
return this.results_show();
}
};
Chosen.prototype.keyup_arrow = function() {
var actives, prevs, sibs;
if (!this.results_showing && !this.is_multiple) {
return this.results_show();
} else if (this.result_highlight) {
sibs = this.result_highlight.previousSiblings();
actives = this.search_results.select("li.active-result");
prevs = sibs.intersect(actives);
if (prevs.length) {
return this.result_do_highlight(prevs.first());
} else {
if (this.choices_count() > 0) {
this.results_hide();
}
return this.result_clear_highlight();
}
}
};
Chosen.prototype.keydown_backstroke = function() {
var next_available_destroy;
if (this.pending_backstroke) {
this.choice_destroy(this.pending_backstroke.down("a"));
return this.clear_backstroke();
} else {
next_available_destroy = this.search_container.siblings().last();
if (next_available_destroy && next_available_destroy.hasClassName("search-choice") && !next_available_destroy.hasClassName("search-choice-disabled")) {
this.pending_backstroke = next_available_destroy;
if (this.pending_backstroke) {
this.pending_backstroke.addClassName("search-choice-focus");
}
if (this.single_backstroke_delete) {
return this.keydown_backstroke();
} else {
return this.pending_backstroke.addClassName("search-choice-focus");
}
}
}
};
Chosen.prototype.clear_backstroke = function() {
if (this.pending_backstroke) {
this.pending_backstroke.removeClassName("search-choice-focus");
}
return this.pending_backstroke = null;
};
Chosen.prototype.keydown_checker = function(evt) {
var stroke, _ref1;
stroke = (_ref1 = evt.which) != null ? _ref1 : evt.keyCode;
this.search_field_scale();
if (stroke !== 8 && this.pending_backstroke) {
this.clear_backstroke();
}
switch (stroke) {
case 8:
this.backstroke_length = this.search_field.value.length;
break;
case 9:
if (this.results_showing && !this.is_multiple) {
this.result_select(evt);
}
this.mouse_on_container = false;
break;
case 13:
evt.preventDefault();
break;
case 38:
evt.preventDefault();
this.keyup_arrow();
break;
case 40:
evt.preventDefault();
this.keydown_arrow();
break;
}
};
Chosen.prototype.search_field_scale = function() {
var div, f_width, h, style, style_block, styles, w, _i, _len;
if (this.is_multiple) {
h = 0;
w = 0;
style_block = "position:absolute; left: -1000px; top: -1000px; display:none;";
styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
for (_i = 0, _len = styles.length; _i < _len; _i++) {
style = styles[_i];
style_block += style + ":" + this.search_field.getStyle(style) + ";";
}
div = new Element('div', {
'style': style_block
}).update(this.search_field.value.escapeHTML());
document.body.appendChild(div);
w = Element.measure(div, 'width') + 25;
div.remove();
f_width = this.container.getWidth();
if (w > f_width - 10) {
w = f_width - 10;
}
return this.search_field.setStyle({
'width': w + 'px'
});
}
};
return Chosen;
})(AbstractChosen);
}).call(this); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/chosen/chosen.proto.js | chosen.proto.js |
!function(){var AbstractChosen,SelectParser,a,b={}.hasOwnProperty,c=function(a,c){function d(){this.constructor=a}for(var e in c)b.call(c,e)&&(a[e]=c[e]);return d.prototype=c.prototype,a.prototype=new d,a.__super__=c.prototype,a};SelectParser=function(){function SelectParser(){this.options_index=0,this.parsed=[]}return SelectParser.prototype.add_node=function(a){return"OPTGROUP"===a.nodeName.toUpperCase()?this.add_group(a):this.add_option(a)},SelectParser.prototype.add_group=function(a){var b,c,d,e,f,g;for(b=this.parsed.length,this.parsed.push({array_index:b,group:!0,label:this.escapeExpression(a.label),children:0,disabled:a.disabled}),f=a.childNodes,g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(this.add_option(c,b,a.disabled));return g},SelectParser.prototype.add_option=function(a,b,c){return"OPTION"===a.nodeName.toUpperCase()?(""!==a.text?(null!=b&&(this.parsed[b].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:a.value,text:a.text,html:a.innerHTML,selected:a.selected,disabled:c===!0?c:a.disabled,group_array_index:b,classes:a.className,style:a.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1):void 0},SelectParser.prototype.escapeExpression=function(a){var b,c;return null==a||a===!1?"":/[\&\<\>\"\'\`]/.test(a)?(b={"<":"<",">":">",'"':""","'":"'","`":"`"},c=/&(?!\w+;)|[\<\>\"\'\`]/g,a.replace(c,function(a){return b[a]||"&"})):a},SelectParser}(),SelectParser.select_to_array=function(a){var b,c,d,e,f;for(c=new SelectParser,f=a.childNodes,d=0,e=f.length;e>d;d++)b=f[d],c.add_node(b);return c.parsed},AbstractChosen=function(){function AbstractChosen(a,b){this.form_field=a,this.options=null!=b?b:{},AbstractChosen.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers())}return AbstractChosen.prototype.set_default_values=function(){var a=this;return this.click_test_action=function(b){return a.test_active_click(b)},this.activate_action=function(b){return a.activate_field(b)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0},AbstractChosen.prototype.set_default_text=function(){return this.default_text=this.form_field.getAttribute("data-placeholder")?this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.options.placeholder_text_multiple||this.options.placeholder_text||AbstractChosen.default_multiple_text:this.options.placeholder_text_single||this.options.placeholder_text||AbstractChosen.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||AbstractChosen.default_no_result_text},AbstractChosen.prototype.mouse_enter=function(){return this.mouse_on_container=!0},AbstractChosen.prototype.mouse_leave=function(){return this.mouse_on_container=!1},AbstractChosen.prototype.input_focus=function(){var a=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return a.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},AbstractChosen.prototype.input_blur=function(){var a=this;return this.mouse_on_container?void 0:(this.active_field=!1,setTimeout(function(){return a.blur_test()},100))},AbstractChosen.prototype.results_option_build=function(a){var b,c,d,e,f;for(b="",f=this.results_data,d=0,e=f.length;e>d;d++)c=f[d],b+=c.group?this.result_add_group(c):this.result_add_option(c),(null!=a?a.first:void 0)&&(c.selected&&this.is_multiple?this.choice_build(c):c.selected&&!this.is_multiple&&this.single_set_selected_text(c.text));return b},AbstractChosen.prototype.result_add_option=function(a){var b,c;return a.search_match?this.include_option_in_results(a)?(b=[],a.disabled||a.selected&&this.is_multiple||b.push("active-result"),!a.disabled||a.selected&&this.is_multiple||b.push("disabled-result"),a.selected&&b.push("result-selected"),null!=a.group_array_index&&b.push("group-option"),""!==a.classes&&b.push(a.classes),c=document.createElement("li"),c.className=b.join(" "),c.style.cssText=a.style,c.setAttribute("data-option-array-index",a.array_index),c.innerHTML=a.search_text,this.outerHTML(c)):"":""},AbstractChosen.prototype.result_add_group=function(a){var b;return a.search_match||a.group_match?a.active_options>0?(b=document.createElement("li"),b.className="group-result",b.innerHTML=a.search_text,this.outerHTML(b)):"":""},AbstractChosen.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},AbstractChosen.prototype.reset_single_select_options=function(){var a,b,c,d,e;for(d=this.results_data,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.selected?e.push(a.selected=!1):e.push(void 0);return e},AbstractChosen.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},AbstractChosen.prototype.results_search=function(){return this.results_showing?this.winnow_results():this.results_show()},AbstractChosen.prototype.winnow_results=function(){var a,b,c,d,e,f,g,h,i,j,k,l,m;for(this.no_results_clear(),e=0,g=this.get_search_text(),a=g.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),d=this.search_contains?"":"^",c=new RegExp(d+a,"i"),j=new RegExp(a,"i"),m=this.results_data,k=0,l=m.length;l>k;k++)b=m[k],b.search_match=!1,f=null,this.include_option_in_results(b)&&(b.group&&(b.group_match=!1,b.active_options=0),null!=b.group_array_index&&this.results_data[b.group_array_index]&&(f=this.results_data[b.group_array_index],0===f.active_options&&f.search_match&&(e+=1),f.active_options+=1),(!b.group||this.group_search)&&(b.search_text=b.group?b.label:b.html,b.search_match=this.search_string_match(b.search_text,c),b.search_match&&!b.group&&(e+=1),b.search_match?(g.length&&(h=b.search_text.search(j),i=b.search_text.substr(0,h+g.length)+"</em>"+b.search_text.substr(h+g.length),b.search_text=i.substr(0,h)+"<em>"+i.substr(h)),null!=f&&(f.group_match=!0)):null!=b.group_array_index&&this.results_data[b.group_array_index].search_match&&(b.search_match=!0)));return this.result_clear_highlight(),1>e&&g.length?(this.update_results_content(""),this.no_results(g)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},AbstractChosen.prototype.search_string_match=function(a,b){var c,d,e,f;if(b.test(a))return!0;if(this.enable_split_word_search&&(a.indexOf(" ")>=0||0===a.indexOf("["))&&(d=a.replace(/\[|\]/g,"").split(" "),d.length))for(e=0,f=d.length;f>e;e++)if(c=d[e],b.test(c))return!0},AbstractChosen.prototype.choices_count=function(){var a,b,c,d;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,d=this.form_field.options,b=0,c=d.length;c>b;b++)a=d[b],a.selected&&(this.selected_option_count+=1);return this.selected_option_count},AbstractChosen.prototype.choices_click=function(a){return a.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},AbstractChosen.prototype.keyup_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),b){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(a.preventDefault(),this.results_showing)return this.result_select(a);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},AbstractChosen.prototype.clipboard_event_checker=function(){var a=this;return setTimeout(function(){return a.results_search()},50)},AbstractChosen.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},AbstractChosen.prototype.include_option_in_results=function(a){return this.is_multiple&&!this.display_selected_options&&a.selected?!1:!this.display_disabled_options&&a.disabled?!1:a.empty?!1:!0},AbstractChosen.prototype.search_results_touchstart=function(a){return this.touch_started=!0,this.search_results_mouseover(a)},AbstractChosen.prototype.search_results_touchmove=function(a){return this.touch_started=!1,this.search_results_mouseout(a)},AbstractChosen.prototype.search_results_touchend=function(a){return this.touch_started?this.search_results_mouseup(a):void 0},AbstractChosen.prototype.outerHTML=function(a){var b;return a.outerHTML?a.outerHTML:(b=document.createElement("div"),b.appendChild(a),b.innerHTML)},AbstractChosen.browser_is_supported=function(){return"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:/iP(od|hone)/i.test(window.navigator.userAgent)?!1:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!1:!0},AbstractChosen.default_multiple_text="Select Some Options",AbstractChosen.default_single_text="Select an Option",AbstractChosen.default_no_result_text="No results match",AbstractChosen}(),this.Chosen=function(b){function Chosen(){return a=Chosen.__super__.constructor.apply(this,arguments)}return c(Chosen,b),Chosen.prototype.setup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field.hasClassName("chosen-rtl")},Chosen.prototype.set_default_values=function(){return Chosen.__super__.set_default_values.call(this),this.single_temp=new Template('<a class="chosen-single chosen-default" tabindex="-1"><span>#{default}</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'),this.multi_temp=new Template('<ul class="chosen-choices"><li class="search-field"><input type="text" value="#{default}" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'),this.no_results_temp=new Template('<li class="no-results">'+this.results_none_found+' "<span>#{terms}</span>"</li>')},Chosen.prototype.set_up_html=function(){var a,b;return a=["chosen-container"],a.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&a.push(this.form_field.className),this.is_rtl&&a.push("chosen-rtl"),b={"class":a.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(b.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=this.is_multiple?new Element("div",b).update(this.multi_temp.evaluate({"default":this.default_text})):new Element("div",b).update(this.single_temp.evaluate({"default":this.default_text})),this.form_field.hide().insert({after:this.container}),this.dropdown=this.container.down("div.chosen-drop"),this.search_field=this.container.down("input"),this.search_results=this.container.down("ul.chosen-results"),this.search_field_scale(),this.search_no_results=this.container.down("li.no-results"),this.is_multiple?(this.search_choices=this.container.down("ul.chosen-choices"),this.search_container=this.container.down("li.search-field")):(this.search_container=this.container.down("div.chosen-search"),this.selected_item=this.container.down(".chosen-single")),this.results_build(),this.set_tab_index(),this.set_label_behavior(),this.form_field.fire("chosen:ready",{chosen:this})},Chosen.prototype.register_observers=function(){var a=this;return this.container.observe("mousedown",function(b){return a.container_mousedown(b)}),this.container.observe("mouseup",function(b){return a.container_mouseup(b)}),this.container.observe("mouseenter",function(b){return a.mouse_enter(b)}),this.container.observe("mouseleave",function(b){return a.mouse_leave(b)}),this.search_results.observe("mouseup",function(b){return a.search_results_mouseup(b)}),this.search_results.observe("mouseover",function(b){return a.search_results_mouseover(b)}),this.search_results.observe("mouseout",function(b){return a.search_results_mouseout(b)}),this.search_results.observe("mousewheel",function(b){return a.search_results_mousewheel(b)}),this.search_results.observe("DOMMouseScroll",function(b){return a.search_results_mousewheel(b)}),this.search_results.observe("touchstart",function(b){return a.search_results_touchstart(b)}),this.search_results.observe("touchmove",function(b){return a.search_results_touchmove(b)}),this.search_results.observe("touchend",function(b){return a.search_results_touchend(b)}),this.form_field.observe("chosen:updated",function(b){return a.results_update_field(b)}),this.form_field.observe("chosen:activate",function(b){return a.activate_field(b)}),this.form_field.observe("chosen:open",function(b){return a.container_mousedown(b)}),this.form_field.observe("chosen:close",function(b){return a.input_blur(b)}),this.search_field.observe("blur",function(b){return a.input_blur(b)}),this.search_field.observe("keyup",function(b){return a.keyup_checker(b)}),this.search_field.observe("keydown",function(b){return a.keydown_checker(b)}),this.search_field.observe("focus",function(b){return a.input_focus(b)}),this.search_field.observe("cut",function(b){return a.clipboard_event_checker(b)}),this.search_field.observe("paste",function(b){return a.clipboard_event_checker(b)}),this.is_multiple?this.search_choices.observe("click",function(b){return a.choices_click(b)}):this.container.observe("click",function(a){return a.preventDefault()})},Chosen.prototype.destroy=function(){return this.container.ownerDocument.stopObserving("click",this.click_test_action),this.form_field.stopObserving(),this.container.stopObserving(),this.search_results.stopObserving(),this.search_field.stopObserving(),null!=this.form_field_label&&this.form_field_label.stopObserving(),this.is_multiple?(this.search_choices.stopObserving(),this.container.select(".search-choice-close").each(function(a){return a.stopObserving()})):this.selected_item.stopObserving(),this.search_field.tabIndex&&(this.form_field.tabIndex=this.search_field.tabIndex),this.container.remove(),this.form_field.show()},Chosen.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field.disabled,this.is_disabled?(this.container.addClassName("chosen-disabled"),this.search_field.disabled=!0,this.is_multiple||this.selected_item.stopObserving("focus",this.activate_action),this.close_field()):(this.container.removeClassName("chosen-disabled"),this.search_field.disabled=!1,this.is_multiple?void 0:this.selected_item.observe("focus",this.activate_action))},Chosen.prototype.container_mousedown=function(a){return this.is_disabled||(a&&"mousedown"===a.type&&!this.results_showing&&a.stop(),null!=a&&a.target.hasClassName("search-choice-close"))?void 0:(this.active_field?this.is_multiple||!a||a.target!==this.selected_item&&!a.target.up("a.chosen-single")||this.results_toggle():(this.is_multiple&&this.search_field.clear(),this.container.ownerDocument.observe("click",this.click_test_action),this.results_show()),this.activate_field())},Chosen.prototype.container_mouseup=function(a){return"ABBR"!==a.target.nodeName||this.is_disabled?void 0:this.results_reset(a)},Chosen.prototype.search_results_mousewheel=function(a){var b;return b=-a.wheelDelta||a.detail,null!=b?(a.preventDefault(),"DOMMouseScroll"===a.type&&(b=40*b),this.search_results.scrollTop=b+this.search_results.scrollTop):void 0},Chosen.prototype.blur_test=function(){return!this.active_field&&this.container.hasClassName("chosen-container-active")?this.close_field():void 0},Chosen.prototype.close_field=function(){return this.container.ownerDocument.stopObserving("click",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClassName("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},Chosen.prototype.activate_field=function(){return this.container.addClassName("chosen-container-active"),this.active_field=!0,this.search_field.value=this.search_field.value,this.search_field.focus()},Chosen.prototype.test_active_click=function(a){return a.target.up(".chosen-container")===this.container?this.active_field=!0:this.close_field()},Chosen.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=SelectParser.select_to_array(this.form_field),this.is_multiple?this.search_choices.select("li.search-choice").invoke("remove"):this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field.readOnly=!0,this.container.addClassName("chosen-container-single-nosearch")):(this.search_field.readOnly=!1,this.container.removeClassName("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},Chosen.prototype.result_do_highlight=function(a){var b,c,d,e,f;return this.result_clear_highlight(),this.result_highlight=a,this.result_highlight.addClassName("highlighted"),d=parseInt(this.search_results.getStyle("maxHeight"),10),f=this.search_results.scrollTop,e=d+f,c=this.result_highlight.positionedOffset().top,b=c+this.result_highlight.getHeight(),b>=e?this.search_results.scrollTop=b-d>0?b-d:0:f>c?this.search_results.scrollTop=c:void 0},Chosen.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClassName("highlighted"),this.result_highlight=null},Chosen.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field.fire("chosen:maxselected",{chosen:this}),!1):(this.container.addClassName("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.value=this.search_field.value,this.winnow_results(),this.form_field.fire("chosen:showing_dropdown",{chosen:this}))},Chosen.prototype.update_results_content=function(a){return this.search_results.update(a)},Chosen.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClassName("chosen-with-drop"),this.form_field.fire("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},Chosen.prototype.set_tab_index=function(){var a;return this.form_field.tabIndex?(a=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field.tabIndex=a):void 0},Chosen.prototype.set_label_behavior=function(){var a=this;return this.form_field_label=this.form_field.up("label"),null==this.form_field_label&&(this.form_field_label=$$("label[for='"+this.form_field.id+"']").first()),null!=this.form_field_label?this.form_field_label.observe("click",function(b){return a.is_multiple?a.container_mousedown(b):a.activate_field()}):void 0},Chosen.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.value=this.default_text,this.search_field.addClassName("default")):(this.search_field.value="",this.search_field.removeClassName("default"))},Chosen.prototype.search_results_mouseup=function(a){var b;return b=a.target.hasClassName("active-result")?a.target:a.target.up(".active-result"),b?(this.result_highlight=b,this.result_select(a),this.search_field.focus()):void 0},Chosen.prototype.search_results_mouseover=function(a){var b;return b=a.target.hasClassName("active-result")?a.target:a.target.up(".active-result"),b?this.result_do_highlight(b):void 0},Chosen.prototype.search_results_mouseout=function(a){return a.target.hasClassName("active-result")||a.target.up(".active-result")?this.result_clear_highlight():void 0},Chosen.prototype.choice_build=function(a){var b,c,d=this;return b=new Element("li",{"class":"search-choice"}).update("<span>"+a.html+"</span>"),a.disabled?b.addClassName("search-choice-disabled"):(c=new Element("a",{href:"#","class":"search-choice-close",rel:a.array_index}),c.observe("click",function(a){return d.choice_destroy_link_click(a)}),b.insert(c)),this.search_container.insert({before:b})},Chosen.prototype.choice_destroy_link_click=function(a){return a.preventDefault(),a.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(a.target)},Chosen.prototype.choice_destroy=function(a){return this.result_deselect(a.readAttribute("rel"))?(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.value.length<1&&this.results_hide(),a.up("li").remove(),this.search_field_scale()):void 0},Chosen.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),"function"==typeof Event.simulate&&this.form_field.simulate("change"),this.active_field?this.results_hide():void 0},Chosen.prototype.results_reset_cleanup=function(){var a;return this.current_selectedIndex=this.form_field.selectedIndex,a=this.selected_item.down("abbr"),a?a.remove():void 0},Chosen.prototype.result_select=function(a){var b,c;return this.result_highlight?(b=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field.fire("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?b.removeClassName("active-result"):this.reset_single_select_options(),b.addClassName("result-selected"),c=this.results_data[b.getAttribute("data-option-array-index")],c.selected=!0,this.form_field.options[c.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(c):this.single_set_selected_text(c.text),(a.metaKey||a.ctrlKey)&&this.is_multiple||this.results_hide(),this.search_field.value="","function"!=typeof Event.simulate||!this.is_multiple&&this.form_field.selectedIndex===this.current_selectedIndex||this.form_field.simulate("change"),this.current_selectedIndex=this.form_field.selectedIndex,this.search_field_scale())):void 0},Chosen.prototype.single_set_selected_text=function(a){return null==a&&(a=this.default_text),a===this.default_text?this.selected_item.addClassName("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClassName("chosen-default")),this.selected_item.down("span").update(a)},Chosen.prototype.result_deselect=function(a){var b;return b=this.results_data[a],this.form_field.options[b.options_index].disabled?!1:(b.selected=!1,this.form_field.options[b.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),"function"==typeof Event.simulate&&this.form_field.simulate("change"),this.search_field_scale(),!0)},Chosen.prototype.single_deselect_control_build=function(){return this.allow_single_deselect?(this.selected_item.down("abbr")||this.selected_item.down("span").insert({after:'<abbr class="search-choice-close"></abbr>'}),this.selected_item.addClassName("chosen-single-with-deselect")):void 0},Chosen.prototype.get_search_text=function(){return this.search_field.value===this.default_text?"":this.search_field.value.strip().escapeHTML()},Chosen.prototype.winnow_results_set_highlight=function(){var a;return this.is_multiple||(a=this.search_results.down(".result-selected.active-result")),null==a&&(a=this.search_results.down(".active-result")),null!=a?this.result_do_highlight(a):void 0},Chosen.prototype.no_results=function(a){return this.search_results.insert(this.no_results_temp.evaluate({terms:a})),this.form_field.fire("chosen:no_results",{chosen:this})},Chosen.prototype.no_results_clear=function(){var a,b;for(a=null,b=[];a=this.search_results.down(".no-results");)b.push(a.remove());return b},Chosen.prototype.keydown_arrow=function(){var a;return this.results_showing&&this.result_highlight?(a=this.result_highlight.next(".active-result"))?this.result_do_highlight(a):void 0:this.results_show()},Chosen.prototype.keyup_arrow=function(){var a,b,c;return this.results_showing||this.is_multiple?this.result_highlight?(c=this.result_highlight.previousSiblings(),a=this.search_results.select("li.active-result"),b=c.intersect(a),b.length?this.result_do_highlight(b.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},Chosen.prototype.keydown_backstroke=function(){var a;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.down("a")),this.clear_backstroke()):(a=this.search_container.siblings().last(),a&&a.hasClassName("search-choice")&&!a.hasClassName("search-choice-disabled")?(this.pending_backstroke=a,this.pending_backstroke&&this.pending_backstroke.addClassName("search-choice-focus"),this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClassName("search-choice-focus")):void 0)},Chosen.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClassName("search-choice-focus"),this.pending_backstroke=null},Chosen.prototype.keydown_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),8!==b&&this.pending_backstroke&&this.clear_backstroke(),b){case 8:this.backstroke_length=this.search_field.value.length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(a),this.mouse_on_container=!1;break;case 13:a.preventDefault();break;case 38:a.preventDefault(),this.keyup_arrow();break;case 40:a.preventDefault(),this.keydown_arrow()}},Chosen.prototype.search_field_scale=function(){var a,b,c,d,e,f,g,h,i;if(this.is_multiple){for(c=0,g=0,e="position:absolute; left: -1000px; top: -1000px; display:none;",f=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],h=0,i=f.length;i>h;h++)d=f[h],e+=d+":"+this.search_field.getStyle(d)+";";return a=new Element("div",{style:e}).update(this.search_field.value.escapeHTML()),document.body.appendChild(a),g=Element.measure(a,"width")+25,a.remove(),b=this.container.getWidth(),g>b-10&&(g=b-10),this.search_field.setStyle({width:g+"px"})}},Chosen}(AbstractChosen)}.call(this); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/chosen/chosen.proto.min.js | chosen.proto.min.js |
(function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.util.clone(e[i]));return r;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var r=t.util.clone(t.languages[e]);for(var i in n)r[i]=n[i];return r},insertBefore:function(e,n,r,i){i=i||t.languages;var s=i[e],o={};for(var u in s)if(s.hasOwnProperty(u)){if(u==n)for(var a in r)r.hasOwnProperty(a)&&(o[a]=r[a]);o[u]=s[u]}return i[e]=o},DFS:function(e,n){for(var r in e){n.call(e,r,e[r]);t.util.type(e)==="Object"&&t.languages.DFS(e[r],n)}}},highlightAll:function(e,n){var r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,s;s=r[i++];)t.highlightElement(s,e===!0,n)},highlightElement:function(r,i,s){var o,u,a=r;while(a&&!e.test(a.className))a=a.parentNode;if(a){o=(a.className.match(e)||[,""])[1];u=t.languages[o]}if(!u)return;r.className=r.className.replace(e,"").replace(/\s+/g," ")+" language-"+o;a=r.parentNode;/pre/i.test(a.nodeName)&&(a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+o);var f=r.textContent;if(!f)return;f=f.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ");var l={element:r,language:o,grammar:u,code:f};t.hooks.run("before-highlight",l);if(i&&self.Worker){var c=new Worker(t.filename);c.onmessage=function(e){l.highlightedCode=n.stringify(JSON.parse(e.data),o);t.hooks.run("before-insert",l);l.element.innerHTML=l.highlightedCode;s&&s.call(l.element);t.hooks.run("after-highlight",l)};c.postMessage(JSON.stringify({language:l.language,code:l.code}))}else{l.highlightedCode=t.highlight(l.code,l.grammar,l.language);t.hooks.run("before-insert",l);l.element.innerHTML=l.highlightedCode;s&&s.call(r);t.hooks.run("after-highlight",l)}},highlight:function(e,r,i){return n.stringify(t.tokenize(e,r),i)},tokenize:function(e,n,r){var i=t.Token,s=[e],o=n.rest;if(o){for(var u in o)n[u]=o[u];delete n.rest}e:for(var u in n){if(!n.hasOwnProperty(u)||!n[u])continue;var a=n[u],f=a.inside,l=!!a.lookbehind,c=0;a=a.pattern||a;for(var h=0;h<s.length;h++){var p=s[h];if(s.length>e.length)break e;if(p instanceof i)continue;a.lastIndex=0;var d=a.exec(p);if(d){l&&(c=d[1].length);var v=d.index-1+c,d=d[0].slice(c),m=d.length,g=v+m,y=p.slice(0,v+1),b=p.slice(g+1),w=[h,1];y&&w.push(y);var E=new i(u,f?t.tokenize(d,f):d);w.push(E);b&&w.push(b);Array.prototype.splice.apply(s,w)}}}return s},hooks:{all:{},add:function(e,n){var r=t.hooks.all;r[e]=r[e]||[];r[e].push(n)},run:function(e,n){var r=t.hooks.all[e];if(!r||!r.length)return;for(var i=0,s;s=r[i++];)s(n)}}},n=t.Token=function(e,t){this.type=e;this.content=t};n.stringify=function(e,r,i){if(typeof e=="string")return e;if(Object.prototype.toString.call(e)=="[object Array]")return e.map(function(t){return n.stringify(t,r,e)}).join("");var s={type:e.type,content:n.stringify(e.content,r,i),tag:"span",classes:["token",e.type],attributes:{},language:r,parent:i};s.type=="comment"&&(s.attributes.spellcheck="true");t.hooks.run("wrap",s);var o="";for(var u in s.attributes)o+=u+'="'+(s.attributes[u]||"")+'"';return"<"+s.tag+' class="'+s.classes.join(" ")+'" '+o+">"+s.content+"</"+s.tag+">"};if(!self.document){self.addEventListener("message",function(e){var n=JSON.parse(e.data),r=n.language,i=n.code;self.postMessage(JSON.stringify(t.tokenize(i,t.languages[r])));self.close()},!1);return}var r=document.getElementsByTagName("script");r=r[r.length-1];if(r){t.filename=r.src;document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)}})();;
Prism.languages.markup={comment:/<!--[\w\W]*?-->/g,prolog:/<\?.+?\?>/,doctype:/<!DOCTYPE.+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|\w+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&/,"&"))});;
Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*{))/gi,inside:{punctuation:/[;:]/g}},url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\};]*(?=\s*\{)/g,property:/(\b|\B)[\w-]+(?=\s*:)/ig,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,ignore:/&(lt|gt|amp);/gi,punctuation:/[\{\};:]/g};Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{style:{pattern:/(<|<)style[\w\W]*?(>|>)[\w\W]*?(<|<)\/style(>|>)/ig,inside:{tag:{pattern:/(<|<)style[\w\W]*?(>|>)|(<|<)\/style(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}});;
Prism.languages.clike={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,lookbehind:!0},string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/ig,inside:{punctuation:/\(/}}, number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|(&){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};;
Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(var|let|if|else|while|do|for|return|in|instanceof|function|new|with|typeof|try|catch|finally|null|break|continue)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g});Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}});Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(<|<)script[\w\W]*?(>|>)[\w\W]*?(<|<)\/script(>|>)/ig,inside:{tag:{pattern:/(<|<)script[\w\W]*?(>|>)|(<|<)\/script(>|>)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});; | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/chosen/docsupport/prism.js | prism.js |
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function encode(s) {
return config.raw ? s : encodeURIComponent(s);
}
function decode(s) {
return config.raw ? s : decodeURIComponent(s);
}
function stringifyCookieValue(value) {
return encode(config.json ? JSON.stringify(value) : String(value));
}
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
s = decodeURIComponent(s.replace(pluses, ' '));
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
function read(s, converter) {
var value = config.raw ? s : parseCookieValue(s);
return $.isFunction(converter) ? converter(value) : value;
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined && !$.isFunction(value)) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setTime(+t + days * 864e+5);
}
return (document.cookie = [
encode(key), '=', stringifyCookieValue(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
// If second argument (value) is a function it's a converter...
result = read(cookie, value);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = read(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) === undefined) {
return false;
}
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return !$.cookie(key);
};
})); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery-cookie/jquery.cookie.js | jquery.cookie.js |
# jQuery
> jQuery is a fast, small, and feature-rich JavaScript library.
For information on how to get started and how to use jQuery, please see [jQuery's documentation](http://api.jquery.com/).
For source files and issues, please visit the [jQuery repo](https://github.com/jquery/jquery).
## Including jQuery
Below are some of the most common ways to include jQuery.
### Browser
#### Script tag
```html
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
```
#### Babel
[Babel](http://babeljs.io/) is a next generation JavaScript compiler. One of the features is the ability to use ES6/ES2015 modules now, even though browsers do not yet support this feature natively.
```js
import $ from "jquery";
```
#### Browserify/Webpack
There are several ways to use [Browserify](http://browserify.org/) and [Webpack](https://webpack.github.io/). For more information on using these tools, please refer to the corresponding project's documention. In the script, including jQuery will usually look like this...
```js
var $ = require("jquery");
```
#### AMD (Asynchronous Module Definition)
AMD is a module format built for the browser. For more information, we recommend [require.js' documentation](http://requirejs.org/docs/whyamd.html).
```js
define(["jquery"], function($) {
});
```
### Node
To include jQuery in [Node](nodejs.org), first install with npm.
```sh
npm install jquery
```
For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as [jsdom](https://github.com/tmpvar/jsdom). This can be useful for testing purposes.
```js
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
```
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/README.md | README.md |
define( [
"./core",
"./var/document",
"./var/rnotwhite",
"./ajax/var/location",
"./ajax/var/nonce",
"./ajax/var/rquery",
"./core/init",
"./ajax/parseJSON",
"./ajax/parseXML",
"./event/trigger",
"./deferred"
], function( jQuery, document, rnotwhite, location, nonce, rquery ) {
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 = /^\/\//,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( 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: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": 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,
// Url cleanup var
urlAnchor,
// 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 || location.href ) + "" ).replace( rhash, "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE8-11+
// IE throws exception if url is malformed, e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE8-11+
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( 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 ] );
}
// If request was aborted inside ajaxSend, stop there
if ( state === 2 ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.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 ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/ajax.js | ajax.js |
define( [
"./core",
"./var/document",
"./var/rcssNum",
"./css/var/cssExpand",
"./var/rnotwhite",
"./css/var/isHidden",
"./css/adjustCSS",
"./css/defaultDisplay",
"./data/var/dataPriv",
"./core/init",
"./effects/Tween",
"./queue",
"./css",
"./deferred",
"./traversing"
], function( jQuery, document, rcssNum, cssExpand, rnotwhite,
isHidden, adjustCSS, defaultDisplay, dataPriv ) {
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = dataPriv.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" ?
dataPriv.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 = dataPriv.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;
dataPriv.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 = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3
// 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: {},
easing: jQuery.easing._default
}, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// Resolve when we played the last frame; otherwise, reject
if ( gotoEnd ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
} ),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
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, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnotwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
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 || dataPriv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = dataPriv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// 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 = window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
window.clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/effects.js | effects.js |
define( [
"./core",
"./var/rnotwhite"
], function( jQuery, rnotwhite ) {
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
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" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( index <= firingIndex ) {
firingIndex--;
}
}
} );
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ?
jQuery.inArray( fn, list ) > -1 :
list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/callbacks.js | callbacks.js |
define( [
"./core",
"./var/concat",
"./var/push",
"./core/access",
"./manipulation/var/rcheckableType",
"./manipulation/var/rtagName",
"./manipulation/var/rscriptType",
"./manipulation/wrapMap",
"./manipulation/getAll",
"./manipulation/setGlobalEval",
"./manipulation/buildFragment",
"./manipulation/support",
"./data/var/dataPriv",
"./data/var/dataUser",
"./data/var/acceptData",
"./core/init",
"./traversing",
"./selector",
"./event"
], function( jQuery, concat, push, access,
rcheckableType, rtagName, rscriptType,
wrapMap, getAll, setGlobalEval, buildFragment, support,
dataPriv, dataUser, acceptData ) {
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,
// Support: IE 10-11, Edge 10240+
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
// 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;
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android<4.1, PhantomJS<2
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: 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;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Support: Chrome <= 35-45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <= 35-45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
// Keep domManip exposed until 3.0 (gh-2225)
domManip: domManip,
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each( function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
} );
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/manipulation.js | manipulation.js |
define( [
"./core",
"./var/slice",
"./callbacks"
], function( jQuery, slice ) {
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()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} 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()
.progress( updateFunc( i, progressContexts, progressValues ) )
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject );
} else {
--remaining;
}
}
}
// If we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/deferred.js | deferred.js |
define( [
"./core",
"./var/pnum",
"./core/access",
"./css/var/rmargin",
"./var/document",
"./var/rcssNum",
"./css/var/rnumnonpx",
"./css/var/cssExpand",
"./css/var/isHidden",
"./css/var/getStyles",
"./css/var/swap",
"./css/curCSS",
"./css/adjustCSS",
"./css/defaultDisplay",
"./css/addGetHookIf",
"./css/support",
"./data/var/dataPriv",
"./core/init",
"./core/ready",
"./selector" // contains
], function( jQuery, pnum, access, rmargin, document, rcssNum, rnumnonpx, cssExpand, isHidden,
getStyles, swap, curCSS, adjustCSS, defaultDisplay, addGetHookIf, support, dataPriv ) {
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]).+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = 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";
// Support: IE11 only
// In IE 11 fullscreen elements inside of an iframe have
// 100x too small dimensions (gh-1764).
if ( document.msFullscreenElement && window.top !== window ) {
// Support: IE11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
if ( elem.getClientRects().length ) {
val = Math.round( elem.getBoundingClientRect()[ name ] * 100 );
}
}
// 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 ] = dataPriv.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 ] = dataPriv.access(
elem,
"olddisplay",
defaultDisplay( elem.nodeName )
);
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
dataPriv.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: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// 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( origName ) || origName );
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
elem.offsetWidth === 0 ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = extra && getStyles( elem ),
subtract = extra && augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
);
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ name ] = value;
value = jQuery.css( elem, name );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return 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();
}
} );
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/css.js | css.js |
define( [
"./core",
"./core/access",
"./data/var/dataPriv",
"./data/var/dataUser"
], function( jQuery, access, dataPriv, dataUser ) {
// 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, "-$&" ).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
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.remove( elem, name );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: 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 ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data, camelKey;
// 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 = dataUser.get( elem, key ) ||
// Try to find dashed key if it exists (gh-2779)
// This is for 2.2.x only
dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() );
if ( data !== undefined ) {
return data;
}
camelKey = jQuery.camelCase( key );
// Attempt to get data from the cache
// with the key camelized
data = dataUser.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...
camelKey = jQuery.camelCase( key );
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 = dataUser.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...*
dataUser.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 ) {
dataUser.set( this, key, value );
}
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/data.js | data.js |
define( [
"./core",
"./data/var/dataPriv",
"./deferred",
"./callbacks"
], function( jQuery, dataPriv ) {
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.remove( elem, [ type + "queue", key ] );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/queue.js | queue.js |
define( [
"./core",
"./var/indexOf",
"./traversing/var/dir",
"./traversing/var/siblings",
"./traversing/var/rneedsContext",
"./core/init",
"./traversing/findFilter",
"./selector"
], function( jQuery, indexOf, dir, siblings, rneedsContext ) {
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter( function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
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.uniqueSort( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
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.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/traversing.js | traversing.js |
define( [
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* 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 ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
offset: function( options ) {
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;
}
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 )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari<7-8+, Chrome<37-44+
// 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;
}
}
);
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/offset.js | offset.js |
define( [
"./core",
"./var/document",
"./var/documentElement",
"./var/hasOwn",
"./var/indexOf"
], function( jQuery, document, documentElement, hasOwn, indexOf ) {
/*
* Optional (non-Sizzle) selector module for custom builds.
*
* Note that this DOES NOT SUPPORT many documented jQuery
* features in exchange for its smaller size:
*
* Attribute not equal selector
* Positional selectors (:first; :eq(n); :odd; etc.)
* Type selectors (:input; :checkbox; :button; etc.)
* State-based selectors (:animated; :visible; :hidden; etc.)
* :has(selector)
* :not(complex selector)
* custom selectors via Sizzle extensions
* Leading combinators (e.g., $collection.find("> *"))
* Reliable functionality on XML fragments
* Requiring all parts of a selector to match elements under context
* (e.g., $div.find("div > *") now matches children of $div)
* Matching against non-elements
* Reliable sorting of disconnected nodes
* querySelectorAll bug fixes (e.g., unreliable :focus on WebKit)
*
* If any of these are unacceptable tradeoffs, either use Sizzle or
* customize this stub for the project's specific needs.
*/
var hasDuplicate, sortInput,
sortStable = jQuery.expando.split( "" ).sort( sortOrder ).join( "" ) === jQuery.expando,
matches = documentElement.matches ||
documentElement.webkitMatchesSelector ||
documentElement.mozMatchesSelector ||
documentElement.oMatchesSelector ||
documentElement.msMatchesSelector;
function sortOrder( 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 ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === document &&
jQuery.contains( document, a ) ) {
return -1;
}
if ( b === document || b.ownerDocument === document &&
jQuery.contains( document, b ) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
function uniqueSort( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
hasDuplicate = false;
sortInput = !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;
}
jQuery.extend( {
find: function( selector, context, results, seed ) {
var elem, nodeType,
i = 0;
results = results || [];
context = context || document;
// Same basic safeguard as Sizzle
if ( !selector || typeof selector !== "string" ) {
return results;
}
// Early return if context is not an element or document
if ( ( nodeType = context.nodeType ) !== 1 && nodeType !== 9 ) {
return [];
}
if ( seed ) {
while ( ( elem = seed[ i++ ] ) ) {
if ( jQuery.find.matchesSelector( elem, selector ) ) {
results.push( elem );
}
}
} else {
jQuery.merge( results, context.querySelectorAll( selector ) );
}
return results;
},
uniqueSort: uniqueSort,
unique: uniqueSort,
text: 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 += jQuery.text( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
return elem.textContent;
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
},
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( bup ) );
},
isXMLDoc: 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;
},
expr: {
attrHandle: {},
match: {
bool: new RegExp( "^(?:checked|selected|async|autofocus|autoplay|controls|defer" +
"|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$", "i" ),
needsContext: /^[\x20\t\r\n\f]*[>+~]/
}
}
} );
jQuery.extend( jQuery.find, {
matches: function( expr, elements ) {
return jQuery.find( expr, null, null, elements );
},
matchesSelector: function( elem, expr ) {
return matches.call( elem, expr );
},
attr: function( elem, name ) {
var fn = jQuery.expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
value = fn && hasOwn.call( jQuery.expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, jQuery.isXMLDoc( elem ) ) :
undefined;
return value !== undefined ? value : elem.getAttribute( name );
}
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/selector-native.js | selector-native.js |
define( [
"./var/arr",
"./var/document",
"./var/slice",
"./var/concat",
"./var/push",
"./var/indexOf",
"./var/class2type",
"./var/toString",
"./var/hasOwn",
"./var/support"
], function( arr, document, slice, concat, push, indexOf, class2type, toString, hasOwn, support ) {
var
version = "@VERSION",
// 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.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = 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)
var realStringObj = obj && obj.toString();
return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
},
isPlainObject: function( obj ) {
var key;
// 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;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call( obj, "constructor" ) &&
!hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
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();
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android<4.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 length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
// JSHint would error on this code due to the Symbol not being defined in ES5.
// Defining this global in .jshintrc would create a danger of using the global
// unguarded in another place, it seems safer to just disable JSHint for these
// three lines.
/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
/* jshint ignore: end */
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: 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 = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/core.js | core.js |
define( [
"./core",
"./manipulation/var/rcheckableType",
"./core/init",
"./traversing", // filter
"./attributes/prop"
], function( jQuery, rcheckableType ) {
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" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, 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();
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/serialize.js | serialize.js |
define( [
"./core",
"./var/document",
"./var/rnotwhite",
"./var/slice",
"./data/var/dataPriv",
"./core/init",
"./selector"
], function( jQuery, document, rnotwhite, slice, dataPriv ) {
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE9
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( 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 );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( 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 data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
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 = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support (at least): Chrome, IE9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox<=42+
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( 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 ) > -1 :
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 detail 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;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android<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 = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://code.google.com/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/event.js | event.js |
define( [
"../core",
"../var/document",
"../data/var/dataPriv",
"../data/var/acceptData",
"../var/hasOwn",
"../event"
], function( jQuery, document, dataPriv, acceptData, hasOwn ) {
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( ( !special._default ||
special._default.apply( eventPath.pop(), data ) === false ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
// Previously, `originalEvent: {}` was set here, so stopPropagation call
// would not be triggered on donor event, since in our own
// jQuery.event.stopPropagation function we had a check for existence of
// originalEvent.stopPropagation method, so, consequently it would be a noop.
//
// But now, this "simulate" function is used only for events
// for which stopPropagation() is noop, so there is no need for that anymore.
//
// For the 1.x branch though, guard for "click" and "submit"
// events is still used, but was moved to jQuery.event.stopPropagation function
// because `originalEvent` should point to the original event for the constancy
// with other events and for more focused logic
}
);
jQuery.event.trigger( e, null, elem );
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
} );
jQuery.fn.extend( {
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
return jQuery;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/event/trigger.js | trigger.js |
define( [
"../core",
"./var/rtagName",
"./var/rscriptType",
"./wrapMap",
"./getAll",
"./setGlobalEval"
], function( jQuery, rtagName, rscriptType, wrapMap, getAll, setGlobalEval ) {
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: Android<4.1, PhantomJS<2
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android<4.1, PhantomJS<2
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
}
return buildFragment;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/manipulation/buildFragment.js | buildFragment.js |
define( [
"../core",
"../var/document",
"../var/documentElement",
"../var/support"
], function( jQuery, document, documentElement, support ) {
( function() {
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: 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:8px;height:0;top:0;left:-9999px;" +
"padding:0;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 computeStyleTests() {
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;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild( container );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild( container );
}
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.
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelMarginRight: function() {
// Support: Android 4.0-4.3
// We're checking for boxSizingReliableVal here instead of pixelMarginRightVal
// since that compresses better and they're computed together anyway.
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return pixelMarginRightVal;
},
reliableMarginLeft: function() {
// Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return reliableMarginLeftVal;
},
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: Android 2.3
// Vendor-prefix box-sizing
"-webkit-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";
documentElement.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv ).marginRight );
documentElement.removeChild( container );
div.removeChild( marginDiv );
return ret;
}
} );
} )();
return support;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/css/support.js | support.js |
define( [
"../core",
"../var/indexOf",
"./var/rneedsContext",
"../selector"
], function( jQuery, indexOf, rneedsContext ) {
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 ) > -1 ) !== 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;
}
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/traversing/findFilter.js | findFilter.js |
define( [
"../core",
"./var/nonce",
"./var/rquery",
"../ajax"
], function( jQuery, nonce, rquery ) {
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// Force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// Save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/ajax/jsonp.js | jsonp.js |
define( [
"../core",
"../core/parseHTML",
"../ajax",
"../traversing",
"../manipulation",
"../selector",
// Optional event/alias dependency
"../event/alias"
], function( jQuery ) {
// 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 > -1 ) {
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.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
} ).done( function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/ajax/load.js | load.js |
define( [
"../core",
"../var/support",
"../ajax"
], function( jQuery, support ) {
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE9
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = callback( "error" );
// Support: IE9
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = callback( "abort" );
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/ajax/xhr.js | xhr.js |
define( [
"../core",
"./support",
"../core/init"
], function( jQuery, support ) {
var rreturn = /\r/g,
rspaces = /[\x20\t\r\n\f]+/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)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
}
},
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 ];
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( 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( jQuery.valHooks.option.get( option ), values ) > -1
) {
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 ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/attributes/val.js | val.js |
define( [
"../core",
"../core/access",
"./support",
"../selector"
], function( jQuery, access, support ) {
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/attributes/prop.js | prop.js |
define( [
"../core",
"../core/access",
"./support",
"../var/rnotwhite",
"../selector"
], function( jQuery, access, support, rnotwhite ) {
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// 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 : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
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 );
}
}
}
} );
// 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;
};
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/attributes/attr.js | attr.js |
define( [
"../core",
"../var/rnotwhite",
"../data/var/dataPriv",
"../core/init"
], function( jQuery, rnotwhite, dataPriv ) {
var rclass = /[\t\r\n\f]/g;
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).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 ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( 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 ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", className );
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + getClass( elem ) + " " ).replace( rclass, " " )
.indexOf( className ) > -1
) {
return true;
}
}
return false;
}
} );
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/attributes/classes.js | classes.js |
define( [
"../core",
"../var/document",
"../core/init",
"../deferred"
], function( jQuery, document ) {
// 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 );
window.removeEventListener( "load", completed );
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.
// Support: IE9-10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/core/ready.js | ready.js |
define( [
"../core",
"../var/document",
"./var/rsingleTag",
"../traversing/findFilter"
], function( jQuery, document, rsingleTag ) {
// 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, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[ 0 ] === "<" &&
selector[ selector.length - 1 ] === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
// 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 || root ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
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 );
return init;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/core/init.js | init.js |
define( [
"../core",
"../css"
], function( jQuery ) {
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: 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;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/effects/Tween.js | Tween.js |
define( [
"../core",
"../var/rnotwhite",
"./var/acceptData"
], function( jQuery, rnotwhite, acceptData ) {
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
register: function( owner, initial ) {
var value = initial || {};
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable, non-writable property
// configurability must be true to allow the property to be
// deleted with the delete operator
} else {
Object.defineProperty( owner, this.expando, {
value: value,
writable: true,
configurable: true
} );
}
return owner[ this.expando ];
},
cache: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( !acceptData( owner ) ) {
return {};
}
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
owner[ this.expando ] && owner[ this.expando ][ 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,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key === undefined ) {
this.register( owner );
} 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 ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <= 35-45+
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://code.google.com/p/chromium/issues/detail?id=378607
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
return Data;
} ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/src/data/Data.js | Data.js |
!function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=R.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),"function"==typeof define&&define.amd?define(function(){return fa}):"undefined"!=typeof module&&module.exports?module.exports=fa:a.Sizzle=fa}(window);
//# sourceMappingURL=sizzle.min.map | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/sizzle/dist/sizzle.min.js | sizzle.min.js |
(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
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
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 m, i, elem, nid, nidselect, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
while ( i-- ) {
groups[i] = nidselect + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created 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 = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~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;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( (parent = document.defaultView) && parent.top !== parent ) {
// Support: IE 11
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* 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( document.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !document.getElementsByName || !document.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 );
return m ? [ 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 ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.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 + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// 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.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
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 = document.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 self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": 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, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( (oldCache = uniqueCache[ 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
uniqueCache[ 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 || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
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,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( 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;
}
});
}
// EXPOSE
if ( typeof define === "function" && define.amd ) {
define(function() { return Sizzle; });
// Sizzle requires that there be a global window in Common-JS like environments
} else if ( typeof module !== "undefined" && module.exports ) {
module.exports = Sizzle;
} else {
window.Sizzle = Sizzle;
}
// EXPOSE
})( window ); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/jquery/sizzle/dist/sizzle.js | sizzle.js |
__
/\ \ __
__ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____
/\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\
\ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\
\ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/
\/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/
\ \____/
\/___/
Underscore.js is a utility-belt library for JavaScript that provides
support for the usual functional suspects (each, map, reduce, filter...)
without extending any core JavaScript objects.
For Docs, License, Tests, and pre-packed downloads, see:
http://underscorejs.org
Underscore is an open-sourced component of DocumentCloud:
https://github.com/documentcloud
Many thanks to our contributors:
https://github.com/jashkenas/underscore/contributors
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/underscore/README.md | README.md |
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.8.3';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
var cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};
_.iteratee = function(value, context) {
return cb(value, context, Infinity);
};
// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};
// An internal function for creating a new object that inherits from another.
var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
};
var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) {
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
// Determine the initial value if none is provided.
if (arguments.length < 3) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
return iterator(obj, iteratee, memo, keys, index, length);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = createReduce(-1);
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var key;
if (isArrayLike(obj)) {
key = _.findIndex(obj, predicate, context);
} else {
key = _.findKey(obj, predicate, context);
}
if (key !== void 0 && key !== -1) return obj[key];
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given item (using `===`).
// Aliased as `includes` and `include`.
_.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = isArrayLike(obj) ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = cb(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = cb(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, startIndex) {
var output = [], idx = 0;
for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
//flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
var j = 0, len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(arguments, true, true, 1);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
return _.unzip(arguments);
};
// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
var length = array && _.max(array, getLength).length || 0;
var result = Array(length);
for (var index = 0; index < length; index++) {
result[index] = _.pluck(array, index);
}
return result;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Generator function to create the findIndex and findLastIndex functions
function createPredicateIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test
_.findIndex = createPredicateIndexFinder(1);
_.findLastIndex = createPredicateIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Generator function to create the indexOf and lastIndexOf functions
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments
var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
var args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = _.partial(_.delay, _, 1);
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed on and after the Nth call.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed up to (but not including) the Nth call.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
if (times <= 1) func = null;
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
function collectNonEnumProps(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
var constructor = obj.constructor;
var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
// Constructor is a special case.
var prop = 'constructor';
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}
// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve all the property names of an object.
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Returns the results of applying the iteratee to each element of the object
// In contrast to _.map it returns an object
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = _.keys(obj),
length = keys.length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = createAssigner(_.allKeys);
// Assigns a given object with all the own properties in the passed-in object(s)
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
_.extendOwn = _.assign = createAssigner(_.keys);
// Returns the first key on an object that passes a predicate test
_.findKey = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = _.keys(obj), key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (predicate(obj[key], key, obj)) return key;
}
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(object, oiteratee, context) {
var result = {}, obj = object, iteratee, keys;
if (obj == null) return result;
if (_.isFunction(oiteratee)) {
keys = _.allKeys(obj);
iteratee = optimizeCb(oiteratee, context);
} else {
keys = flatten(arguments, false, false, 1);
iteratee = function(value, key, obj) { return key in obj; };
obj = Object(obj);
}
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(flatten(arguments, false, false, 1), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = createAssigner(_.allKeys, true);
// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
_.create = function(prototype, props) {
var result = baseCreate(prototype);
if (props) _.extendOwn(result, props);
return result;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Returns whether an object has a given set of `key:value` pairs.
_.isMatch = function(object, attrs) {
var keys = _.keys(attrs), length = keys.length;
if (object == null) return !length;
var obj = Object(object);
for (var i = 0; i < length; i++) {
var key = keys[i];
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
var areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a != 'object' || typeof b != 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), and in Safari 8 (#1929).
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
// Predicate-generating functions. Often useful outside of Underscore.
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = property;
// Generates a function for a given object that returns a given property.
_.propertyOf = function(obj) {
return obj == null ? function(){} : function(key) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
_.matcher = _.matches = function(attrs) {
attrs = _.extendOwn({}, attrs);
return function(obj) {
return _.isMatch(obj, attrs);
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = optimizeCb(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property, fallback) {
var value = object == null ? void 0 : object[property];
if (value === void 0) {
value = fallback;
}
return _.isFunction(value) ? value.call(object) : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// Provide unwrapping proxy for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
return '' + this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this)); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/underscore/underscore.js | underscore.js |
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this);
//# sourceMappingURL=underscore-min.map | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/underscore/underscore-min.js | underscore-min.js |
(function(f){"function"==typeof define?define(f):"function"==typeof YUI?YUI.add("es5",f):f()})(function(){Function.prototype.bind||(Function.prototype.bind=function(d){var c=this;if("function"!=typeof c)throw new TypeError("Function.prototype.bind called on incompatible "+c);var a=n.call(arguments,1),b=function(){if(this instanceof b){var e=function(){};e.prototype=c.prototype;var e=new e,i=c.apply(e,a.concat(n.call(arguments)));return Object(i)===i?i:e}return c.apply(d,a.concat(n.call(arguments)))};
return b});var f=Function.prototype.call,m=Object.prototype,n=Array.prototype.slice,l=f.bind(m.toString),o=f.bind(m.hasOwnProperty);o(m,"__defineGetter__")&&(f.bind(m.__defineGetter__),f.bind(m.__defineSetter__),f.bind(m.__lookupGetter__),f.bind(m.__lookupSetter__));Array.isArray||(Array.isArray=function(d){return l(d)=="[object Array]"});Array.prototype.forEach||(Array.prototype.forEach=function(d,c){var a=j(this),b=-1,e=a.length>>>0;if(l(d)!="[object Function]")throw new TypeError;for(;++b<e;)b in
a&&d.call(c,a[b],b,a)});Array.prototype.map||(Array.prototype.map=function(d,c){var a=j(this),b=a.length>>>0,e=Array(b);if(l(d)!="[object Function]")throw new TypeError(d+" is not a function");for(var i=0;i<b;i++)i in a&&(e[i]=d.call(c,a[i],i,a));return e});Array.prototype.filter||(Array.prototype.filter=function(d,c){var a=j(this),b=a.length>>>0,e=[],i;if(l(d)!="[object Function]")throw new TypeError(d+" is not a function");for(var f=0;f<b;f++)if(f in a){i=a[f];d.call(c,i,f,a)&&e.push(i)}return e});
Array.prototype.every||(Array.prototype.every=function(d,c){var a=j(this),b=a.length>>>0;if(l(d)!="[object Function]")throw new TypeError(d+" is not a function");for(var e=0;e<b;e++)if(e in a&&!d.call(c,a[e],e,a))return false;return true});Array.prototype.some||(Array.prototype.some=function(d,c){var a=j(this),b=a.length>>>0;if(l(d)!="[object Function]")throw new TypeError(d+" is not a function");for(var e=0;e<b;e++)if(e in a&&d.call(c,a[e],e,a))return true;return false});Array.prototype.reduce||
(Array.prototype.reduce=function(d){var c=j(this),a=c.length>>>0;if(l(d)!="[object Function]")throw new TypeError(d+" is not a function");if(!a&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var b=0,e;if(arguments.length>=2)e=arguments[1];else{do{if(b in c){e=c[b++];break}if(++b>=a)throw new TypeError("reduce of empty array with no initial value");}while(1)}for(;b<a;b++)b in c&&(e=d.call(void 0,e,c[b],b,c));return e});Array.prototype.reduceRight||(Array.prototype.reduceRight=
function(d){var c=j(this),a=c.length>>>0;if(l(d)!="[object Function]")throw new TypeError(d+" is not a function");if(!a&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var b,a=a-1;if(arguments.length>=2)b=arguments[1];else{do{if(a in c){b=c[a--];break}if(--a<0)throw new TypeError("reduceRight of empty array with no initial value");}while(1)}do a in this&&(b=d.call(void 0,b,c[a],a,c));while(a--);return b});Array.prototype.indexOf||(Array.prototype.indexOf=
function(d){var c=j(this),a=c.length>>>0;if(!a)return-1;var b=0;arguments.length>1&&(b=p(arguments[1]));for(b=b>=0?b:Math.max(0,a+b);b<a;b++)if(b in c&&c[b]===d)return b;return-1});Array.prototype.lastIndexOf||(Array.prototype.lastIndexOf=function(d){var c=j(this),a=c.length>>>0;if(!a)return-1;var b=a-1;arguments.length>1&&(b=Math.min(b,p(arguments[1])));for(b=b>=0?b:a-Math.abs(b);b>=0;b--)if(b in c&&d===c[b])return b;return-1});if(!Object.keys){var q=!0,r="toString toLocaleString valueOf hasOwnProperty isPrototypeOf propertyIsEnumerable constructor".split(" "),
s=r.length,t;for(t in{toString:null})q=!1;Object.keys=function(d){if(typeof d!="object"&&typeof d!="function"||d===null)throw new TypeError("Object.keys called on a non-object");var c=[],a;for(a in d)o(d,a)&&c.push(a);if(q)for(a=0;a<s;a++){var b=r[a];o(d,b)&&c.push(b)}return c}}if(!Date.prototype.toISOString||-1===(new Date(-621987552E5)).toISOString().indexOf("-000001"))Date.prototype.toISOString=function(){var d,c,a,b;if(!isFinite(this))throw new RangeError("Date.prototype.toISOString called on non-finite value.");
d=[this.getUTCMonth()+1,this.getUTCDate(),this.getUTCHours(),this.getUTCMinutes(),this.getUTCSeconds()];b=this.getUTCFullYear();b=(b<0?"-":b>9999?"+":"")+("00000"+Math.abs(b)).slice(0<=b&&b<=9999?-4:-6);for(c=d.length;c--;){a=d[c];a<10&&(d[c]="0"+a)}return b+"-"+d.slice(0,2).join("-")+"T"+d.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};Date.now||(Date.now=function(){return(new Date).getTime()});Date.prototype.toJSON||(Date.prototype.toJSON=function(){if(typeof this.toISOString!=
"function")throw new TypeError("toISOString property is not callable");return this.toISOString()});if(!Date.parse||864E13!==Date.parse("+275760-09-13T00:00:00.000Z")){var g=Date,f=function c(a,b,e,f,h,j,l){var k=arguments.length;if(this instanceof g){k=k==1&&String(a)===a?new g(c.parse(a)):k>=7?new g(a,b,e,f,h,j,l):k>=6?new g(a,b,e,f,h,j):k>=5?new g(a,b,e,f,h):k>=4?new g(a,b,e,f):k>=3?new g(a,b,e):k>=2?new g(a,b):k>=1?new g(a):new g;k.constructor=c;return k}return g.apply(this,arguments)},u=RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(?:Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$"),
h;for(h in g)f[h]=g[h];f.now=g.now;f.UTC=g.UTC;f.prototype=g.prototype;f.prototype.constructor=f;f.parse=function(c){var a=u.exec(c);if(a){a.shift();for(var b=1;b<7;b++){a[b]=+(a[b]||(b<3?1:0));b==1&&a[b]--}var e=+a.pop(),f=+a.pop(),h=a.pop(),b=0;if(h){if(f>23||e>59)return NaN;b=(f*60+e)*6E4*(h=="+"?-1:1)}e=+a[0];if(0<=e&&e<=99){a[0]=e+400;return g.UTC.apply(this,a)+b-126227808E5}return g.UTC.apply(this,a)+b}return g.parse.apply(this,arguments)};Date=f}h="\t\n\x0B\f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff";
if(!String.prototype.trim||h.trim()){h="["+h+"]";var v=RegExp("^"+h+h+"*"),w=RegExp(h+h+"*$");String.prototype.trim=function(){if(this===void 0||this===null)throw new TypeError("can't convert "+this+" to object");return String(this).replace(v,"").replace(w,"")}}var p=function(c){c=+c;c!==c?c=0:c!==0&&(c!==1/0&&c!==-(1/0))&&(c=(c>0||-1)*Math.floor(Math.abs(c)));return c},x="a"!="a"[0],j=function(c){if(c==null)throw new TypeError("can't convert "+c+" to object");return x&&typeof c=="string"&&c?c.split(""):
Object(c)}}); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/es5-shim/es5-shim.min.js | es5-shim.min.js |
// Module systems magic dance
(function (definition) {
// RequireJS
if (typeof define == "function") {
define(definition);
// YUI3
} else if (typeof YUI == "function") {
YUI.add("es5-sham", definition);
// CommonJS and <script>
} else {
definition();
}
})(function () {
// ES5 15.2.3.2
// http://es5.github.com/#x15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || (
object.constructor
? object.constructor.prototype
: prototypeOfObject
);
};
}
// ES5 15.2.3.3
// http://es5.github.com/#x15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT + object);
}
// If object does not owns property return undefined immediately.
if (!owns(object, property)) {
return;
}
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
var descriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) {
descriptor.get = getter;
}
if (setter) {
descriptor.set = setter;
}
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
// http://es5.github.com/#x15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
// http://es5.github.com/#x15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype != "object") {
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
}
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (properties !== void 0) {
Object.defineProperties(object, properties);
}
return object;
};
}
// ES5 15.2.3.6
// http://es5.github.com/#x15.2.3.6
// Patch for WebKit and IE8 standard mode
// Designed by hax <hax.github.com>
// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// http://msdn.microsoft.com/en-us/library/dd282900.aspx
// http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// https://bugs.webkit.org/show_bug.cgi?id=36423
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
// returns falsy
}
}
// check whether defineProperty works if it's given. Otherwise,
// shim partially.
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
}
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) {
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
}
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get")) {
defineGetter(object, property, descriptor.get);
}
if (owns(descriptor, "set")) {
defineSetter(object, property, descriptor.set);
}
}
return object;
};
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property) && property != "__proto__") {
Object.defineProperty(object, property, properties[property]);
}
}
return object;
};
}
// ES5 15.2.3.8
// http://es5.github.com/#x15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
// http://es5.github.com/#x15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
// http://es5.github.com/#x15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
// http://es5.github.com/#x15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
// http://es5.github.com/#x15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
// http://es5.github.com/#x15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
// 1. If Type(O) is not Object throw a TypeError exception.
if (Object(object) !== object) {
throw new TypeError(); // TODO message
}
// 2. Return the Boolean value of the [[Extensible]] internal property of O.
var name = '';
while (owns(object, name)) {
name += '?';
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
}
}); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/es5-shim/es5-sham.js | es5-sham.js |
- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License
- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal
Project)
- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA
- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License
- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License
- kossnocorp Sasha Koss XXX TODO License or CLA
- bryanforbes Bryan Forbes XXX TODO License or CLA
- killdream Quildreen Motta Copyright (C) 2011 MIT Licence
- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD
License
- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License
- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain)
- iwyg XXX TODO License or CLA
- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License
- xavierm02 Montillet Xavier Copyright (C) 2011 MIT License
- Raynos Jake Verbaten Copyright (C) 2011 MIT Licence
- samsonjs Sami Samhuri Copyright (C) 2010 MIT License
- rwldrn Rick Waldron Copyright (C) 2011 MIT License
- lexer Alexey Zakharov XXX TODO License or CLA
- 280 North Inc. (Now Motorola LLC, a subsidiary of Google Inc.)
Copyright (C) 2009 MIT License
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/es5-shim/CONTRIBUTORS.md | CONTRIBUTORS.md |
(function(d){"function"==typeof define?define(d):"function"==typeof YUI?YUI.add("es5-sham",d):d()})(function(){function d(a){try{return Object.defineProperty(a,"sentinel",{}),"sentinel"in a}catch(c){}}Object.getPrototypeOf||(Object.getPrototypeOf=function(a){return a.__proto__||(a.constructor?a.constructor.prototype:prototypeOfObject)});Object.getOwnPropertyDescriptor||(Object.getOwnPropertyDescriptor=function(a,c){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object: "+
a);if(owns(a,c)){var b={enumerable:true,configurable:true};if(supportsAccessors){var d=a.__proto__;a.__proto__=prototypeOfObject;var f=lookupGetter(a,c),e=lookupSetter(a,c);a.__proto__=d;if(f||e){if(f)b.get=f;if(e)b.set=e;return b}}b.value=a[c];return b}});Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(a){return Object.keys(a)});Object.create||(Object.create=function(a,c){var b;if(a===null)b={__proto__:null};else{if(typeof a!="object")throw new TypeError("typeof prototype["+typeof a+
"] != 'object'");b=function(){};b.prototype=a;b=new b;b.__proto__=a}c!==void 0&&Object.defineProperties(b,c);return b});if(Object.defineProperty){var g=d({}),h="undefined"==typeof document||d(document.createElement("div"));if(!g||!h)var e=Object.defineProperty}if(!Object.defineProperty||e)Object.defineProperty=function(a,c,b){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.defineProperty called on non-object: "+a);if(typeof b!="object"&&typeof b!="function"||b===
null)throw new TypeError("Property description must be an object: "+b);if(e)try{return e.call(Object,a,c,b)}catch(d){}if(owns(b,"value"))if(supportsAccessors&&(lookupGetter(a,c)||lookupSetter(a,c))){var f=a.__proto__;a.__proto__=prototypeOfObject;delete a[c];a[c]=b.value;a.__proto__=f}else a[c]=b.value;else{if(!supportsAccessors)throw new TypeError("getters & setters can not be defined on this javascript engine");owns(b,"get")&&defineGetter(a,c,b.get);owns(b,"set")&&defineSetter(a,c,b.set)}return a};
Object.defineProperties||(Object.defineProperties=function(a,c){for(var b in c)owns(c,b)&&b!="__proto__"&&Object.defineProperty(a,b,c[b]);return a});Object.seal||(Object.seal=function(a){return a});Object.freeze||(Object.freeze=function(a){return a});try{Object.freeze(function(){})}catch(j){var i=Object.freeze;Object.freeze=function(a){return typeof a=="function"?a:i(a)}}Object.preventExtensions||(Object.preventExtensions=function(a){return a});Object.isSealed||(Object.isSealed=function(){return false});
Object.isFrozen||(Object.isFrozen=function(){return false});Object.isExtensible||(Object.isExtensible=function(a){if(Object(a)!==a)throw new TypeError;for(var c="";owns(a,c);)c=c+"?";a[c]=true;var b=owns(a,c);delete a[c];return b})}); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/es5-shim/es5-sham.min.js | es5-sham.min.js |
// Module systems magic dance
(function (definition) {
// RequireJS
if (typeof define == "function") {
define(definition);
// YUI3
} else if (typeof YUI == "function") {
YUI.add("es5", definition);
// CommonJS and <script>
} else {
definition();
}
})(function () {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
* Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var F = function(){};
F.prototype = target.prototype;
var self = new F;
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return self;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
// XXX bound.length is never writable, so don't even try
//
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
// Having a toString local variable name breaks in Opera so use _toString.
var _toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return _toString(obj) == "[object Array]";
};
}
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var self = toObject(this),
thisp = arguments[1],
i = -1,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object context
fun.call(thisp, self[i], i, self);
}
}
};
}
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var self = toObject(this),
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
result = [],
value,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, self)) {
result.push(value);
}
}
}
return result;
};
}
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, self)) {
return false;
}
}
return true;
};
}
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, self)) {
return true;
}
}
return false;
};
}
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1) {
throw new TypeError('reduce of empty array with no initial value');
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError('reduce of empty array with no initial value');
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, self);
}
}
return result;
};
}
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value, empty array
if (!length && arguments.length == 1) {
throw new TypeError('reduceRight of empty array with no initial value');
}
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0) {
throw new TypeError('reduceRight of empty array with no initial value');
}
} while (true);
}
do {
if (i in this) {
result = fun.call(void 0, result, self[i], i, self);
}
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = toInteger(arguments[1]);
}
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = Math.min(i, toInteger(arguments[1]));
}
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i]) {
return i;
}
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
Object.keys = function keys(object) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) {
Date.prototype.toISOString = function toISOString() {
var result, length, value, year;
if (!isFinite(this)) {
throw new RangeError("Date.prototype.toISOString called on non-finite value.");
}
// the date time string format is specified in 15.9.1.15.
result = [this.getUTCMonth() + 1, this.getUTCDate(),
this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = this.getUTCFullYear();
year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two digits.
if (value < 10) {
result[length] = "0" + value;
}
}
// pad milliseconds to have three digits.
return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." +
("000" + this.getUTCMilliseconds()).slice(-3) + "Z";
}
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ToPrimitive(O, hint Number).
// 3. If tv is a Number and is not finite, return null.
// XXX
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof this.toISOString != "function") {
throw new TypeError('toISOString property is not callable');
}
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return this.toISOString();
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (!Date.parse || Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var Date = function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length == 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp("^" +
"(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year
"(?:-(\\d{2})" + // optional month capture
"(?:-(\\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\\d{2})" + // hours capture
":(\\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\\d{2})" + // seconds capture
"(?:\\.(\\d{3}))?" + // milliseconds capture
")?" +
"(?:" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\\d{2})" + // hours offset capture
":(\\d{2})" + // minutes offset capture
")" +
")?)?)?)?" +
"$");
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate) {
Date[key] = NativeDate[key];
}
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
match.shift(); // kill match[0], the full match
// parse months, days, hours, minutes, seconds, and milliseconds
for (var i = 1; i < 7; i++) {
// provide default values if necessary
match[i] = +(match[i] || (i < 3 ? 1 : 0));
// match[1] is the month. Months are 0-11 in JavaScript
// `Date` objects, but 1-12 in ISO notation, so we
// decrement.
if (i == 1) {
match[i]--;
}
}
// parse the UTC offset component
var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop();
// compute the explicit time zone offset if specified
var offset = 0;
if (sign) {
// detect invalid offsets and return early
if (hourOffset > 23 || minuteOffset > 59) {
return NaN;
}
// express the provided time zone offset in minutes. The offset is
// negative for time zones west of UTC; positive otherwise.
offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1);
}
// Date.UTC for years between 0 and 99 converts year to 1900 + year
// The Gregorian calendar has a 400-year cycle, so
// to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...),
// where 12622780800000 - number of milliseconds in Gregorian calendar 400 years
var year = +match[0];
if (0 <= year && year <= 99) {
match[0] = year + 400;
return NativeDate.UTC.apply(this, match) + offset - 12622780800000;
}
// compute a new UTC date value, accounting for the optional offset
return NativeDate.UTC.apply(this, match) + offset;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
//
// String
// ======
//
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === undefined || this === null) {
throw new TypeError("can't convert "+this+" to object");
}
return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
};
}
//
// Util
// ======
//
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
var toInteger = function (n) {
n = +n;
if (n !== n) { // isNaN
n = 0;
} else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
};
var prepareString = "a"[0] != "a";
// ES5 9.9
// http://es5.github.com/#x9.9
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert "+o+" to object");
}
// If the implementation doesn't support by-index access of
// string characters (ex. IE < 9), split the string
if (prepareString && typeof o == "string" && o) {
return o.split("");
}
return Object(o);
};
}); | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/es5-shim/es5-shim.js | es5-shim.js |
`es5-shim.js` and `es5-shim.min.js` monkey-patch a JavaScript context to
contain all EcmaScript 5 methods that can be faithfully emulated with a
legacy JavaScript engine.
`es5-sham.js` and `es5-sham.min.js` monkey-patch other ES5 methods as
closely as possible. For these methods, as closely as possible to ES5
is not very close. Many of these shams are intended only to allow code
to be written to ES5 without causing run-time errors in older engines.
In many cases, this means that these shams cause many ES5 methods to
silently fail. Decide carefully whether this is what you want.
## Tests
The tests are written with the Jasmine BDD test framework.
To run the tests, navigate to <root-folder>/tests/.
In order to run against the shim-code, the tests attempt to kill the current
implementation of the missing methods. This happens in <root-folder>/tests/helpers/h-kill.js.
So in order to run the tests against the build-in methods, invalidate that file somehow
(comment-out, delete the file, delete the script-tag, etc.).
## Shims
### Complete tests ###
* Array.prototype.every
* Array.prototype.filter
* Array.prototype.forEach
* Array.prototype.indexOf
* Array.prototype.lastIndexOf
* Array.prototype.map
* Array.prototype.some
* Array.prototype.reduce
* Array.prototype.reduceRight
* Array.isArray
* Date.now
* Date.prototype.toJSON
* Function.prototype.bind
* /!\ Caveat: the bound function's length is always 0.
* /!\ Caveat: the bound function has a prototype property.
* /!\ Caveat: bound functions do not try too hard to keep you
from manipulating their ``arguments`` and ``caller`` properties.
* /!\ Caveat: bound functions don't have checks in ``call`` and
``apply`` to avoid executing as a constructor.
* Object.keys
* String.prototype.trim
### Untested ###
* Date.parse (for ISO parsing)
* Date.prototype.toISOString
## Shams
* /?\ Object.create
For the case of simply "begetting" an object that
inherits prototypically from another, this should work
fine across legacy engines.
/!\ Object.create(null) will work only in browsers that
support prototype assignment. This creates an object
that does not have any properties inherited from
Object.prototype. It will silently fail otherwise.
/!\ The second argument is passed to
Object.defineProperties which will probably fail
silently.
* /?\ Object.getPrototypeOf
This will return "undefined" in some cases. It uses
__proto__ if it's available. Failing that, it uses
constructor.prototype, which depends on the constructor
property of the object's prototype having not been
replaced. If your object was created like this, it
won't work:
function Foo() {
}
Foo.prototype = {};
Because the prototype reassignment destroys the
constructor property.
This will work for all objects that were created using
`Object.create` implemented with this library.
* /!\ Object.getOwnPropertyNames
This method uses Object.keys, so it will not be accurate
on legacy engines.
* Object.isSealed
Returns "false" in all legacy engines for all objects,
which is conveniently guaranteed to be accurate.
* Object.isFrozen
Returns "false" in all legacy engines for all objects,
which is conveniently guaranteed to be accurate.
* Object.isExtensible
Works like a charm, by trying very hard to extend the
object then redacting the extension.
### Fail silently
* /!\ Object.getOwnPropertyDescriptor
The behavior of this shim does not conform to ES5. It
should probably not be used at this time, until its
behavior has been reviewed and been confirmed to be
useful in legacy engines.
* /!\ Object.defineProperty
This method will silently fail to set "writable",
"enumerable", and "configurable" properties.
Providing a getter or setter with "get" or "set" on a
descriptor will silently fail on engines that lack
"__defineGetter__" and "__defineSetter__", which include
all versions of IE up to version 8 so far.
IE 8 provides a version of this method but it only works
on DOM objects. Thus, the shim will not get installed
and attempts to set "value" properties will fail
silently on non-DOM objects.
https://github.com/kriskowal/es5-shim/issues#issue/5
* /!\ Object.defineProperties
This uses the Object.defineProperty shim
* Object.seal
Silently fails on all legacy engines. This should be
fine unless you are depending on the safety and security
provisions of this method, which you cannot possibly
obtain in legacy engines.
* Object.freeze
Silently fails on all legacy engines. This should be
fine unless you are depending on the safety and security
provisions of this method, which you cannot possibly
obtain in legacy engines.
* Object.preventExtensions
Silently fails on all legacy engines. This should be
fine unless you are depending on the safety and security
provisions of this method, which you cannot possibly
obtain in legacy engines.
| zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/ui/app/static/libs/es5-shim/README.md | README.md |
import ConfigParser
import logging
import os
import signal
import sys
import threading
import varnishapi
from _mysql_exceptions import OperationalError
from log.db import LogDatabase
from log.log_snapshot import Snapshot
from log.parser import (
annotations,
clear_annotations,
clear_spans,
parse_log_row,
spans,
)
log = logging.getLogger()
snapshot = Snapshot()
config = ConfigParser.ConfigParser()
__DB_PARAMS__ = dict()
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR}
varnish_log_args = ['-g', 'request']
callback_sleep_time = 0.5
cache_name = None
storage = None
vap = None
task = None
def init_log():
log_file = config.get('Log', 'log_file')
log_level = config.get('Log', 'log_level')
log_format = '%(asctime)s %(levelname)s: %(message)s ' \
'[in %(pathname)s:%(lineno)d]'
try:
logging.basicConfig(level=LEVELS.get(log_level.lower()),
format=log_format,
filename=log_file,
filemode='w')
except IOError as io:
print io.message
sys.exit(1)
except Exception as ex:
print ex.args[0]
sys.exit(1)
def init_config(overridden_config=None):
# The directory of the script.
default_config = os.path.join(
os.path.dirname(sys.argv[0]), "default.cfg")
etc_config = os.path.join("/etc/zipnish/zipnish.cfg")
# ~/.
extra_cfg_files = [default_config, etc_config]
if overridden_config:
extra_cfg_files.append(os.path.join(os.getcwd(), overridden_config))
for f in extra_cfg_files:
if os.path.isfile(f):
with open(f) as fp:
config.readfp(fp)
break
config.read(extra_cfg_files)
try:
assert config.has_section('Database'), "Database section is missing."
assert config.has_option(
'Database', 'host'), "MySql host option is missing."
assert config.has_option(
'Database', 'db_name'), "MySql database name option is missing."
assert config.has_option(
'Database', 'user'), "MySql user option is missing."
assert config.has_option(
'Database', 'pass'), "MySql password option is missing."
assert config.has_section('Log'), "Log section missing."
assert config.has_option(
'Log', 'log_file'), "Log file path is missing."
assert config.has_option(
'Log', 'log_level'), "Log level option is missing."
except AssertionError as ae:
print ae.message
sys.exit(1)
__DB_PARAMS__['host'] = config.get('Database', 'host')
__DB_PARAMS__['db'] = config.get('Database', 'db_name')
__DB_PARAMS__['user'] = config.get('Database', 'user')
__DB_PARAMS__['passwd'] = config.get('Database', 'pass')
__DB_PARAMS__['keep_alive'] = config.get('Database', 'keep_alive')
if config.has_option('Sync', 'splay'):
global callback_sleep_time
callback_sleep_time = config.getfloat('Sync', 'splay')
if config.has_option('Cache', 'name'):
global cache_name
cache_name = config.get('Cache', 'name')
def vap_callback(vap, cbd, priv):
try:
vxid = cbd['vxid']
request_type = cbd['type']
tag = cbd['tag']
t_tag = vap.VSL_tags[tag]
data = cbd['data']
snapshot.fill_snapshot(vxid, request_type, t_tag, data)
except Exception as vap_callback_ex:
log.error(vap_callback_ex)
def error_callback(error):
log.error(error)
vap.Fini()
def fetch_varnish_log():
out = vap.Dispatch(vap_callback)
interval = 0
if not out:
interval = 0.5 # callback_sleep_time
task.interval = interval
class PeriodicEvent(object):
def __init__(self, interval, func):
self.interval = interval
self.func = func
self.terminate = threading.Event()
def _signals_install(self, func):
for sig in [signal.SIGINT, signal.SIGTERM]:
signal.signal(sig, func)
def _signal_handler(self, signum, frame):
self.terminate.set()
def run(self):
self._signals_install(self._signal_handler)
while not self.terminate.is_set():
self.func()
self.terminate.wait(self.interval)
self._signals_install(signal.SIG_DFL)
def snapshot_callback(log_input):
parse_log_row(log_input)
if len(annotations) >= 4:
storage.insert("spans", spans)
storage.insert("annotations", annotations)
clear_spans()
clear_annotations()
def main():
global storage
global vap
global task
init_config()
init_log()
try:
storage = LogDatabase(**__DB_PARAMS__)
if cache_name:
varnish_log_args.extend(['-n', cache_name])
snapshot.add_callback_func(snapshot_callback)
vap = varnishapi.VarnishLog(varnish_log_args)
task = PeriodicEvent(0.5, fetch_varnish_log)
log.debug("Log Reader is about to start.")
task.run()
except OperationalError as op:
print "Database error %s" % op.args[0]
log.error(op)
except Exception as ex:
print "Unknown exception %s" % ex.args[0]
log.error(ex)
if __name__ == '__main__':
main() | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/logreader/app.py | app.py |
from ctypes import *
import sys,getopt
###########################################
class VSC_level_desc(Structure):
_fields_ = [
("verbosity" ,c_uint), #unsigned verbosity;
("label", c_char_p), #const char *label; /* label */
("sdesc", c_char_p), #const char *sdesc; /* short description */
("ldesc", c_char_p), #const char *ldesc; /* long description */
]
class VSC_type_desc(Structure):
_fields_ = [
("label", c_char_p), #const char *label; /* label */
("sdesc", c_char_p), #const char *sdesc; /* short description */
("ldesc", c_char_p), #const char *ldesc; /* long description */
]
class VSM_fantom(Structure):
_fields_ = [
("chunk", c_void_p), #struct VSM_chunk *chunk;
("b", c_void_p), #void *b; /* first byte of payload */
("e", c_void_p), #void *e; /* first byte past payload */
#("priv", c_uint), #uintptr_t priv; /* VSM private */
("priv", c_void_p), #uintptr_t priv; /* VSM private */
("_class", c_char * 8), #char class[VSM_MARKER_LEN];
("type", c_char * 8), #char type[VSM_MARKER_LEN];
("ident", c_char * 128), #char ident[VSM_IDENT_LEN];
]
class VSC_section(Structure):
_fields_ = [
("type", c_char_p), #const char *type;
("ident", c_char_p), #const char *ident;
("desc", POINTER(VSC_type_desc)), #const struct VSC_type_desc *desc;
("fantom", POINTER(VSM_fantom)), #struct VSM_fantom *fantom;
]
class VSC_desc(Structure):
_fields_ = [
("name", c_char_p), #const char *name; /* field name */
("fmt", c_char_p), #const char *fmt; /* field format ("uint64_t") */
("flag", c_int), #int flag; /* 'c' = counter, 'g' = gauge */
("sdesc", c_char_p), #const char *sdesc; /* short description */
("ldesc", c_char_p), #const char *ldesc; /* long description */
("level", POINTER(VSC_level_desc)), #const struct VSC_level_desc *level;
]
class VSC_point(Structure):
_fields_ = [
("desc", POINTER(VSC_desc)), #const struct VSC_desc *desc; /* point description */
#("ptr", c_void_p), #const volatile void *ptr; /* field value */
("ptr", POINTER(c_ulonglong)), #const volatile void *ptr; /* field value */
("section", POINTER(VSC_section)), #const struct VSC_section *section;
]
#typedef int VSC_iter_f(void *priv, const struct VSC_point *const pt);
VSC_iter_f = CFUNCTYPE(
c_int,
c_void_p,
POINTER(VSC_point)
)
###########################################
class VSLC_ptr(Structure):
_fields_ = [
("ptr" , POINTER(c_uint32)), #const uint32_t *ptr; /* Record pointer */
("priv", c_uint), #unsigned priv;
]
class VSL_cursor(Structure):
_fields_ = [
("rec" , VSLC_ptr), #struct VSLC_ptr rec;
("priv_tbl", c_void_p), #const void *priv_tbl;
("priv_data", c_void_p), #void *priv_data;
]
class VSL_transaction(Structure):
_fields_ = [
("level" , c_uint), #unsigned level;
("vxid", c_int32), #int32_t vxid;
("vxid_parent", c_int32), #int32_t vxid_parent;
("type", c_int), #enum VSL_transaction_e type;
("reason", c_int), #enum VSL_reason_e reason;
("c", POINTER(VSL_cursor)), #struct VSL_cursor *c;
]
class VTAILQ_HEAD(Structure):
_fields_ = [
("vtqh_first" , c_void_p), #struct type *vtqh_first; /* first element */ \
("vtqh_last", POINTER(c_void_p)), #struct type **vtqh_last; /* addr of last next element */ \
]
class vbitmap(Structure):
_fields_ = [
("bits" , c_void_p), #VBITMAP_TYPE *bits;
("nbits", c_uint), #unsigned nbits;
]
class vsb(Structure):
_fields_ = [
("magic" , c_uint), #unsigned magic;
("s_buf", c_char_p), #char *s_buf; /* storage buffer */
("s_error", c_int), #int s_error; /* current error code */
#("s_size", c_ssize_t), #ssize_t s_size; /* size of storage buffer */
#("s_len", c_ssize_t), #ssize_t s_len; /* current length of string */
("s_size", c_long), #ssize_t s_size; /* size of storage buffer */
("s_len", c_long), #ssize_t s_len; /* current length of string */
("s_flags", c_int), #int s_flags; /* flags */
]
class VSL_data(Structure):
_fields_ = [
("magic", c_uint), #unsigned magic;
("diag", POINTER(vsb)), #struct vsb *diag;
("flags", c_uint), #unsigned flags;
("vbm_select", POINTER(vbitmap)), #struct vbitmap *vbm_select;
("vbm_supress", POINTER(vbitmap)), #struct vbitmap *vbm_supress;
("vslf_select", VTAILQ_HEAD), #vslf_list vslf_select;
("vslf_suppress", VTAILQ_HEAD), #vslf_list vslf_suppress;
("b_opt", c_int), #int b_opt;
("c_opt", c_int), #int c_opt;
("C_opt", c_int), #int C_opt;
("L_opt", c_int), #int L_opt;
("T_opt", c_double), #double T_opt;
("v_opt", c_int), #int v_opt;
]
#typedef int VSLQ_dispatch_f(struct VSL_data *vsl, struct VSL_transaction * const trans[], void *priv);
VSLQ_dispatch_f = CFUNCTYPE(
c_int,
POINTER(VSL_data),
POINTER(POINTER(VSL_transaction)),
c_void_p
)
class VarnishAPIDefine40:
def __init__(self):
self.VSL_COPT_TAIL = (1 << 0)
self.VSL_COPT_BATCH = (1 << 1)
self.VSL_COPT_TAILSTOP = (1 << 2)
self.SLT_F_BINARY = (1 << 1)
'''
//////////////////////////////
enum VSL_transaction_e {
VSL_t_unknown,
VSL_t_sess,
VSL_t_req,
VSL_t_bereq,
VSL_t_raw,
VSL_t__MAX,
};
'''
self.VSL_t_unknown = 0
self.VSL_t_sess = 1
self.VSL_t_req = 2
self.VSL_t_bereq = 3
self.VSL_t_raw = 4
self.VSL_t__MAX = 5
'''
//////////////////////////////
enum VSL_reason_e {
VSL_r_unknown,
VSL_r_http_1,
VSL_r_rxreq,
VSL_r_esi,
VSL_r_restart,
VSL_r_pass,
VSL_r_fetch,
VSL_r_bgfetch,
VSL_r_pipe,
VSL_r__MAX,
};
'''
self.VSL_r_unknown = 0
self.VSL_r_http_1 = 1
self.VSL_r_rxreq = 2
self.VSL_r_esi = 3
self.VSL_r_restart = 4
self.VSL_r_pass = 5
self.VSL_r_fetch = 6
self.VSL_r_bgfetch = 7
self.VSL_r_pipe = 8
self.VSL_r__MAX = 9
class LIBVARNISHAPI13:
def __init__(self,lib):
self.VSL_CursorFile = lib.VSL_CursorFile
self.VSL_CursorFile.restype = c_void_p
self.VSL_CursorVSM = lib.VSL_CursorVSM
self.VSL_CursorVSM.restype = c_void_p
self.VSL_Error = lib.VSL_Error
self.VSL_Error.restype = c_char_p
self.VSM_Error = lib.VSM_Error
self.VSM_Error.restype = c_char_p
self.VSM_Name = lib.VSM_Name
self.VSM_Name.restype = c_char_p
self.VSLQ_New = lib.VSLQ_New
self.VSLQ_New.restype = c_void_p
self.VSLQ_New.argtypes = [c_void_p, POINTER(c_void_p),c_int,c_char_p]
self.VSLQ_Delete = lib.VSLQ_Delete
self.VSLQ_Delete.argtypes = [POINTER(c_void_p)]
#self.VSLQ_Dispatch = lib.VSLQ_Dispatch
#self.VSLQ_Dispatch.restype = c_int
#self.VSLQ_Dispatch.argtypes = (c_void_p, CFUNCTYPE ,c_void_p)
class VSLUtil:
def tag2VarName(self, tag, data):
if not self.__tags.has_key(tag):
return ''
r = self.__tags[tag]
if r == '':
return ''
elif r[-1:] == '.':
return r + data.split(':',1)[0]
return (r)
__tags = {
'Debug' : '',
'Error' : '',
'CLI' : '',
'SessOpen' : '',
'SessClose' : '',
'BackendOpen' : '',
'BackendReuse' : '',
'BackendClose' : '',
'HttpGarbage' : '',
'Backend' : '',
'Length' : '',
'FetchError' : '',
'BogoHeader' : '',
'LostHeader' : '',
'TTL' : '',
'Fetch_Body' : '',
'VCL_acl' : '',
'VCL_call' : '',
'VCL_trace' : '',
'VCL_return' : '',
'ReqStart' : 'client.ip',
'Hit' : '',
'HitPass' : '',
'ExpBan' : '',
'ExpKill' : '',
'WorkThread' : '',
'ESI_xmlerror' : '',
'Hash' : '',
'Backend_health' : '',
'VCL_Log' : '',
'VCL_Error' : '',
'Gzip' : '',
'Link' : '',
'Begin' : '',
'End' : '',
'VSL' : '',
'Storage' : '',
'Timestamp' : '',
'ReqAcct' : '',
'ESI_BodyBytes' : '',
'PipeAcct' : '',
'BereqAcct' : '',
'ReqMethod' : 'req.method',
'ReqURL' : 'req.url',
'ReqProtocol' : 'req.proto',
'ReqStatus' : '',
'ReqReason' : '',
'ReqHeader' : 'req.http.',
'ReqUnset' : 'unset req.http.',
'ReqLost' : '',
'RespMethod' : '',
'RespURL' : '',
'RespProtocol' : 'resp.proto',
'RespStatus' : 'resp.status',
'RespReason' : 'resp.reason',
'RespHeader' : 'resp.http.',
'RespUnset' : 'unset resp.http.',
'RespLost' : '',
'BereqMethod' : 'bereq.method',
'BereqURL' : 'bereq.url',
'BereqProtocol' : 'bereq.proto',
'BereqStatus' : '',
'BereqReason' : '',
'BereqHeader' : 'bereq.http.',
'BereqUnset' : 'unset bereq.http.',
'BereqLost' : '',
'BerespMethod' : '',
'BerespURL' : '',
'BerespProtocol' : 'beresp.proto',
'BerespStatus' : 'beresp.status',
'BerespReason' : 'beresp.reason',
'BerespHeader' : 'beresp.http.',
'BerespUnset' : 'unset beresp.http.',
'BerespLost' : '',
'ObjMethod' : '',
'ObjURL' : '',
'ObjProtocol' : 'obj.proto',
'ObjStatus' : 'obj.status',
'ObjReason' : 'obj.reason',
'ObjHeader' : 'obj.http.',
'ObjUnset' : 'unset obj.http.',
'ObjLost' : '',
}
class VarnishAPI:
def __init__(self, opt = '', sopath = 'libvarnishapi.so.1'):
self.lib = cdll[sopath]
self.lva = LIBVARNISHAPI13(self.lib)
self.defi = VarnishAPIDefine40()
self.__cb = None
self.vsm = self.lib.VSM_New()
self.d_opt = 0
VSLTAGS = c_char_p * 256
self.VSL_tags = VSLTAGS.in_dll(self.lib, "VSL_tags")
VSLTAGFLAGS = c_uint * 256
self.VSL_tagflags = VSLTAGFLAGS.in_dll(self.lib, "VSL_tagflags")
VSLQGROUPING = c_char_p * 4
self.VSLQ_grouping = VSLQGROUPING.in_dll(self.lib, "VSLQ_grouping")
self.error = ''
def ArgDefault(self, op, arg):
if op == "n":
#�C���X�^���X�w��
i = self.lib.VSM_n_Arg(self.vsm, arg)
if i <= 0:
error = "%s" % self.lib.VSM_Error(self.vsm)
return(i)
elif op == "N":
#VSM�t�@�C���w��
i = self.lib.VSM_N_Arg(self.vsm, arg)
if i <= 0:
error = "%s" % self.lib.VSM_Error(self.vsm)
return(i)
self.d_opt = 1
return(None)
class VarnishStat(VarnishAPI):
def __init__(self, opt='', sopath = 'libvarnishapi.so.1'):
VarnishAPI.__init__(self,sopath)
self.lib.VSM_Open(self.vsm)
if len(opt)>0:
self.__setArg(opt)
def __setArg(self,opt):
opts, args = getopt.getopt(opt,"bcCdx:X:r:q:N:n:I:i:g:")
error = 0
for o in opts:
op = o[0].lstrip('-')
arg = o[1]
self.__Arg(op,arg)
#Check
if self.__r_arg and self.vsm:
error = "Can't have both -n and -r options"
if error:
self.error = error
return(0)
return(1)
def __Arg(self, op, arg):
#default
VarnishAPI.__Arg(op, arg)
if i < 0:
return(i)
def __getstat(self, priv, pt):
if not bool(pt):
return(0)
val = pt[0].ptr[0]
sec = pt[0].section
key = ''
type = sec[0].fantom[0].type
ident = sec[0].fantom[0].ident
if type != '':
key += type + '.'
if ident != '':
key += ident + '.'
key += pt[0].desc[0].name
self.__buf[key]={'val':val,'desc':pt[0].desc[0].sdesc}
return(0)
def getStats(self):
self.__buf = {}
self.lib.VSC_Iter(self.vsm, None, VSC_iter_f(self.__getstat), None);
return self.__buf
class VarnishLog(VarnishAPI):
def __init__(self, opt = '', sopath = 'libvarnishapi.so.1'):
VarnishAPI.__init__(self,sopath)
self.vut = VSLUtil()
self.vsl = self.lib.VSL_New()
self.vslq = None
self.__g_arg = 0
self.__q_arg = None
self.__r_arg = 0
self.name = ''
if len(opt)>0:
self.__setArg(opt)
self.__Setup()
def __setArg(self,opt):
opts, args = getopt.getopt(opt,"bcCdx:X:r:q:N:n:I:i:g:")
error = 0
for o in opts:
op = o[0].lstrip('-')
arg = o[1]
self.__Arg(op,arg)
#Check
if self.__r_arg and self.vsm:
error = "Can't have both -n and -r options"
if error:
self.error = error
return(0)
return(1)
def __Arg(self, op, arg):
i = VarnishAPI.ArgDefault(self,op, arg)
if i != None:
return(i)
if op == "d":
#�擪����
self.d_opt = 1
elif op == "g":
#�O���[�s���O�w��
self.__g_arg = self.__VSLQ_Name2Grouping(arg)
if self.__g_arg == -2:
error = "Ambiguous grouping type: %s" % (arg)
return(self.__g_arg)
elif self.__g_arg < 0:
error = "Unknown grouping type: %s" % (arg)
return(self.__g_arg)
#elif op == "P":
# #PID�w���͑Ή����Ȃ�
elif op == "q":
#VSL-query
self.__q_arg = arg
elif op == "r":
#�o�C�i���t�@�C��
self.__r_arg = arg
else:
#default
i = self.__VSL_Arg(op, arg);
if i < 0:
error = "%s" % self.lib.VSL_Error(self.vsl)
return(i)
def __Setup(self):
if self.__r_arg:
c = self.lva.VSL_CursorFile(self.vsl, self.__r_arg, 0);
else:
if self.lib.VSM_Open(self.vsm):
self.error = "Can't open VSM file (%s)" % self.lib.VSM_Error(self.vsm)
return(0)
self.name = self.lva.VSM_Name(self.vsm)
c = self.lva.VSL_CursorVSM(self.vsl, self.vsm,
(self.defi.VSL_COPT_TAILSTOP if self.d_opt else self.defi.VSL_COPT_TAIL) | self.defi.VSL_COPT_BATCH
)
if not c:
self.error = "Can't open log (%s)" % self.lva.VSL_Error(self.vsl)
print self.error
return(0)
#query
z = cast(c,c_void_p)
self.vslq = self.lva.VSLQ_New(self.vsl,z, self.__g_arg, self.__q_arg);
if not self.vslq:
self.error = "Query expression error:\n%s" % self.lib.VSL_Error(self.vsl)
return(0)
return(1)
def __cbMain(self,cb,priv=None):
self.__cb = cb
self.__priv = priv
if not self.vslq:
if self.lib.VSM_Open(self.vsm):
self.lib.VSM_ResetError(self.vsm)
return(1)
c = self.lva.VSL_CursorVSM(self.vsl, self.vsm,self.defi.VSL_COPT_TAIL | self.defi.VSL_COPT_BATCH);
if not c:
self.lib.VSM_ResetError(self.vsm)
self.lib.VSM_Close(self.vsm)
return(1)
self.vslq = self.lva.VSLQ_New(self.vsl, POINTER(c), self.__g_arg, self.__q_arg);
self.error = 'Log reacquired'
i = self.lib.VSLQ_Dispatch(self.vslq, VSLQ_dispatch_f(self.__callBack), None);
return(i)
def Dispatch(self,cb,priv=None):
i = self.__cbMain(cb,priv)
if i > -2:
return i
if not self.vsm:
return i
self.lib.VSLQ_Flush(self.vslq, VSLQ_dispatch_f(self.__callBack), None);
self.lva.VSLQ_Delete(byref(cast(self.vslq,c_void_p)))
self.vslq = None
if i == -2:
self.error = "Log abandoned"
self.lib.VSM_Close(self.vsm)
if i < -2:
self.error = "Log overrun"
return i
def Fini(self):
if self.vslq:
self.lva.VSLQ_Delete(byref(cast(self.vslq,c_void_p)))
self.vslq = 0
if self.vsl:
self.lib.VSL_Delete(self.vsl)
self.vsl = 0
if self.vsm:
self.lib.VSM_Delete(self.vsm)
self.vsm = 0
def __VSL_Arg(self, opt, arg = '\0'):
return self.lib.VSL_Arg(self.vsl, ord(opt), arg)
def __VSLQ_Name2Grouping(self, arg):
return self.lib.VSLQ_Name2Grouping(arg, -1)
def __callBack(self,vsl, pt, fo):
idx = -1
while 1:
idx += 1
t = pt[idx]
if not bool(t):
break
tra=t[0]
c =tra.c[0]
cbd = {
'level' : tra.level,
'vxid' : tra.vxid,
'vxid_parent' : tra.vxid_parent,
'reason' : tra.reason,
}
if vsl[0].c_opt or vsl[0].b_opt:
if tra.type == self.defi.VSL_t_req and not vsl[0].c_opt:
continue
elif tra.type == self.defi.VSL_t_bereq and not vsl[0].b_opt:
continue
elif tra.type != self.defi.VSL_t_raw:
continue
while 1:
i = self.lib.VSL_Next(tra.c);
if i < 0:
return (i)
if i == 0:
break
if not self.lib.VSL_Match(self.vsl, tra.c):
continue
#decode vxid type ...
length =c.rec.ptr[0] & 0xffff
cbd['length']=length
cbd['data'] =string_at(c.rec.ptr,length + 8)[8:]
tag =c.rec.ptr[0] >> 24
cbd['tag'] =tag
if c.rec.ptr[1] &(1<< 30):
cbd['type'] = 'c'
elif c.rec.ptr[1] &(1<< 31):
cbd['type'] = 'b'
else:
cbd['type'] = '-'
cbd['isbin'] = self.VSL_tagflags[tag] & self.defi.SLT_F_BINARY
if self.__cb:
self.__cb(self,cbd,self.__priv)
return(0) | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/logreader/varnishapi.py | varnishapi.py |
from simplemysql import SimpleMysql
class LogDatabase:
def __init__(self, **keyVals):
# saving database parameters
self.dbParams = keyVals
# table information
self.tablePrefix = 'zipnish_'
self.tables = ['spans', 'annotations']
# connect to database
self.db = SimpleMysql(
host=keyVals['host'],
db=keyVals['db'],
user=keyVals['user'],
passwd=keyVals['passwd'],
keep_alive=keyVals['keep_alive']
)
self.__create_tables()
def __create_tables(self):
spans_table_query = "CREATE TABLE IF NOT EXISTS zipnish_spans " \
"(span_id BIGINT NOT NULL, " \
"parent_id BIGINT, " \
"trace_id BIGINT NOT NULL, " \
"span_name VARCHAR(255) NOT NULL, " \
"debug SMALLINT NOT NULL, " \
"duration BIGINT, " \
"created_ts BIGINT);"
span_id_index0 = "ALTER TABLE zipnish_spans ADD INDEX(span_id);"
trace_id_index0 = "ALTER TABLE zipnish_spans ADD INDEX(trace_id);"
span_name_index0 = "ALTER TABLE zipnish_spans ADD INDEX(span_name(64));"
created_ts_index = "ALTER TABLE zipnish_spans ADD INDEX(created_ts);"
annotations_table_query = "CREATE TABLE IF NOT EXISTS zipnish_annotations " \
"(span_id BIGINT NOT NULL, " \
"trace_id BIGINT NOT NULL, " \
"span_name VARCHAR(255) NOT NULL, " \
"service_name VARCHAR(255) NOT NULL, " \
"value TEXT, " \
"ipv4 INT, " \
"port INT, " \
"a_timestamp BIGINT NOT NULL, " \
"duration BIGINT);"
span_id_key = "ALTER TABLE zipnish_annotations ADD FOREIGN KEY(span_id) " \
"REFERENCES zipnish_spans(span_id) ON DELETE CASCADE;"
trace_id_index = "ALTER TABLE zipnish_annotations ADD INDEX(trace_id);"
span_name_index = "ALTER TABLE zipnish_annotations ADD INDEX(span_name(64));"
value_index = "ALTER TABLE zipnish_annotations ADD INDEX(value(64));"
a_timestamp_index = "ALTER TABLE zipnish_annotations ADD INDEX(a_timestamp);"
queryes = [spans_table_query, span_id_index0, trace_id_index0,
span_name_index0, created_ts_index,
annotations_table_query, span_id_key, trace_id_index,
span_name_index, value_index, a_timestamp_index]
stmt = "SHOW TABLES LIKE 'zipnish_%'"
cursor = self.db.query(stmt)
table_count = len(cursor.fetchall())
if table_count == 0:
for query in queryes:
self.db.query(query)
self.db.commit()
def get_params(self):
return self.dbParams
def insert(self, table_name, rows):
table = self.tablePrefix + table_name
for row in rows:
self.db.insert(table, row)
self.db.commit() | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/logreader/log/db.py | db.py |
import socket
import struct
spans = []
annotations = []
CLIENT_RECEIVE = 'cr'
SERVER_RECEIVE = 'sr'
SERVER_SEND = 'ss'
def clear_spans():
global spans
del spans[:]
def clear_annotations():
global annotations
del annotations[:]
def __ts_convert(row_dict, ts_key, convert_func):
if ts_key in row_dict:
ts_value = row_dict[ts_key]
ts = ts_value if ts_value else ''
if len(ts):
row_dict[ts_key] = convert_func(ts)
def __convert_timestamp(timestamp):
return int(timestamp.replace('.', ''))
def __convert_duration(duration):
_duration = duration.replace('.', '').lstrip('0')
return int(_duration) if len(_duration) else 0
def __convert_ip_to_int(ip):
_ip = socket.gethostbyname(ip)
return struct.unpack("!I", socket.inet_aton(_ip))[0]
def replace_client_span_id(client_span_id, backend_span_id):
for span_idx in range(len(spans)):
span_row = spans[span_idx]
if span_row['span_id'] == client_span_id:
if span_row['trace_id'] == span_row['span_id']:
span_row['trace_id'] = backend_span_id
span_row['span_id'] = backend_span_id
spans[span_idx] = span_row
def __parse_client_log(row_dict):
__ts_convert(row_dict, 'timestamp-abs-Start', __convert_timestamp)
__ts_convert(row_dict, 'timestamp-duration-Start', __convert_duration)
__ts_convert(row_dict, 'timestamp-duration-Resp', __convert_duration)
__ts_convert(row_dict, 'timestamp-abs-Resp', __convert_timestamp)
if 'trace_id' not in row_dict:
row_dict['trace_id'] = row_dict['span_id']
span = {'span_id': row_dict['span_id'],
'parent_id': row_dict['parent_id'],
'trace_id': row_dict['trace_id'],
'span_name': row_dict['span_name'],
'debug': row_dict['debug'],
'duration': row_dict['timestamp-duration-Start'],
'created_ts': row_dict['timestamp-abs-Start']}
spans.append(span)
if row_dict['parent_id'] is not None:
child_span = dict()
child_span.update(span)
child_span['duration'] = row_dict['timestamp-duration-Resp']
child_span['created_ts'] = row_dict['timestamp-abs-Resp']
spans.append(child_span)
def __parse_backend_log(row_dict):
__ts_convert(row_dict, 'timestamp-duration-Start', __convert_duration)
__ts_convert(row_dict, 'timestamp-abs-Start', __convert_timestamp)
__ts_convert(row_dict, 'timestamp-duration-Bereq', __convert_duration)
__ts_convert(row_dict, 'timestamp-abs-Bereq', __convert_timestamp)
__ts_convert(row_dict, 'timestamp-duration-Beresp', __convert_duration)
__ts_convert(row_dict, 'timestamp-abs-Beresp', __convert_timestamp)
__ts_convert(row_dict, 'timestamp-duration-BerespBody', __convert_duration)
__ts_convert(row_dict, 'timestamp-abs-BerespBody', __convert_timestamp)
if 'trace_id' not in row_dict:
row_dict['trace_id'] = row_dict['span_id']
if row_dict['ipv4']:
row_dict['ipv4'] = __convert_ip_to_int(row_dict['ipv4'])
begin_tag_data = row_dict['begin'].strip().split(" ")
client_span_id = begin_tag_data[1]
replace_client_span_id(client_span_id, row_dict['span_id'])
annotation = {
'span_id': row_dict['span_id'],
'trace_id': row_dict['trace_id'],
'span_name': row_dict['span_name'],
'service_name': row_dict['span_name'],
'value': 'cs',
'ipv4': row_dict['ipv4'],
'port': row_dict['port'],
'a_timestamp': row_dict['timestamp-abs-Start'],
'duration': row_dict['timestamp-duration-Start']
}
client_start_annotation = dict()
client_start_annotation.update(annotation)
client_start_annotation['a_timestamp'] = row_dict['timestamp-abs-Bereq']
client_start_annotation['duration'] = row_dict['timestamp-duration-Bereq']
client_start_annotation['value'] = SERVER_RECEIVE
server_rec_annotation = dict()
server_rec_annotation.update(annotation)
server_rec_annotation['a_timestamp'] = row_dict['timestamp-abs-Beresp']
server_rec_annotation['duration'] = row_dict['timestamp-duration-Beresp']
server_rec_annotation['value'] = SERVER_SEND
server_resp_annotation = dict()
server_resp_annotation.update(annotation)
server_resp_annotation['a_timestamp'] = row_dict[
'timestamp-abs-BerespBody']
server_resp_annotation['duration'] = row_dict[
'timestamp-duration-BerespBody']
server_resp_annotation['value'] = CLIENT_RECEIVE
annotations.append(annotation)
annotations.append(client_start_annotation)
annotations.append(server_rec_annotation)
annotations.append(server_resp_annotation)
def parse_log_row(row_dict):
if 'debug' not in row_dict:
row_dict['debug'] = 0
if 'parent_id' not in row_dict:
row_dict['parent_id'] = 0
req_type = row_dict['request_type']
if req_type == 'c':
__parse_client_log(row_dict)
elif req_type == 'b':
__parse_backend_log(row_dict) | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/logreader/log/parser.py | parser.py |
URL_TAGS = ['ReqURL', 'BereqURL']
HEADER_TAGS = ['ReqHeader', 'RespHeader', 'BereqHeader', 'BerespHeader']
class Snapshot(object):
def __init__(self):
self.log_snapshot = dict()
self.callbacks = []
def add_callback_func(self, func):
self.callbacks.append(func)
def fill_snapshot(self, vxid, request_type, tag, data):
if tag == 'Begin':
self.log_snapshot.clear()
self.log_snapshot['begin'] = data
elif tag == 'End':
self.log_snapshot['request_type'] = request_type
self.__on_snapshot_ready()
self.log_snapshot.clear()
if tag in URL_TAGS:
self.log_snapshot['span_name'] = data.rstrip('\x00')
elif tag == 'Link':
value = data.split(" ")[1]
self.log_snapshot['link'] = value
elif tag == 'Timestamp':
ts = data.rstrip('\x00').split(" ")
assert len(ts) == 4
ts_name_tag = ts[0].rstrip(":")
ts_abs_tag = "timestamp-%s-%s" % ("abs", ts_name_tag)
ts_duration_tag = "timestamp-%s-%s" % ("duration", ts_name_tag)
self.log_snapshot[ts_abs_tag] = ts[1]
self.log_snapshot[ts_duration_tag] = ts[3]
elif tag in HEADER_TAGS:
header_info = data.rstrip('\x00').split(": ")
header_name = header_info[0].lower()
header_value = header_info[1].rsplit()[0]
if header_name == 'x-varnish':
self.log_snapshot['span_id'] = header_value
elif header_name == 'x-varnish-trace':
self.log_snapshot['trace_id'] = header_value
elif header_name == 'x-varnish-parent':
self.log_snapshot['parent_id'] = header_value
elif header_name == 'x-varnish-debug':
self.log_snapshot['debug'] = header_value
elif header_name == 'host':
ipv4 = header_value
port = 0
if ":" in header_value:
value = header_value.split(":")
ipv4 = value[0]
port = value[1]
self.log_snapshot['ipv4'] = ipv4
self.log_snapshot['port'] = port
def __on_snapshot_ready(self):
for func in self.callbacks:
if func:
func(self.log_snapshot.copy()) | zipnish | /zipnish-0.1.5.tar.gz/zipnish-0.1.5/logreader/log/log_snapshot.py | log_snapshot.py |
v3.16.2
=======
Bugfixes
--------
- In ``Path.match``, Windows path separators are no longer honored. The fact that they were was incidental and never supported. (#92)
- Fixed name/suffix/suffixes/stem operations when no filename is present and the Path is not at the root of the zipfile. (#96)
- Reworked glob utilizing the namelist directly. (#101)
v3.16.1
=======
Bugfixes
--------
- Replaced the ``fnmatch.translate`` with a fresh glob-to-regex translator for more correct matching behavior. (#98)
v3.16.0
=======
Features
--------
- Require Python 3.8 or later.
v3.15.0
=======
* gh-102209: ``test_implied_dirs_performance`` now tests
measures the time complexity experimentally.
v3.14.0
=======
* Minor cleanup in tests, including #93.
v3.13.0
=======
* In tests, add a fallback when ``func_timeout`` isn't available.
v3.12.1
=======
* gh-101566: In ``CompleteDirs``, override ``ZipFile.getinfo``
to supply a ``ZipInfo`` for implied dirs.
v3.12.0
=======
* gh-101144: Honor ``encoding`` as positional parameter
to ``Path.open()`` and ``Path.read_text()``.
v3.11.0
=======
* #85: Added support for new methods on ``Path``:
- ``match``
- ``glob`` and ``rglob``
- ``relative_to``
- ``is_symlink``
v3.10.0
=======
* ``zipp`` is now a package.
v3.9.1
======
* Removed 'print' expression in test_pickle.
* bpo-43651: Apply ``io.text_encoding`` on Python 3.10 and later.
v3.9.0
======
* #81: ``Path`` objects are now pickleable if they've been
constructed from pickleable objects. Any restored objects
will re-construct the zip file with the original arguments.
v3.8.1
======
Refreshed packaging.
Enrolled with Tidelift.
v3.8.0
======
Removed compatibility code.
v3.7.0
======
Require Python 3.7 or later.
v3.6.0
======
#78: Only ``Path`` is exposed in the public API.
v3.5.1
======
#77: Remove news file intended only for CPython.
v3.5.0
======
#74 and bpo-44095: Added ``.suffix``, ``.suffixes``,
and ``.stem`` properties.
v3.4.2
======
Refresh package metadata.
v3.4.1
======
Refresh packaging.
v3.4.0
======
#68 and bpo-42090: ``Path.joinpath`` now takes arbitrary
positional arguments and no longer accepts ``add`` as a
keyword argument.
v3.3.2
======
Updated project metadata including badges.
v3.3.1
======
bpo-42043: Add tests capturing subclassing requirements.
v3.3.0
======
#9: ``Path`` objects now expose a ``.filename`` attribute
and rely on that to resolve ``.name`` and ``.parent`` when
the ``Path`` object is at the root of the zipfile.
v3.2.0
======
#57 and bpo-40564: Mutate the passed ZipFile object
type instead of making a copy. Prevents issues when
both the local copy and the caller's copy attempt to
close the same file handle.
#56 and bpo-41035: ``Path._next`` now honors
subclasses.
#55: ``Path.is_file()`` now returns False for non-existent names.
v3.1.0
======
#47: ``.open`` now raises ``FileNotFoundError`` and
``IsADirectoryError`` when appropriate.
v3.0.0
======
#44: Merge with v1.2.0.
v1.2.0
======
#44: ``zipp.Path.open()`` now supports a compatible signature
as ``pathlib.Path.open()``, accepting text (default) or binary
modes and soliciting keyword parameters passed through to
``io.TextIOWrapper`` (encoding, newline, etc). The stream is
opened in text-mode by default now. ``open`` no
longer accepts ``pwd`` as a positional argument and does not
accept the ``force_zip64`` parameter at all. This change is
a backward-incompatible change for that single function.
v2.2.1
======
#43: Merge with v1.1.1.
v1.1.1
======
#43: Restored performance of implicit dir computation.
v2.2.0
======
#36: Rebuild package with minimum Python version declared both
in package metadata and in the python tag.
v2.1.0
======
#32: Merge with v1.1.0.
v1.1.0
======
#32: For read-only zip files, complexity of ``.exists`` and
``joinpath`` is now constant time instead of ``O(n)``, preventing
quadratic time in common use-cases and rendering large
zip files unusable for Path. Big thanks to Benjy Weinberger
for the bug report and contributed fix (#33).
v2.0.1
======
#30: Corrected version inference (from jaraco/skeleton#12).
v2.0.0
======
Require Python 3.6 or later.
v1.0.0
======
Re-release of 0.6 to correspond with release as found in
Python 3.8.
v0.6.0
======
#12: When adding implicit dirs, ensure that ancestral directories
are added and that duplicates are excluded.
The library now relies on
`more_itertools <https://pypi.org/project/more_itertools>`_.
v0.5.2
======
#7: Parent of a directory now actually returns the parent.
v0.5.1
======
Declared package as backport.
v0.5.0
======
Add ``.joinpath()`` method and ``.parent`` property.
Now a backport release of the ``zipfile.Path`` class.
v0.4.0
======
#4: Add support for zip files with implied directories.
v0.3.3
======
#3: Fix issue where ``.name`` on a directory was empty.
v0.3.2
======
#2: Fix TypeError on Python 2.7 when classic division is used.
v0.3.1
======
#1: Fix TypeError on Python 3.5 when joining to a path-like object.
v0.3.0
======
Add support for constructing a ``zipp.Path`` from any path-like
object.
``zipp.Path`` is now a new-style class on Python 2.7.
v0.2.1
======
Fix issue with ``__str__``.
v0.2.0
======
Drop reliance on future-fstrings.
v0.1.0
======
Initial release with basic functionality.
| zipp | /zipp-3.16.2.tar.gz/zipp-3.16.2/NEWS.rst | NEWS.rst |
.. image:: https://img.shields.io/pypi/v/zipp.svg
:target: https://pypi.org/project/zipp
.. image:: https://img.shields.io/pypi/pyversions/zipp.svg
.. image:: https://github.com/jaraco/zipp/workflows/tests/badge.svg
:target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
:alt: tests
.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
:target: https://github.com/astral-sh/ruff
:alt: Ruff
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
:alt: Code style: Black
.. .. image:: https://readthedocs.org/projects/PROJECT_RTD/badge/?version=latest
.. :target: https://PROJECT_RTD.readthedocs.io/en/latest/?badge=latest
.. image:: https://img.shields.io/badge/skeleton-2023-informational
:target: https://blog.jaraco.com/skeleton
.. image:: https://tidelift.com/badges/package/pypi/zipp
:target: https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=readme
A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
`Path object <https://docs.python.org/3.8/library/zipfile.html#path-objects>`_.
Compatibility
=============
New features are introduced in this third-party library and later merged
into CPython. The following table indicates which versions of this library
were contributed to different versions in the standard library:
.. list-table::
:header-rows: 1
* - zipp
- stdlib
* - 3.15
- 3.12
* - 3.5
- 3.11
* - 3.2
- 3.10
* - 3.3 ??
- 3.9
* - 1.0
- 3.8
Usage
=====
Use ``zipp.Path`` in place of ``zipfile.Path`` on any Python.
For Enterprise
==============
Available as part of the Tidelift Subscription.
This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.
`Learn more <https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=referral&utm_campaign=github>`_.
| zipp | /zipp-3.16.2.tar.gz/zipp-3.16.2/README.rst | README.rst |
from collections import namedtuple
Path=namedtuple('Path', 'l, r, pnodes, ppath, changed')
def isa(type):
"""
Returns is_<type>(obj) a function that returns true
when it's argument is the istance of type
"""
def f(obj):
return isinstance(obj, type)
f.__name__ = "is_{0}".format(type)
return f
native_list = __builtins__['list']
def list(root):
return zipper(
root,
isa(native_list),
tuple,
lambda node, children: native_list(children)
)
native_dict = __builtins__['dict']
is_dict=isa(native_dict)
def dict(root):
return zipper(
root,
# i is either the root object or a tuple of key value pairs
lambda i: i is is_dict(root) or is_dict(i[1]),
lambda i: tuple(i.items() if i is is_dict(i) else i[1].items()),
lambda node, children: native_dict(children)
)
def zipper(root, is_branch, children, make_node):
return Loc(root, None, is_branch, children, make_node)
class Loc(namedtuple('Loc', 'current, path, is_branch, get_children, make_node')):
def __repr__(self):
return "<zipper.Loc({}) object at {}>".format(self.current, id(self))
## Context
def node(self):
return self.current
def children(self):
if self.branch():
return self.get_children(self.current)
def branch(self):
return self.is_branch(self.current)
def root(self):
return self.top().current
def at_end(self):
return not bool(self.path)
## Navigation
def down(self):
children = self.children()
if children:
path = Path(
l=(),
r=children[1:],
pnodes=self.path.pnodes + (self.current,) if self.path else (self.current,),
ppath = self.path,
changed=False
)
return self._replace(current=children[0],path=path)
def up(self):
if self.path:
l, r, pnodes, ppath, changed = self.path
if pnodes:
pnode = pnodes[-1]
if changed:
return self._replace(
current=self.make_node(pnode, l+(self.current,)+r),
path = ppath and ppath._replace(changed=True)
)
else:
return self._replace(current=pnode,path=ppath)
def top(self):
loc = self
while loc.path:
loc = loc.up()
return loc
def ancestor(self,filter):
"""
Return the first ancestor preceding the current loc that
matches the filter(ancestor) function.
The filter function is invoked with the location of the
next ancestor. If the filter function returns true then
the ancestor will be returned to the invoker of
loc.ancestor(filter) method. Otherwise the search will move
to the next ancestor until the top of the tree is reached.
"""
u = self.up()
while u:
if filter(u):
return u
else:
u = u.up()
def left(self):
if self.path and self.path.l:
ls, r = self.path[:2]
l,current = ls[:-1], ls[-1]
return self._replace(current=current, path=self.path._replace(
l = l,
r = (self.current,) + r
))
def leftmost(self):
"""Returns the left most sibling at this location or self"""
path = self.path
if path:
l,r = self.path[:2]
t = l + (self.current,) + r
current = t[0]
return self._replace(current=current, path=path._replace(
l = (),
r = t[1:]
))
else:
return self
def rightmost(self):
"""Returns the right most sibling at this location or self"""
path = self.path
if path:
l,r = self.path[:2]
t = l + (self.current,) + r
current = t[-1]
return self._replace(current=current, path=path._replace(
l = t[:-1],
r = ()
))
else:
return self
def right(self):
if self.path and self.path.r:
l, rs = self.path[:2]
current, rnext = rs[0], rs[1:]
return self._replace(current=current, path=self.path._replace(
l=l+(self.current,),
r = rnext
))
def leftmost_descendant(self):
loc = self
while loc.branch():
d = loc.down()
if d:
loc = d
else:
break
return loc
def rightmost_descendant(self):
loc = self
while loc.branch():
d = loc.down()
if d:
loc = d.rightmost()
else:
break
return loc
def move_to(self, dest):
"""
Move to the same 'position' in the tree as the given loc and return
the loc that currently resides there. This method does not gurantee
that the node from the previous loc will be the same node if the node
or it's ancestory has bee modified.
"""
moves = []
path = dest.path
while path:
moves.extend(len(path.l) * ['r'])
moves.append('d')
path = path.ppath
moves.reverse()
loc = self.top()
for m in moves:
if m == 'd':
loc = loc.down()
else:
loc = loc.right()
return loc
## Enumeration
def preorder_iter(self):
loc = self
while loc:
loc = loc.preorder_next()
if loc:
yield loc
def preorder_next(self):
"""
Visit's nodes in depth-first pre-order.
For eaxmple given the following tree:
a
/ \
b e
^ ^
c d f g
preorder_next will visit the nodes in the following order
b, c, d, e, f, g, a
See preorder_iter for an example.
"""
if self.path is ():
return None
n = self.down() or self.right()
if n is not None:
return n
else:
u = self.up()
while u:
r = u.right()
if r:
return r
else:
if u.path:
u = u.up()
else:
return u._replace(path=())
def postorder_next(self):
"""
Visit's nodes in depth-first post-order.
For eaxmple given the following tree:
a
/ \
b e
^ ^
c d f g
postorder next will visit the nodes in the following order
c, d, b, f, g, e a
Note this method ends when it reaches the root node. To
start traversal from the root call leftmost_descendant()
first. See postorder_iter for an example.
"""
r = self.right()
if (r):
return r.leftmost_descendant()
else:
return self.up()
def postorder_iter(self):
loc = self.leftmost_descendant()
while loc:
yield loc
loc = loc.postorder_next()
## editing
def append(self, item):
"""
Inserts the item as the rightmost child of the node at this loc,
without moving.
"""
return self.replace(
self.make_node(self.node(), self.children()+(item,))
)
def edit(self, f, *args):
"Replace the node at this loc with the value of f(node, *args)"
return self.replace(f(self.current, *args))
def insert(self, item):
"""
Inserts the item as the leftmost child of the node at this loc,
without moving.
"""
return self.replace(
self.make_node(self.node(), (item,) + self.children())
)
def insert_left(self, item):
"""Insert item as left sibling of node without moving"""
path = self.path
if not path:
raise IndexError("Can't insert at top")
new = path._replace(l=path.l + (item,) , changed=True)
return self._replace(path=new)
def insert_right(self, item):
"""Insert item as right sibling of node without moving"""
path = self.path
if not path:
raise IndexError("Can't insert at top")
new = path._replace(r=(item,) + path.r, changed=True)
return self._replace(path=new)
def replace(self, value):
if self.path:
return self._replace(current=value, path=self.path._replace(changed=True))
else:
return self._replace(current=value)
def find(self, func):
loc = self.leftmost_descendant()
while True:
if func(loc):
return loc
elif loc.at_end():
return None
else:
loc = loc.postorder_next()
def remove(self):
"""
Removes the node at the current location, returning the
node that would have proceeded it in a depth-first walk.
For eaxmple given the following tree:
a
/ \
b e
^ ^
c d f g
^
c1 c2
Removing c would return b, removing d would return c2.
"""
path = self.path
if not path:
raise IndexError("Remove at top")
l, r, pnodes, ppath, changed = path
if l:
ls, current = l[:-1], l[-1]
return self._replace(current=current, path=path._replace(
l=ls,
changed=True
)).rightmost_descendant()
else:
return self._replace(
current=self.make_node(pnodes[-1], r),
path = ppath and ppath._replace(changed=True)
) | zipper | /zipper-0.0.3.tar.gz/zipper-0.0.3/zipper.py | zipper.py |
from zippy_form.utils import FIELD_RULES_FILE_FORMAT_ALLOWED
def get_text_box_field_validation_rule_schema():
# Get Text Box field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"minlength": 2,
"maxlength": 10
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"minlength": {"type": "integer", "minimum": 1},
"maxlength": {"type": "integer", "minimum": 1},
},
"required": ["required", "unique", "minlength", "maxlength"],
"additionalProperties": False
}
return schema
def get_website_url_field_validation_rule_schema():
# Get Website URL field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"url": true - should be always true
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"url": {"type": "boolean"}
},
"required": ["required", "unique", "url"],
"additionalProperties": False
}
return schema
def get_textarea_field_validation_rule_schema():
# Get TextArea field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"minlength": 2,
"maxlength": 10
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"minlength": {"type": "integer", "minimum": 1},
"maxlength": {"type": "integer", "minimum": 1},
},
"required": ["required", "unique", "minlength", "maxlength"],
"additionalProperties": False
}
return schema
def get_number_field_validation_rule_schema():
# Get Number field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"min": 2,
"max": 10,
"number" true - should be always true
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"min": {"type": "integer", "minimum": 1},
"max": {"type": "integer", "minimum": 1},
"number": {"type": "boolean"},
"decimal": {"type": "boolean"},
"decimal_places": {"type": "integer", "minimum": 0},
},
"required": ["required", "unique", "min", "max", "number", "decimal", "decimal_places"],
"additionalProperties": False
}
return schema
def get_email_field_validation_rule_schema():
# Get Email field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"email": true - should be always true
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"email": {"type": "boolean"},
},
"required": ["required", "unique", "email"],
"additionalProperties": False
}
return schema
def get_dropdown_field_validation_rule_schema():
# Get Dropdown field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"max_selection": 2
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"max_selection": {"type": "integer", "minimum": 1},
},
"required": ["required", "max_selection"],
"additionalProperties": False
}
return schema
def get_radio_field_validation_rule_schema():
# Get Radio field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
},
"required": ["required", "unique"],
"additionalProperties": False
}
return schema
def get_date_field_validation_rule_schema():
# Get Date field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"date": true, - should be always true
"date_format": 'm-d-Y',
}
Allowed Date Format: refer 'FIELD_RULES_DATE_FORMAT_ALLOWED' utils
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"date": {"type": "boolean"},
"date_format": {"type": "string"},
},
"required": ["required", "unique", "date", "date_format"],
"additionalProperties": False
}
return schema
def get_time_field_validation_rule_schema():
# Get Time field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"time": true, - should be always true
"time_format": '12'
}
Allowed Date Format: refer 'FIELD_RULES_TIME_FORMAT_ALLOWED' utils
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"time": {"type": "boolean"},
"time_format": {"type": "string"},
},
"required": ["required", "unique", "time", "time_format"],
"additionalProperties": False
}
return schema
def get_short_textarea_field_validation_rule_schema():
# Get Short TextArea field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
"minlength": 2,
"maxlength": 10
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
"minlength": {"type": "integer", "minimum": 1},
"maxlength": {"type": "integer", "minimum": 1},
},
"required": ["required", "unique", "minlength", "maxlength"],
"additionalProperties": False
}
return schema
def get_file_field_validation_rule_schema():
# Get File field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"file": true, - should be always true
"file_max_size_mb": 2, - 2MB(value should be added in MB)
"file_extensions_allowed": [],
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"file": {"type": "boolean"},
"file_max_size_mb": {"type": "number", "minimum": 0, "multipleOf": 0.1},
"file_extensions_allowed": {
"type": "array",
"items": {
"type": "string",
"enum": FIELD_RULES_FILE_FORMAT_ALLOWED
}
}
},
"required": ["required", "file", "file_max_size_mb", "file_extensions_allowed"],
"additionalProperties": False
}
return schema
def get_multiselect_checkbox_field_validation_rule_schema():
# Get MultiSelect Checkbox field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"max_selection": 2
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"max_selection": {"type": "integer", "minimum": 1},
},
"required": ["required", "max_selection"],
"additionalProperties": False
}
return schema
def get_hidden_field_validation_rule_schema():
# Get Hidden field Validation Rules Schema
"""
Sample Valid Schema:
{
"required": true,
"unique": false,
}
"""
schema = {
"type": "object",
"properties": {
"required": {"type": "boolean"},
"unique": {"type": "boolean"},
},
"required": ["required", "unique"],
"additionalProperties": False
}
return schema | zippy-form | /zippy_form-1.0.0-py3-none-any.whl/zippy_form/validation_rule_schema.py | validation_rule_schema.py |
import json
from django.core.paginator import Paginator
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from zippy_form.models import FormField, Form, FormStep, FormSubmission, FormSubmissionData, FormFieldOption
from zippy_form.serializers import FormSerializer, FormStepSerializer, MapFieldToFormStepSerializer, UpdateFieldSettingsSerializer, ReOrderFieldSerializer
from zippy_form.utils import FORM_STATUS, FORM_FIELD_STATUS, FIELD_TYPES, FORM_SUBMISSION_STATUS, \
FORM_SUBMISSION_STATUS_TEXT, FORM_STEP_STATUS, FIELD_RULES, FORM_FIELD_OPTION_STATUS, FIELD_RULES_FILE_FORMAT_ALLOWED, \
FORM_STATUS_DETAILS, FORM_FIELD_DETAILS, FORM_STEP_STATUS_DETAILS
from zippy_form.validation_rule import validate_is_empty, validate_minlength, validate_maxlength, validate_is_url,\
validate_is_unique, validate_is_number, validate_min_value, validate_max_value, validate_is_email, validate_is_date,\
validate_min_max_selection, validate_is_file, validate_file_extension, validate_file_size, validate_is_time
DEAFULT_PAGE_SIZE = 6
def dynamic_form_middleware():
print("aww")
@api_view(['GET'])
def form_list(req):
"""
Get list of non deleted forms
"""
page_size = DEAFULT_PAGE_SIZE
response_data = {'list': {}}
page = req.GET.get('page', 1)
# Get only non deleted forms
form_submissions = Form.objects.exclude(status=FORM_STATUS[0][0]).order_by('-created_date')
# TODO - Search by name & filter by form status
paginator = Paginator(form_submissions, page_size)
page_obj = paginator.get_page(page)
if int(page) > page_obj.paginator.num_pages:
response_data['list']['per_page'] = 0
response_data['list']['page'] = 0
response_data['list']['total'] = 0
response_data['list']['total_pages'] = 0
response_data['list']['data'] = []
response_data['list']['msg'] = "Invalid Page."
return Response({"status": "error", "data": response_data}, status=status.HTTP_400_BAD_REQUEST)
else:
data = []
# Loop each form
for form in page_obj.object_list:
single_row_entry = {}
single_row_entry['id'] = form.id
single_row_entry['name'] = form.name
single_row_entry['description'] = form.description
single_row_entry['status'] = form.status
single_row_entry['status_text'] = FORM_STATUS_DETAILS[form.status]
data.append(single_row_entry)
response_data['list']['per_page'] = page_obj.paginator.per_page
response_data['list']['page'] = page_obj.number
response_data['list']['total'] = page_obj.paginator.count
response_data['list']['total_pages'] = page_obj.paginator.num_pages
response_data['list']['data'] = data
return Response({"status": "success", "data": response_data}, status=status.HTTP_200_OK)
@api_view(['POST'])
def create_form(req):
"""
Create form with status draft with step 1 - To be used when clicking "Add Form" from the form builder
"""
form = Form.objects.create(name="Untitled Form")
form_step = FormStep.objects.create(
name="Step 1",
step_order=1,
form=form,
)
steps = []
response_data = {'form': {}, 'steps': steps}
response_data['form']['id'] = form.id
response_data['form']['name'] = form.name
response_data['form']['description'] = ''
response_data['form']['class_name'] = ''
response_data['form']['success_msg'] = ''
response_data['form']['status'] = form.status
response_data['form']['status_text'] = FORM_STATUS_DETAILS[form.status]
step_details = {'id': form_step.id, 'name': form_step.name, 'description': '', 'is_current_step': True}
steps.append(step_details)
return Response({"status": "success", "data": response_data, "msg": "Form Created Successfully."},
status=status.HTTP_201_CREATED)
@api_view(['PUT'])
def update_form(req, form_id):
"""
Update form
* Update form & field status from Draft to Active
"""
try:
# Update only for non deleted form
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
msg = "Invalid Form ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
serializer = FormSerializer(form, data=req.data)
if not serializer.is_valid():
return Response({"status": "validation_error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
else:
form.name = serializer.validated_data['name']
# Update draft form to active status
if form.status == FORM_STATUS[3][0]:
form.status = FORM_STATUS[1][0]
form.save()
# Update draft fields of the form to active status, which has field settings updated
form_fields = form.form_fields.filter(status=FORM_FIELD_STATUS[3][0]).filter(is_field_settings_updated=True)
for form_field in form_fields:
form_field.status = FORM_FIELD_STATUS[1][0]
form_field.save()
response_data = {'form': {}}
response_data['form']['id'] = form.id
response_data['form']['name'] = form.name
response_data['form']['description'] = ''
response_data['form']['class_name'] = ''
response_data['form']['success_msg'] = ''
response_data['form']['status'] = form.status
response_data['form']['status_text'] = FORM_STATUS_DETAILS[form.status]
return Response({"status": "success", "data": response_data, "msg": "Form Updated Successfully."},
status=status.HTTP_200_OK)
@api_view(['PUT'])
def update_form_status(req, form_id):
"""
Update form status
* Active to InActive
* InActive to Active
"""
try:
# Update form status only for the non deleted form
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
data = "Invalid Form ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
if form.status == FORM_STATUS[1][0]:
# Update form status from Active to InActive
form.status = FORM_STATUS[2][0]
form.save()
elif form.status == FORM_STATUS[2][0]:
# Update form status from InActive to Active
form.status = FORM_STATUS[1][0]
form.save()
response_data = {'form': {}}
response_data['form']['id'] = form.id
return Response({"status": "success", "data": response_data, "msg": "Form Status Updated Successfully."},
status=status.HTTP_200_OK)
@api_view(['DELETE'])
def delete_form(req, form_id):
"""
Soft delete form
"""
try:
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
data = "Invalid Form ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
# Soft delete form
form.status = FORM_STATUS[0][0]
form.save()
response_data = {'form': {}}
response_data['form']['id'] = form.id
return Response({"status": "success", "data": response_data, "msg": "Form Deleted Successfully."},
status=status.HTTP_200_OK)
@api_view(['GET'])
def form_submission_list(req, form_id):
"""
Get list of form submissions
"""
try:
# Get submission only for the non deleted form
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
data = "Invalid Form ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
page_size = DEAFULT_PAGE_SIZE
response_data = {'list': {}}
page = req.GET.get('page', 1)
# Get only non deleted form submission
form_submissions = FormSubmission.objects.filter(form=form_id).exclude(status=FORM_SUBMISSION_STATUS[0][0]) \
.order_by('-modified_date')
paginator = Paginator(form_submissions, page_size)
page_obj = paginator.get_page(page)
if int(page) > page_obj.paginator.num_pages:
response_data['list']['per_page'] = 0
response_data['list']['page'] = 0
response_data['list']['total'] = 0
response_data['list']['total_pages'] = 0
response_data['list']['data'] = []
response_data['list']['msg'] = "Invalid Page."
return Response({"status": "error", "data": response_data}, status=status.HTTP_400_BAD_REQUEST)
else:
column_headers = []
column_field_id = []
column_headers.append({"field_type": '_id', "label": 'Id'})
# Get only active fields which are configured to show on table
table_form_fields = form.form_fields.filter(status=FORM_FIELD_STATUS[1][0]).filter(show_on_table=True) \
.order_by('table_field_order')
# From above queryset - Get the "Column Headers" & "Field ID"
for table_form_field in table_form_fields:
column_headers.append({"field_type": table_form_field.field_type, "label": table_form_field.label})
column_field_id.append(str(table_form_field.id))
column_headers.append({"field_type": '_status_id', "label": 'Status ID'})
column_headers.append({"field_type": '_status', "label": 'Status'})
data = []
# Loop each form submission
for form_submission in page_obj.object_list:
single_row_entry = []
# default - "ID" at first index for each submission
single_row_entry.append(form_submission.id)
# get the submitted data from "FormSubmissionData" - based on the "form submission" & the active fields
# which are configured to show on table | getting all the values here, to reduce db call
dynamic_field_values = FormSubmissionData.objects.filter(form_submission=form_submission) \
.filter(form_field_id__in=column_field_id)
formatted_dynamic_field_values = {}
for dynamic_field_value in dynamic_field_values:
field_type = dynamic_field_value.form_field.field_type
if field_type == FIELD_TYPES[5][0]:
_values = format_string_to_json_array(dynamic_field_value.dropdown_field)
_option_values = get_field_option_values(_values)
if _value is not None:
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = _option_values
else:
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = []
elif field_type == FIELD_TYPES[6][0]:
_value = dynamic_field_value.radio_field
_option_value = get_field_option_value(_value)
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = _option_value
# elif field_type == FIELD_TYPES[7][0]:
# formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = dynamic_field_value.checkbox_field
elif field_type == FIELD_TYPES[10][0]:
_value = dynamic_field_value.file_field
if _value:
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = _value.url
else:
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = ""
elif field_type == FIELD_TYPES[12][0]:
_values = format_string_to_json_array(dynamic_field_value.multiselect_checkbox_field)
if _values is not None:
_option_values = get_field_option_values(_values)
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = _option_values
else:
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = []
else:
formatted_dynamic_field_values[str(dynamic_field_value.form_field.id)] = dynamic_field_value.text_field
# loop the active fields which are configured to show on table & get the values added on the submission
# using "formatted_dynamic_field_values"
for column_field in column_field_id:
if formatted_dynamic_field_values.get(column_field):
single_row_entry.append(formatted_dynamic_field_values.get(column_field))
elif formatted_dynamic_field_values.get(column_field) == []:
single_row_entry.append([])
else:
single_row_entry.append("")
# default - "Status ID & Status" at last index for each submission
single_row_entry.append(form_submission.status)
single_row_entry.append(FORM_SUBMISSION_STATUS_TEXT[form_submission.status])
data.append(single_row_entry)
response_data['column_headers'] = column_headers
response_data['list']['per_page'] = page_obj.paginator.per_page
response_data['list']['page'] = page_obj.number
response_data['list']['total'] = page_obj.paginator.count
response_data['list']['total_pages'] = page_obj.paginator.num_pages
response_data['list']['data'] = data
return Response({"status": "success", "data": response_data}, status=status.HTTP_200_OK)
@api_view(['GET'])
def steps_mapped_to_form(req, form_id):
"""
Get steps mapped to form
"""
try:
# Get form steps only for the non deleted form
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
data = "Invalid Form ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
page_size = DEAFULT_PAGE_SIZE
response_data = {'list': {}}
page = req.GET.get('page', 1)
form_steps = form.form_steps.exclude(status=FORM_STEP_STATUS[0][0]).order_by('step_order')
paginator = Paginator(form_steps, page_size)
page_obj = paginator.get_page(page)
if int(page) > page_obj.paginator.num_pages:
response_data['list']['per_page'] = 0
response_data['list']['page'] = 0
response_data['list']['total'] = 0
response_data['list']['total_pages'] = 0
response_data['list']['data'] = []
response_data['list']['msg'] = "Invalid Page."
return Response({"status": "error", "data": response_data}, status=status.HTTP_400_BAD_REQUEST)
else:
data = []
# Loop each step
for form_step in page_obj.object_list:
single_row_entry = {}
single_row_entry['id'] = form_step.id
single_row_entry['name'] = form_step.name
single_row_entry['description'] = form_step.description
single_row_entry['status'] = form_step.status
single_row_entry['status_text'] = FORM_STEP_STATUS_DETAILS[form_step.status]
data.append(single_row_entry)
response_data['list']['per_page'] = page_obj.paginator.per_page
response_data['list']['page'] = page_obj.number
response_data['list']['total'] = page_obj.paginator.count
response_data['list']['total_pages'] = page_obj.paginator.num_pages
response_data['list']['data'] = data
return Response({"status": "success", "data": response_data}, status=status.HTTP_200_OK)
@api_view(['POST'])
def create_form_step(req):
"""
Create form step & map to form
"""
serializer = FormStepSerializer(data=req.data)
if not serializer.is_valid():
return Response({"status": "validation_error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
else:
instance = serializer.save()
response_data = {'step': {}}
response_data['step']['id'] = instance.id
response_data['step']['name'] = instance.name
return Response({"status": "success", "data": response_data, "msg": "Form Step Created Successfully."},
status=status.HTTP_201_CREATED)
@api_view(['PUT'])
def update_form_step(req, step_id):
"""
Update form step
"""
try:
form_step = FormStep.objects.filter(id=step_id).exclude(status=FORM_STATUS[0][0]).get()
except FormStep.DoesNotExist:
data = "Invalid Form Step ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
serializer = FormStepSerializer(form_step, data=req.data)
if not serializer.is_valid():
return Response({"status": "validation_error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
else:
instance = serializer.save()
response_data = {'step': {}}
response_data['step']['id'] = instance.id
response_data['step']['name'] = instance.name
return Response({"status": "success", "data": response_data, "msg": "Form Step Updated Successfully."},
status=status.HTTP_200_OK)
@api_view(['DELETE'])
def delete_form_step(req, step_id):
"""
Soft delete form step
"""
try:
form_step = FormStep.objects.filter(id=step_id).exclude(status=FORM_STATUS[0][0]).get()
except FormStep.DoesNotExist:
data = "Invalid Form Step ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
# Soft delete form step
form_step.status = FORM_STEP_STATUS[0][0]
form_step.save()
response_data = {'step': {}}
response_data['step']['id'] = form_step.id
response_data['step']['name'] = form_step.name
return Response({"status": "success", "data": response_data, "msg": "Form Step Deleted Successfully."},
status=status.HTTP_200_OK)
@api_view(['GET'])
def fields_mapped_to_form_step(req, form_id, step_id = None):
"""
Get list of fields mapped to form step
"""
try:
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
data = "Invalid Form ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
# Get all step mapped to form - Query not executed here
form_steps = form.form_steps.filter(status=FORM_STEP_STATUS[1][0]).order_by('step_order')
if step_id is None:
# Query executed here
first_form_step = form_steps.first()
current_step = str(first_form_step.id)
else:
# Check if the "step id" received from request is valid
try:
form.form_steps.filter(id=step_id).filter(status=FORM_STEP_STATUS[1][0]).get()
except FormStep.DoesNotExist:
data = "Invalid Form Step ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
current_step = step_id
# Todo - Check what happens if their is no steps on the form
# Get only active fields
form_fields = FormField.objects.filter(form_id=form_id).filter(form_step=current_step) \
.exclude(status=FORM_FIELD_STATUS[0][0]).order_by('field_order').prefetch_related('form_field_options')
steps = []
fields = []
response_data = {'action': "#", 'form': {}, 'steps': steps, 'fields': fields}
response_data['form']['id'] = form.id
response_data['form']['name'] = form.name
response_data['form']['description'] = form.description
response_data['form']['class_name'] = form.class_name
response_data['form']['success_msg'] = form.success_msg
response_data['form']['status'] = form.status
response_data['form']['status_text'] = FORM_STATUS_DETAILS[form.status]
for form_step in form_steps:
step = {}
step['id'] = form_step.id
step['name'] = form_step.name
step['description'] = form_step.description
if current_step == str(form_step.id):
step['is_current_step'] = True
else:
step['is_current_step'] = False
steps.append(step)
for form_field in form_fields:
field_details = {
'field_id': form_field.id,
'field_type': form_field.field_type,
'field_order': form_field.field_order,
'field_size': form_field.field_size,
'label': form_field.label,
'class_name': form_field.custom_class_name,
'is_mandatory': form_field.is_mandatory,
}
field_type = form_field.field_type
if field_type != FIELD_TYPES[14][0] and field_type != FIELD_TYPES[15][0]:
field_details['placeholder'] = form_field.placeholder
field_details['validations'] = form_field.validation_rule
if field_type == FIELD_TYPES[5][0] or field_type == FIELD_TYPES[6][0] or field_type == FIELD_TYPES[7][0] or \
field_type == FIELD_TYPES[12][0]:
# Get Options for Dropdown, Radio, Checkbox, MultiSelect Checkbox fields
field_options = []
form_field_options = form_field.form_field_options.filter(status=FORM_FIELD_OPTION_STATUS[1][0]).order_by(
'option_order').all()
for form_field_option in form_field_options:
field_option = {
'value': form_field_option.id,
'label': form_field_option.label,
}
field_options.append(field_option)
field_details['options'] = field_options
if field_type == FIELD_TYPES[0][0] or field_type == FIELD_TYPES[1][0] or field_type == FIELD_TYPES[3][0] or \
field_type == FIELD_TYPES[4][0] or field_type == FIELD_TYPES[5][0]:
# Text Box, Number, Email, Website URL, Dropdown
field_details['field_format'] = form_field.field_format
if field_type == FIELD_TYPES[14][0] or field_type == FIELD_TYPES[15][0]:
# Heading, Paragraph
field_details['content'] = form_field.content
field_details['content_size'] = form_field.content_size
field_details['content_alignment'] = form_field.content_alignment
field_details['status'] = form_field.status
field_details['status_text'] = FORM_FIELD_DETAILS[form_field.status]
fields.append(field_details)
response_data['fields'] = fields
return Response({"status": "success", "data": response_data}, status=status.HTTP_200_OK)
@api_view(['POST'])
def map_field_to_form_step(req):
"""
Map Field to Form Step with draft status
"""
serializer = MapFieldToFormStepSerializer(data=req.data)
if not serializer.is_valid():
return Response({"status": "validation_error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
else:
try:
# Map fields only for the non deleted form
form = serializer.validated_data['form']
form_id = form.id
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
data = {}
msg = []
data['form'] = msg
msg.append("Invalid Form ID.")
return Response({"status": "validation_error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
try:
# Map fields only for the active step
form_step = serializer.validated_data['form_step']
form_step_id = form_step.id
form_step = form.form_steps.filter(id=form_step_id).filter(status=FORM_STEP_STATUS[1][0]).get()
except FormStep.DoesNotExist:
data = {}
msg = []
data['form_step'] = msg
msg.append("Invalid Form Step ID.")
return Response({"status": "validation_error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
# Map field to form step
field_order = serializer.validated_data['field_order']
instance = serializer.save(table_field_order=field_order)
response_data = {'field': {}}
response_data['field']['id'] = instance.id
response_data['field']['label'] = instance.label
response_data['field']['type'] = instance.field_type
return Response({"status": "success", "data": response_data, "msg": "Field Mapped To Form Successfully."},
status=status.HTTP_200_OK)
@api_view(['PUT'])
def re_order_field(req, form_id, step_id, field_id):
"""
ReOrder Form Field
"""
# TODO - Need to test
try:
# ReOrder field only for non deleted form
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
msg = "Invalid Form ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
try:
# ReOrder field only for non deleted field step
form_steps = form.form_steps.filter(id=step_id).exclude(status=FORM_STEP_STATUS[0][0]).get()
except FormStep.DoesNotExist:
msg = "Invalid Form Step ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
try:
# ReOrder field only for non deleted field
field = form_steps.form_step_fields.filter(id=field_id).exclude(status=FORM_FIELD_STATUS[0][0]).get()
except FormField.DoesNotExist:
msg = "Invalid Form Field ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
serializer = ReOrderFieldSerializer(field, data=req.data)
if not serializer.is_valid():
return Response({"status": "validation_error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
else:
new_field_order = int(req.POST.get('field_order'))
old_field_order = field.field_order
if old_field_order < new_field_order:
# Moving field down, update fields between old and new position
fields_to_update = FormField.objects.filter(form_step__id=step_id).filter(field_order__gt=old_field_order,
field_order__lte=new_field_order).order_by('field_order')
for field in fields_to_update:
field.field_order -= 1
field.save()
elif old_field_order > new_field_order:
# Moving field up, update fields between new and old position
fields_to_update = FormField.objects.filter(form_step__id=step_id).filter(field_order__gte=new_field_order,
field_order__lt=old_field_order).order_by('-field_order')
for field in fields_to_update:
field.field_order += 1
field.save()
instance = serializer.save()
response_data = {'field': {}}
response_data['field']['id'] = instance.id
return Response({"status": "success", "data": response_data, "msg": "Field ReOrdered Successfully."},
status=status.HTTP_200_OK)
@api_view(['PUT'])
def update_field_settings(req, form_id, field_id):
"""
Update Field Settings
"""
try:
# Update field settings only for non deleted form
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
msg = "Invalid Form ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
try:
# Update field settings only for non deleted field
field = FormField.objects.filter(id=field_id).filter(form_id=form_id).exclude(status=FORM_FIELD_STATUS[0][0]).get()
except FormField.DoesNotExist:
msg = "Invalid Form Field ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
serializer = UpdateFieldSettingsSerializer(field, data=req.data)
if not serializer.is_valid():
return Response({"status": "validation_error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
else:
instance = serializer.save(is_field_settings_updated=True)
field_type = field.field_type
if field_type == FIELD_TYPES[5][0] or field_type == FIELD_TYPES[6][0] or field_type == FIELD_TYPES[7][0] or \
field_type == FIELD_TYPES[12][0]:
# Save Options for Dropdown, Radio, Checkbox, MultiSelect Checkbox fields
options = serializer.validated_data.get('options', [])
create_update_field_options(options, field)
response_data = {'field': {}}
response_data['field']['id'] = instance.id
return Response({"status": "success", "data": response_data, "msg": "Field Settings Updated Successfully."},
status=status.HTTP_200_OK)
@api_view(['DELETE'])
def delete_field(req, form_id, field_id):
"""
Soft delete field
"""
try:
form = Form.objects.filter(id=form_id).exclude(status=FORM_STATUS[0][0]).get()
except Form.DoesNotExist:
msg = "Invalid Form ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
try:
field = form.form_fields.filter(id=field_id).exclude(status=FORM_FIELD_STATUS[0][0]).get()
except FormField.DoesNotExist:
msg = "Invalid Form Field ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
# Soft delete form field
field.status = FORM_FIELD_STATUS[0][0]
field.save()
response_data = {'field': {}}
response_data['field']['id'] = instance.id
return Response({"status": "success", "data": response_data, "msg": "Form Field Deleted Successfully."},
status=status.HTTP_200_OK)
@api_view(['GET'])
def dynamic_form_list(req):
"""
Get list of active forms
"""
page_size = DEAFULT_PAGE_SIZE
response_data = {'list': {}}
page = req.GET.get('page', 1)
# Get only non deleted forms
form_submissions = Form.objects.filter(status=FORM_STATUS[1][0]).order_by('-created_date')
# TODO - Search by name & filter by form status
paginator = Paginator(form_submissions, page_size)
page_obj = paginator.get_page(page)
if int(page) > page_obj.paginator.num_pages:
response_data['list']['per_page'] = 0
response_data['list']['page'] = 0
response_data['list']['total'] = 0
response_data['list']['total_pages'] = 0
response_data['list']['data'] = []
response_data['list']['msg'] = "Invalid Page."
return Response({"status": "error", "data": response_data}, status=status.HTTP_400_BAD_REQUEST)
else:
data = []
# Loop each form
for form in page_obj.object_list:
single_row_entry = {}
single_row_entry['id'] = form.id
single_row_entry['name'] = form.name
single_row_entry['description'] = form.description
single_row_entry['status'] = form.status
single_row_entry['status_text'] = FORM_STATUS_DETAILS[form.status]
data.append(single_row_entry)
response_data['list']['per_page'] = page_obj.paginator.per_page
response_data['list']['page'] = page_obj.number
response_data['list']['total'] = page_obj.paginator.count
response_data['list']['total_pages'] = page_obj.paginator.num_pages
response_data['list']['data'] = data
return Response({"status": "success", "data": response_data}, status=status.HTTP_200_OK)
@api_view(['GET'])
def dynamic_form_fields_mapped_to_form_step(req, form_id, step_id=None):
"""
Frontend(Dynamic Form) - Active Field mapped to Form Step
"""
try:
# Get only active Form
form = Form.objects.filter(id=form_id).filter(status=FORM_STATUS[1][0]).get()
except Form.DoesNotExist:
data = "Invalid Form ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
# Get all step mapped to form - Query not executed here
form_steps = form.form_steps.filter(status=FORM_STEP_STATUS[1][0]).order_by('step_order')
if step_id is None:
# Query executed here
first_form_step = form_steps.first()
current_step = str(first_form_step.id)
else:
# Check if the "step id" received from request is valid
try:
form.form_steps.filter(id=step_id).filter(status=FORM_STEP_STATUS[1][0]).get()
except FormStep.DoesNotExist:
data = "Invalid Form Step ID."
return Response({"status": "error", "data": data}, status=status.HTTP_400_BAD_REQUEST)
current_step = step_id
# Todo - Check what happens if their is no steps on the form
# Get only active fields
form_fields = FormField.objects.filter(form_id=form_id).filter(form_step=current_step) \
.filter(status=FORM_FIELD_STATUS[1][0]).order_by('field_order').prefetch_related('form_field_options')
steps = []
fields = []
response_data = {'action': "#", 'form': {}, 'steps': steps, 'fields': fields}
response_data['form']['id'] = form.id
response_data['form']['name'] = form.name
response_data['form']['description'] = form.description
response_data['form']['class_name'] = form.class_name
response_data['form']['success_msg'] = form.success_msg
for form_step in form_steps:
step = {}
step['id'] = form_step.id
step['name'] = form_step.name
step['description'] = form_step.description
if current_step == str(form_step.id):
step['is_current_step'] = True
else:
step['is_current_step'] = False
steps.append(step)
for form_field in form_fields:
field_details = {
'field_id': form_field.id,
'field_type': form_field.field_type,
'field_order': form_field.field_order,
'label': form_field.label,
'class_name': form_field.field_size + " " + form_field.custom_class_name,
}
field_type = form_field.field_type
if field_type != FIELD_TYPES[14][0] and field_type != FIELD_TYPES[15][0]:
field_details['placeholder'] = form_field.placeholder
field_details['validations'] = form_field.validation_rule
if field_type == FIELD_TYPES[5][0] or field_type == FIELD_TYPES[6][0] or field_type == FIELD_TYPES[7][0] or \
field_type == FIELD_TYPES[12][0]:
# Get Options for Dropdown, Radio, Checkbox, MultiSelect Checkbox fields
field_options = []
form_field_options = form_field.form_field_options.filter(status=FORM_FIELD_OPTION_STATUS[1][0]).order_by('option_order').all()
for form_field_option in form_field_options:
field_option = {
'value': form_field_option.id,
'label': form_field_option.label,
}
field_options.append(field_option)
field_details['options'] = field_options
if field_type == FIELD_TYPES[0][0] or field_type == FIELD_TYPES[1][0] or field_type == FIELD_TYPES[3][0] or \
field_type == FIELD_TYPES[4][0] or field_type == FIELD_TYPES[5][0]:
# Text Box, Number, Email, Website URL, Dropdown
field_details['field_format'] = form_field.field_format
if field_type == FIELD_TYPES[14][0] or field_type == FIELD_TYPES[15][0]:
# Heading, Paragraph
field_details['content'] = form_field.content
field_details['content_size'] = form_field.content_size
field_details['content_alignment'] = form_field.content_alignment
fields.append(field_details)
response_data['fields'] = fields
return Response({"status": "success", "data": response_data}, status=status.HTTP_200_OK)
@api_view(['GET'])
def active_form_list(req):
"""
List of active Forms
"""
pass
@api_view(['POST'])
def submit_form(req, form_id, step_id, submission_id=None):
"""
Frontend(Dynamic Form) - Submit Form
"""
try:
# Allow submit only for active form from frontend
form = Form.objects.filter(id=form_id).filter(status=FORM_STATUS[1][0]).get()
except Form.DoesNotExist:
msg = "Invalid Form ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
# Check if the "step id" received from request is valid
try:
form.form_steps.filter(id=step_id).filter(status=FORM_STEP_STATUS[1][0]).get()
except FormStep.DoesNotExist:
msg = "Invalid Form Step ID."
return Response({"status": "error", "msg": msg}, status=status.HTTP_400_BAD_REQUEST)
# Get only active fields mapped to the step
form_fields = FormField.objects.filter(form_id=form_id).filter(form_step=step_id) \
.filter(status=FORM_FIELD_STATUS[1][0])
# Validate all active fields mapped to the step
validation = validate_form_fields(req, form_fields, req.data, step_id)
# Handle validation error
if validation['status'] == 'validation_error':
return Response(validation, status=status.HTTP_400_BAD_REQUEST)
# Handle validation success
if submission_id is None:
# Create Form Submission Entry
form_submission = FormSubmission.objects.create(form=form)
else:
# Existing Form Submission Entry
# Todo
pass
# Save form submission data against the form submission entry
for form_data in req.data:
form_data_key = form_data
form_data_value = req.data[form_data]
field_detail = FormField.objects.filter(id=form_data_key).filter(status=FORM_FIELD_STATUS[1][0]).first()
# Save form submission data to respective column based on the field type
if field_detail:
form_submission_data = FormSubmissionData()
form_submission_data.form_submission = form_submission
form_submission_data.form_field = field_detail
form_submission_data.form_field_type = field_detail.field_type
if field_detail.field_type == FIELD_TYPES[0][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[1][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[2][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[3][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[4][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[5][0]:
form_submission_data.dropdown_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[6][0]:
form_submission_data.radio_field = form_data_value
# elif field_detail.field_type == FIELD_TYPES[7][0]:
# form_submission_data.checkbox_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[8][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[9][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[10][0]:
form_submission_data.file_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[11][0]:
form_submission_data.text_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[12][0]:
form_submission_data.multiselect_checkbox_field = form_data_value
elif field_detail.field_type == FIELD_TYPES[13][0]:
form_submission_data.text_field = form_data_value
form_submission_data.save()
response_data = {'submission_id': form_submission.id}
return Response({"status": "success", "data": response_data, "msg": "Form Submitted Successfully."},
status=status.HTTP_200_OK)
def validate_form_fields(req, form_fields, req_data, step_id):
"""
Validate all fields mapped to the step, when submitting each form step
"""
form_req_data = {}
form_missing_fields = []
field_labels = {}
field_types = {}
field_validation_rules = {}
validation_errors = {}
# Loop & format the request data
for form_data in req_data:
field_key = str(form_data)
field_req_value = req_data[form_data]
form_req_data[field_key] = field_req_value
# Loop & get all the validation rules added for the fields
for form_field in form_fields:
field_key = str(form_field.id)
field_label = form_field.label
field_type = form_field.field_type
field_validation_rule = form_field.validation_rule
# if field is "dropdown, radio, multiselect checkbox", add additional validation rule to validate url
if field_type == FIELD_TYPES[5][0]:
field_validation_rule.update({"dropdown": True})
if field_type == FIELD_TYPES[6][0]:
field_validation_rule.update({"radio": True})
if field_type == FIELD_TYPES[12][0]:
field_validation_rule.update({"multiselect_checkbox": True})
field_labels[field_key] = field_label
field_types[field_key] = field_type
field_validation_rules[field_key] = field_validation_rule
# Get list of fields missed on the request
if field_key not in form_req_data:
# Todo - When working on Update for dynamic field, need to add logic to skip checking file
# field if not present on the form
form_missing_fields.append(field_key)
# Validate fields - Check if all the fields mapped for the step are present on the request
if len(form_missing_fields) > 0:
data = {}
for form_missing_field in form_missing_fields:
data[form_missing_field] = "This field is required."
return {"status": "validation_error", "error_on": "current_step", "error_step_id": step_id,
"data": data,
"msg": "Some fields missed or wrongly provided on the request."}
# Validate fields - Loop each request data & validate based on validation rules
for data in form_req_data:
field_key = data
field_label = field_labels[field_key]
field_validation_rule = field_validation_rules[field_key]
field_value = form_req_data[field_key]
field_type = field_types[field_key]
# Validate single field
validation = validate_form_field(req, field_key, field_label, field_validation_rule, field_value, field_type)
if len(validation) != 0:
# If single field has error
validation_errors.update(validation)
# Validate fields - If any of the fields mapped for the step has error
if len(validation_errors) > 0:
return {"status": "validation_error", "error_on": "current_step", "error_step_id": step_id, "data": validation_errors}
return {"status": "success"}
def validate_form_field(req, field_key, field_label, field_validation_rule, field_value, field_type):
"""
Validate single field based on the validation rule
"""
validation_error = {}
if FIELD_RULES[0][0] in field_validation_rule:
if field_validation_rule['required']:
error = validate_is_empty(field_value)
if error:
validation_error[field_key] = f"{field_label} may not be blank."
return validation_error
if FIELD_RULES[10][0] in field_validation_rule:
if field_value and field_validation_rule['max_selection']:
max_selection_allowed = field_validation_rule.get('max_selection', 1)
formatted_input = format_string_to_json_array(field_value)
if formatted_input is None:
validation_error[field_key] = f"{field_label} is invalid."
return validation_error
else:
validate_min = field_validation_rule['required']
validate_max = True
error = validate_min_max_selection(formatted_input, max_selection_allowed, validate_min, validate_max)
if error == 1:
validation_error[field_key] = f"Please select at least one choice."
return validation_error
elif error == 2:
validation_error[field_key] = f"You already reached the maximum number of accepted choices({max_selection_allowed})."
return validation_error
if FIELD_RULES[9][0] in field_validation_rule:
if field_value and field_validation_rule['number']:
decimal_places_allowed = field_validation_rule.get('decimal_places', 0)
if not field_validation_rule['decimal']:
# if field configured, not to have decimal places
error = validate_is_number(field_value)
if error:
validation_error[field_key] = f"{field_label} is invalid."
else:
formatted_field_value = parse_to_float(field_value)
# if field configured, to have decimal - allow value with decimal & without decimal
if formatted_field_value is None:
validation_error[field_key] = f"{field_label} is invalid."
else:
if '.' in str(field_value):
# if field is decimal, check the decimal place is same as the decimal place configured
decimal_places = len(str(field_value).split(".")[1])
if decimal_places != decimal_places_allowed:
validation_error[field_key] = f"{field_label} should contain {decimal_places_allowed} decimal places."
if validation_error:
return validation_error
if FIELD_RULES[1][0] in field_validation_rule:
if field_value:
minlength = field_validation_rule['minlength']
error = validate_minlength(field_value, minlength)
if error:
validation_error[field_key] = f"{field_label} must contain atleast {minlength} characters."
return validation_error
if FIELD_RULES[2][0] in field_validation_rule:
if field_value:
maxlength = field_validation_rule['maxlength']
error = validate_maxlength(field_value, maxlength)
if error:
validation_error[field_key] = f"{field_label} should not be greater than {maxlength} characters."
return validation_error
if FIELD_RULES[3][0] in field_validation_rule:
if field_value:
min_value = field_validation_rule['min']
error = validate_min_value(field_value, min_value)
if error:
validation_error[field_key] = f"{field_label} should be equal or greater than {min_value} digits."
return validation_error
if FIELD_RULES[4][0] in field_validation_rule:
if field_value:
max_value = field_validation_rule['max']
error = validate_max_value(field_value, max_value)
if error:
validation_error[field_key] = f"{field_label} should be equal or less than {max_value} digits."
return validation_error
if FIELD_RULES[5][0] in field_validation_rule:
if field_value and field_validation_rule['email']:
error = validate_is_email(field_value)
if error:
validation_error[field_key] = f"{field_label} is invalid."
return validation_error
if FIELD_RULES[6][0] in field_validation_rule:
if field_value and field_validation_rule['url']:
error = validate_is_url(field_value)
if error:
validation_error[field_key] = f"{field_label} is invalid."
return validation_error
if FIELD_RULES[7][0] in field_validation_rule:
if field_value and field_validation_rule['date']:
date_format_allowed = field_validation_rule.get('date_format', '')
error = validate_is_date(field_value, date_format_allowed)
if error:
validation_error[field_key] = f"{field_label} is invalid."
return validation_error
if FIELD_RULES[8][0] in field_validation_rule:
if field_value and field_validation_rule['unique']:
error = validate_is_unique(field_value, field_key, field_type)
if error:
validation_error[field_key] = f"{field_label} has been already taken."
return validation_error
if FIELD_RULES[11][0] in field_validation_rule:
if field_validation_rule['file']:
error = validate_is_file(field_key, req)
if error:
# if file added is not valid file
validation_error[field_key] = "No file uploaded."
return validation_error
else:
# if file added is valid file, validate extension
file_extensions_allowed = field_validation_rule.get('file_extensions_allowed', [])
invalid_file_error = validate_file_extension(field_value, file_extensions_allowed)
if invalid_file_error:
file_extensions_allowed = FIELD_RULES_FILE_FORMAT_ALLOWED
allowed_file_extensions = ", "
allowed_file_extensions = allowed_file_extensions.join(file_extensions_allowed)
validation_error[field_key] = f"Upload only {allowed_file_extensions} file."
return validation_error
else:
# if file added is with valid extension, validate file size
file_max_size_allowed = field_validation_rule.get('file_max_size_mb', 0)
invalid_file_size_error = validate_file_size(field_value, file_max_size_allowed)
if invalid_file_size_error:
# if file's size is greater than the allowed file size
validation_error[field_key] = f"Upload file smaller than {file_max_size_allowed}MB."
return validation_error
if FIELD_RULES[12][0] in field_validation_rule:
if field_value and field_validation_rule['time']:
time_format_allowed = field_validation_rule.get('time_format', '')
error = validate_is_time(field_value, time_format_allowed)
if error:
validation_error[field_key] = f"{field_label} is invalid."
return validation_error
return validation_error
def parse_to_float(value):
"""
Parse the value to float
"""
try:
parsed_value = float(value)
except:
parsed_value = None
return parsed_value
def format_string_to_json_array(string):
"""
Format string to json array
"""
formatted_string = None
try:
json_value = json.loads(string)
if type(json_value) is list:
formatted_string = json_value
else:
formatted_string = None
except:
formatted_string = None
return formatted_string
def create_update_field_options(options, field_instance):
"""
Create or Update Field Options
"""
options_to_create = []
options_to_edit = {}
options_to_edit__id = []
# loop all the form field options from request
for option in options:
id = option.get('value', '')
label = option.get('label', '')
order = option.get('order', 0)
if id:
options_to_edit[id] = {'label': label, 'order': order}
options_to_edit__id.append(id)
else:
options_to_create.append(option)
# Edit or Delete - Option
form_field_options = field_instance.form_field_options.filter(status=FORM_FIELD_OPTION_STATUS[1][0])
# loop all the form field options from DB with status "active", update or soft delete
for form_field_option in form_field_options:
option__id = str(form_field_option.id) # DB - Option ID
if option__id in options_to_edit__id:
req__option = options_to_edit[option__id] #get option received from request
req__option_label = req__option['label']
req__option_order = req__option['order']
# Update Label & Order if modified
if form_field_option.label != req__option_label or form_field_option.option_order != req__option_order:
form_field_option.label = req__option_label
form_field_option.option_order = req__option_order
form_field_option.save()
else:
# Soft Delete Option
form_field_option.status = FORM_FIELD_OPTION_STATUS[0][0]
form_field_option.save()
# Bulk Create - Option
field_option_objects = []
for option in options_to_create:
field_option = FormFieldOption(
label = option['label'],
option_order = option['order'],
form_field = field_instance
)
field_option_objects.append(field_option)
FormFieldOption.objects.bulk_create(field_option_objects)
def get_field_option_values(option_ids = []):
"""
Get Field Option Values - If option is non deleted
"""
# TODO - Check if only getting non deleted options
option_values = []
field_options = FormFieldOption.objects.filter(id__in=option_ids).filter(status=FORM_FIELD_OPTION_STATUS[1][0])
if field_options:
for field_option in field_options:
option_values.append(field_option.label)
return option_values
def get_field_option_value(option_id = ""):
"""
Get Field Option Value - If option is non deleted
"""
# TODO - Check if only getting non deleted option
option_value = ""
field_option = FormFieldOption.objects.filter(id=option_id).filter(status=FORM_FIELD_OPTION_STATUS[1][0]).first()
if field_option:
option_value = field_option.label
return option_value | zippy-form | /zippy_form-1.0.0-py3-none-any.whl/zippy_form/views.py | views.py |
FORM_STATUS = (
('deleted', 'Deleted'),
('active', 'Active'),
('in_active', 'InActive'),
('draft', 'Draft'),
)
FORM_STATUS_DETAILS = {
'deleted': 'Deleted',
'active': 'Active',
'in_active': 'InActive',
'draft': 'Draft',
}
FORM_STEP_STATUS = (
('deleted', 'Deleted'),
('active', 'Active'),
)
FORM_STEP_STATUS_DETAILS = {
'deleted': 'Deleted',
'active': 'Active',
}
FORM_FIELD_STATUS = (
('deleted', 'Deleted'),
('active', 'Active'),
('in_active', 'InActive'),
('draft', 'Draft'),
)
FORM_FIELD_DETAILS = {
'deleted': 'Deleted',
'active': 'Active',
'in_active': 'InActive',
'draft': 'Draft',
}
FORM_FIELD_OPTION_STATUS = (
('deleted', 'Deleted'),
('active', 'Active'),
)
FORM_SUBMISSION_STATUS = (
('deleted', 'Deleted'),
('active', 'Active'),
('draft', 'Draft'),
)
FORM_SUBMISSION_STATUS_TEXT = {
'deleted': 'Deleted',
'active': 'Active',
'draft': 'Draft',
}
FIELD_SIZE = (
('col-md-12', 'Large'),
('col-md-6', 'Medium'),
('col-md-4', 'Small'),
)
FIELD_TYPES = (
('text_box', 'Text Box'),
('website_url', 'Website URL'),
('text_area', 'TextArea'),
('number', 'Number'),
('email', 'Email'),
('dropdown', 'Dropdown'),
('radio', 'Radio'),
('checkbox', 'Checkbox'),
('date', 'Date'),
('time', 'Time'),
('file', 'File Upload'),
('short_text_area', 'Short TextArea'),
('multiselect_checkbox', 'MultiSelect Checkbox'),
('hidden', 'Hidden'),
('heading', 'Heading'),
('paragraph', 'Paragraph'),
)
FIELD_RULES = (
('required', 'Required'),
('minlength', 'MinLength'),
('maxlength', 'MaxLength'),
('min', 'Min'),
('max', 'Max'),
('email', 'Email'),
('url', 'URL'),
('date', 'Date'),
('unique', 'Unique'),
('number', 'Number'),
('max_selection', 'Max Selection'),
('file', 'File'),
('time', 'Time'),
)
FIELD_RULES_DATE_FORMAT_ALLOWED = {
'm-d-Y': '%m-%d-%Y',
'd-m-Y': '%d-%m-%Y'
}
FIELD_RULES_TIME_FORMAT_ALLOWED = {
'12': '%I:%M %p',
'24': '%H:%M'
}
FIELD_RULES_FILE_FORMAT_ALLOWED = ["jpg", "jpeg", "png", "doc", "pdf"] | zippy-form | /zippy_form-1.0.0-py3-none-any.whl/zippy_form/utils.py | utils.py |
from rest_framework import serializers
from jsonschema import validate, ValidationError
from django.conf import settings
from zippy_form.models import FormStep, FormField, Form
from zippy_form.utils import FIELD_TYPES, FIELD_RULES_DATE_FORMAT_ALLOWED, FIELD_RULES_TIME_FORMAT_ALLOWED, FORM_STATUS
from zippy_form.validation_rule_schema import get_text_box_field_validation_rule_schema, \
get_textarea_field_validation_rule_schema, get_website_url_field_validation_rule_schema, \
get_short_textarea_field_validation_rule_schema, get_number_field_validation_rule_schema, \
get_email_field_validation_rule_schema, get_date_field_validation_rule_schema, \
get_time_field_validation_rule_schema, get_dropdown_field_validation_rule_schema, \
get_radio_field_validation_rule_schema, get_multiselect_checkbox_field_validation_rule_schema, \
get_file_field_validation_rule_schema, get_hidden_field_validation_rule_schema
class FormSerializer(serializers.ModelSerializer):
class Meta:
model = Form
fields = ['id', 'name']
class FormStepSerializer(serializers.ModelSerializer):
class Meta:
model = FormStep
fields = ['id', 'name', 'form']
def validate_form(self, attrs):
if attrs.status == FORM_STATUS[0][0]:
raise serializers.ValidationError('Invalid Form ID.')
return attrs
def create(self, validated_data):
step_order = 1
last_form_step = FormStep.objects.filter(form_id=validated_data['form']).order_by('-step_order').first()
if last_form_step:
last_form_step_order = last_form_step.step_order
step_order = last_form_step_order + 1
validated_data['step_order'] = step_order
return FormStep.objects.create(**validated_data)
class MapFieldToFormStepSerializer(serializers.ModelSerializer):
class Meta:
model = FormField
fields = ['id', 'field_type', 'form', 'form_step', 'field_order']
class ReOrderFieldSerializer(serializers.ModelSerializer):
class Meta:
model = FormField
fields = ['id', 'field_order']
class UpdateFieldSettingsSerializer(serializers.ModelSerializer):
def validate_validation_rule(self, value):
if not value:
raise serializers.ValidationError("Invalid Validation Rule.")
filed_type = self.instance.field_type
# print(filed_type)
schema = None
if filed_type == FIELD_TYPES[0][0]:
schema = get_text_box_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[1][0]:
schema = get_website_url_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[2][0]:
schema = get_textarea_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[3][0]:
schema = get_number_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[4][0]:
schema = get_email_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[5][0]:
schema = get_dropdown_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[6][0]:
schema = get_radio_field_validation_rule_schema()
# elif filed_type == FIELD_TYPES[7][0]:
# schema = get_radio_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[8][0]:
schema = get_date_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[9][0]:
schema = get_time_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[10][0]:
schema = get_file_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[11][0]:
schema = get_short_textarea_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[12][0]:
schema = get_multiselect_checkbox_field_validation_rule_schema()
elif filed_type == FIELD_TYPES[13][0]:
schema = get_hidden_field_validation_rule_schema()
if schema:
try:
validate(value, schema)
except ValidationError as e:
# print("Schema Error: ", e)
raise serializers.ValidationError("Invalid Validation Rule.")
if filed_type == FIELD_TYPES[8][0]:
# additional validation for date field
if value['date']:
date_format = value['date_format']
field_rules_date_format_allowed = FIELD_RULES_DATE_FORMAT_ALLOWED.keys()
if date_format not in field_rules_date_format_allowed:
allowed_date_format = ", "
allowed_date_format = allowed_date_format.join(field_rules_date_format_allowed)
msg = f"Only {allowed_date_format} allowed for date format"
raise serializers.ValidationError(msg)
elif filed_type == FIELD_TYPES[9][0]:
# additional validation for time field
if value['time']:
time_format = value['time_format']
field_rules_time_format_allowed = FIELD_RULES_TIME_FORMAT_ALLOWED.keys()
if time_format not in field_rules_time_format_allowed:
allowed_time_format = ", "
allowed_time_format = allowed_time_format.join(field_rules_time_format_allowed)
msg = f"Only {allowed_time_format} hrs allowed for time format"
raise serializers.ValidationError(msg)
return value
def validate_field_format(self, value):
if not value:
raise serializers.ValidationError("This field may not be blank.")
# input_group_icon = []
# if hasattr(settings, 'ZF_INPUT_GROUP_ICONS'):
# _input_group_icon = settings.ZF_INPUT_GROUP_ICONS
# if type(_input_group_icon) == list:
# input_group_icon = _input_group_icon
schema = {
"type": "object",
"properties": {
"field_format": {
"type": "string",
"enum": ["default", "input_group"]
},
"input_group_icon": {
"type": "string",
},
"input_group_icon_position": {
"type": "string",
"enum": ["start", "end"]
},
},
"required": ["field_format"],
"additionalProperties": False
}
try:
validate(value, schema)
except ValidationError as e:
# print("Schema Error: ", e)
raise serializers.ValidationError("Invalid Format.")
return value
def validate_options(self, value):
if not value:
raise serializers.ValidationError("This field may not be blank.")
schema = {
"type": "array",
"items": {
"type": "object",
"properties": {
"value": {"type": "string"},
"label": {"type": "string"},
"order": {"type": "integer", "minimum": 0}
},
"required": ["value", "label", "order"],
"additionalProperties": False
}
}
try:
validate(value, schema)
except ValidationError as e:
# print("Schema Error: ", e)
raise serializers.ValidationError("Invalid Format.")
return value
def validate_content(self, value):
if not value:
raise serializers.ValidationError("This field may not be blank.")
return value
def validate_content_size(self, value):
if not value:
raise serializers.ValidationError("This field may not be blank.")
allowed_content_size = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p']
if value not in allowed_content_size:
allowed_content_size_msg = ", "
allowed_content_size_msg = allowed_content_size_msg.join(allowed_content_size)
raise serializers.ValidationError("Only " + allowed_content_size_msg + " allowed.")
return value
def validate_content_alignment(self, value):
if not value:
raise serializers.ValidationError("This field may not be blank.")
allowed_content_alignment = ['start', 'center', 'end']
if value not in allowed_content_alignment:
allowed_content_alignment_msg = ", "
allowed_content_alignment_msg = allowed_content_alignment_msg.join(allowed_content_alignment)
raise serializers.ValidationError("Only " + allowed_content_alignment_msg + " allowed.")
return value
def validate(self, attrs):
label_field = attrs.get('label', None)
field_size_field = attrs.get('field_size', None)
placeholder_field = attrs.get('placeholder', None)
custom_class_name_field = attrs.get('custom_class_name', None)
validation_rule_field = attrs.get('validation_rule', None)
field_format_field = attrs.get('field_format', None)
is_mandatory_field = attrs.get('is_mandatory', None)
options_field = attrs.get('options', None)
is_unique_field = attrs.get('is_unique', None)
content_field = attrs.get('content', None)
content_size_field = attrs.get('content_size', None)
content_alignment_field = attrs.get('content_alignment', None)
errors = {}
field_type = self.instance.field_type
if field_size_field is None:
errors["field_size"] = ["This field is required."]
if custom_class_name_field is None:
errors["custom_class_name"] = ["This field is required."]
if is_mandatory_field is None:
errors["is_mandatory"] = ["This field is required."]
if field_type == FIELD_TYPES[0][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is None:
errors["field_format"] = ["This field is required."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[1][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is None:
errors["field_format"] = ["This field is required."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[2][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[3][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is None:
errors["field_format"] = ["This field is required."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[4][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is None:
errors["field_format"] = ["This field is required."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[5][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is None:
errors["field_format"] = ["This field is required."]
if options_field is None:
errors["options"] = ["This field is required."]
if is_unique_field:
errors["is_unique"] = ["Unique Validation not allowed for this field type."]
if field_type == FIELD_TYPES[6][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is None:
errors["options"] = ["This field is required."]
if field_type == FIELD_TYPES[7][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is None:
errors["options"] = ["This field is required."]
if field_type == FIELD_TYPES[8][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[9][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[10][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if is_unique_field:
errors["is_unique"] = ["Unique Validation not allowed for this field type."]
if field_type == FIELD_TYPES[11][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[12][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if is_unique_field:
errors["is_unique"] = ["Unique Validation not allowed for this field type."]
if field_type == FIELD_TYPES[13][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is None:
errors["placeholder"] = ["This field is required."]
if validation_rule_field is None:
errors["validation_rule"] = ["This field is required."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if field_type == FIELD_TYPES[14][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is not None:
errors["placeholder"] = ["Placeholder not allowed for this field type."]
if validation_rule_field is not None:
errors["validation_rule"] = ["Validation Rule not allowed for this field type."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if is_unique_field:
errors["is_unique"] = ["Unique Validation not allowed for this field type."]
if content_field is None:
errors["content"] = ["This field is required"]
if content_size_field is None:
errors["content_size"] = ["This field is required"]
if content_alignment_field is None:
errors["content_alignment"] = ["This field is required"]
if field_type == FIELD_TYPES[15][0]:
if label_field is None:
errors["label"] = ["This field is required"]
if placeholder_field is not None:
errors["placeholder"] = ["Placeholder not allowed for this field type."]
if validation_rule_field is not None:
errors["validation_rule"] = ["Validation Rule not allowed for this field type."]
if field_format_field is not None:
errors["field_format"] = ["Field Format not allowed for this field type."]
if options_field is not None:
errors["options"] = ["Options not allowed for this field type."]
if is_unique_field:
errors["is_unique"] = ["Unique Validation not allowed for this field type."]
if content_field is None:
errors["content"] = ["This field is required"]
if content_size_field is None:
errors["content_size"] = ["This field is required"]
if content_alignment_field is None:
errors["content_alignment"] = ["This field is required"]
if errors:
raise serializers.ValidationError(errors)
return attrs
options = serializers.JSONField(required=False)
class Meta:
model = FormField
fields = ['id', 'label', 'field_size', 'placeholder', 'custom_class_name', 'validation_rule', 'is_mandatory',
'is_unique', 'options', 'field_format', 'content', 'content_size', 'content_alignment']
extra_kwargs = {
"label": {"required": False},
"field_size": {"required": False},
"placeholder": {"required": False, "allow_blank": True},
"custom_class_name": {"required": False},
"validation_rule": {"required": False},
"is_mandatory": {"required": False},
"is_unique": {"required": False},
} | zippy-form | /zippy_form-1.0.0-py3-none-any.whl/zippy_form/serializers.py | serializers.py |
import uuid
from django.db import models
from django.contrib.auth.models import User
from .utils import FORM_STATUS, FIELD_TYPES, FORM_FIELD_STATUS, FORM_SUBMISSION_STATUS, FIELD_SIZE, FORM_STEP_STATUS, \
FORM_FIELD_OPTION_STATUS
class Form(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
name = models.CharField(max_length=255)
description = models.TextField(blank=True)
class_name = models.CharField(max_length=255, blank=True)
success_msg = models.TextField(blank=True)
status = models.CharField(max_length=10, choices=FORM_STATUS, default=FORM_STATUS[3][0])
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None)
class FormStep(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
name = models.CharField(max_length=255)
description = models.TextField(blank=True)
form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name="form_steps")
step_order = models.PositiveIntegerField()
status = models.CharField(max_length=10, choices=FORM_STEP_STATUS, default=FORM_STEP_STATUS[1][0])
class FormField(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
label = models.CharField(max_length=255, default="Untitled")
field_type = models.CharField(max_length=20, choices=FIELD_TYPES)
field_size = models.CharField(max_length=20, choices=FIELD_SIZE, default=FIELD_SIZE[0][0])
placeholder = models.CharField(max_length=255, blank=True)
field_order = models.PositiveIntegerField()
custom_class_name = models.CharField(max_length=255, blank=True)
validation_rule = models.JSONField(default=dict)
field_format = models.JSONField(default=dict)
is_mandatory = models.BooleanField(default=False)
is_unique = models.BooleanField(default=False)
show_on_table = models.BooleanField(default=True)
table_field_order = models.PositiveIntegerField(default=0)
form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name="form_fields")
form_step = models.ForeignKey(FormStep, on_delete=models.CASCADE, related_name="form_step_fields")
status = models.CharField(max_length=10, choices=FORM_FIELD_STATUS, default=FORM_FIELD_STATUS[3][0])
is_field_settings_updated = models.BooleanField(default=False)
content = models.TextField(blank=True)
content_size = models.CharField(blank=True, max_length=255)
content_alignment = models.CharField(blank=True, max_length=255)
# Use 'FormFieldOption' table for saving dropdown, radio, checkbox options
class FormFieldOption(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
label = models.CharField(max_length=255)
option_order = models.PositiveIntegerField(default=0)
form_field = models.ForeignKey(FormField, on_delete=models.CASCADE, related_name="form_field_options")
status = models.CharField(max_length=10, choices=FORM_FIELD_OPTION_STATUS, default=FORM_FIELD_OPTION_STATUS[1][0])
class FormSubmission(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
form = models.ForeignKey(Form, on_delete=models.CASCADE)
submitted_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None)
status = models.CharField(max_length=10, choices=FORM_SUBMISSION_STATUS, default=FORM_SUBMISSION_STATUS[2][0])
user_agent = models.CharField(max_length=255, blank=True)
request_ip = models.CharField(max_length=255, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class FormSubmissionData(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
form_submission = models.ForeignKey(FormSubmission, on_delete=models.CASCADE)
form_field = models.ForeignKey(FormField, on_delete=models.CASCADE, null=True)
form_field_type = models.CharField(max_length=255, blank=True)
text_field = models.TextField(blank=True)
checkbox_field = models.BooleanField(blank=True, null=True)
multiselect_checkbox_field = models.JSONField(null=True, default=None)
radio_field = models.CharField(max_length=255, blank=True)
dropdown_field = models.JSONField(null=True, default=None)
file_field = models.FileField(blank=True) | zippy-form | /zippy_form-1.0.0-py3-none-any.whl/zippy_form/models.py | models.py |
import re
from datetime import datetime
from django.core.validators import URLValidator
from django.db.models import Q
from django.core.exceptions import ValidationError
from zippy_form.models import FormSubmissionData
from zippy_form.utils import FORM_SUBMISSION_STATUS, FIELD_TYPES, FIELD_RULES_DATE_FORMAT_ALLOWED, \
FIELD_RULES_TIME_FORMAT_ALLOWED
def validate_is_empty(value):
"""
Check if value exists or not
"""
error = False
if not value:
error = True
return error
def validate_minlength(value, minlength):
"""
Check if value is not less than the minimum characters set.
"""
error = False
if len(value) < minlength:
error = True
return error
def validate_maxlength(value, maxlength):
"""
Check if value is not greater than the maximum characters set.
"""
error = False
if len(value) > maxlength:
error = True
return error
def validate_is_url(value):
"""
Check if value is valid URL.
"""
error = False
url_validator = URLValidator(schemes=['http', 'https'])
try:
url_validator(value)
except ValidationError:
error = True
return error
def validate_is_unique(value, field_key, field_type):
"""
Check if value doesn't exist already.
"""
error = False
# Todo - When editing should exclude the current submission id
if field_type == FIELD_TYPES[0][0] or field_type == FIELD_TYPES[1][0] or field_type == FIELD_TYPES[2][0] \
or field_type == FIELD_TYPES[3][0] or field_type == FIELD_TYPES[4][0] or field_type == FIELD_TYPES[8][0] \
or field_type == FIELD_TYPES[9][0] or field_type == FIELD_TYPES[11][0]:
# Check value exist already only for the "Active" form submission.
value_already_exist = FormSubmissionData.objects. \
filter(Q(form_submission__status=FORM_SUBMISSION_STATUS[1][0])). \
filter(form_field_id=field_key).filter(text_field=value).exists()
if value_already_exist:
error = True
return error
def validate_is_number(value):
"""
Check if value is number.
"""
error = False
if not value.isnumeric():
error = True
return error
def validate_min_value(value, min_value):
"""
Check if value is greater or equal to the minimum value.
"""
error = False
if not float(value) >= float(min_value):
error = True
return error
def validate_max_value(value, max_value):
"""
Check if value is less or equal to the maximum value.
"""
error = False
if not float(value) <= float(max_value):
error = True
return error
def validate_is_email(value):
"""
Check if value is valid email.
"""
error = False
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(pattern, value):
error = True
return error
def validate_is_date(value, date_format_allowed):
"""
Check if value is valid date.
"""
try:
date_format_allowed = FIELD_RULES_DATE_FORMAT_ALLOWED[date_format_allowed]
datetime.strptime(value, date_format_allowed)
error = False
except ValueError:
error = True
return error
def validate_min_max_selection(value, max_selection_allowed, validate_min, validate_max):
"""
Check if length of the value matches the max selection allowed & has minimum 1 if the field is required
"""
error = 0 # 0 indicates no error
value_length = len(value)
if validate_min and value_length == 0:
error = 1
elif validate_max and len(value) > max_selection_allowed:
error = 2
return error
def validate_is_file(field_key, req):
"""
Check if value is valid file.
"""
error = False
uploaded_file = req.FILES.get(field_key, None)
if not uploaded_file:
error = True
return error
def validate_file_extension(uploaded_file, file_extensions_allowed):
"""
Check if value is valid file.
"""
error = False
file_extension = uploaded_file.name.split('.')[-1].lower()
if file_extension not in file_extensions_allowed:
error = True
return error
def validate_file_size(uploaded_file, max_file_size_allowed):
"""
Check if file size not greater than allowed file size limit.
"""
error = False
max_upload_size = max_file_size_allowed * 1024 * 1024 # MB
if uploaded_file.size > max_upload_size:
error = True
return error
def validate_is_time(value, time_format_allowed):
"""
Check if value is valid time.
"""
try:
date_format_allowed = FIELD_RULES_TIME_FORMAT_ALLOWED[time_format_allowed]
datetime.strptime(value, date_format_allowed)
error = False
except ValueError:
error = True
return error | zippy-form | /zippy_form-1.0.0-py3-none-any.whl/zippy_form/validation_rule.py | validation_rule.py |
===============================
zippy-ip-scanner
===============================
**A free, open-source cross-platform IP scanning application written in python.**
----
.. image:: https://github.com/swprojects/Zippy-Ip-Scanner/raw/master/zippyipscanner/splash.png?raw=true
:align: center
.. image:: https://img.shields.io/badge/License-GPL%20v3-blue.svg
.. image:: https://travis-ci.org/swprojects/Zippy-Ip-Scanner.svg?branch=master
:target: https://travis-ci.org/swprojects/Zippy-Ip-Scanner
.. image:: https://img.shields.io/pypi/v/zippy-ip-scanner.svg
:target: https://pypi.python.org/pypi/zippy-ip-scanner
.. image:: https://coveralls.io/repos/github/swprojects/Zippy-Ip-Scanner/badge.svg?branch=dev
:target: https://coveralls.io/github/swprojects/Zippy-Ip-Scanner?branch=dev
----
.. image:: https://github.com/swprojects/Zippy-Ip-Scanner/raw/master/resources/images/screen.png?raw=true
:align: center
Installation
============
Install via pip: **pip install zippy-ip-scanner**
.. _pypi: https://pypi.org/project/zippy-ip-scanner/#description
Alternate Installation
======================
*Executables can be found here:*
Github_
Sourceforge_
======
See issues_ for development progress, bugs and todo.
.. _issues: https://github.com/swprojects/Zippy-Ip-Scanner/issues/
.. _github: https://github.com/swprojects/Zippy-Ip-Scanner/releases/
.. _sourceforge: https://sourceforge.net/projects/zippy-ip-scanner/files/
| zippy-ip-scanner | /zippy-ip-scanner-1.1.0.tar.gz/zippy-ip-scanner-1.1.0/README.rst | README.rst |
__license__ = ("""
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
""") | zippy-ip-scanner | /zippy-ip-scanner-1.1.0.tar.gz/zippy-ip-scanner-1.1.0/zippyipscanner/license.py | license.py |
if __name__ != "__main__":
# this allows us import relatively
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import logging
from version import __version__
from license import __license__
import sys
from PyQt5.QtWidgets import (QApplication, QDialog, QGridLayout, QGroupBox,
QLabel, QTextEdit, QHBoxLayout)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
class AboutDialog(QDialog):
def __init__(self, parent=None, testing=False):
super(AboutDialog, self).__init__(parent)
self.setWindowTitle("About Zippy Ip Scanner")
self.testing = testing
if testing is False:
if parent:
self.setWindowIcon(QIcon(parent.appPath + "zippyipscanner.ico"))
self.initGUI()
self.show()
@property
def homePageLink(self):
return "www.sanawu.com"
@property
def macVendorLink(self):
return "http://macvendors.co/kb/privacy-policy"
@property
def macVendorPolicy(self):
p = ("Zippy Ip Scanner retrieves the MAC vendor name via MacVendors.co API and \n"
+ "therefore MAC vendor name retrieval is subject to <a href={0}>MacVendors.co"
+ " privacy policy</a>.\n".format(self.macVendorLink)
+ "Uncheck Manufacturer checkbox to disable this feature.")
return p
@property
def githubLink(self):
return "https://github.com/swprojects/Zippy-Ip-Scanner"
def keyPressEvent(self, event):
logging.info("AboutDialog->keyPressEvent")
try:
e = event.key()
except AttributeError:
e = event
if e == Qt.Key_Escape:
self.close()
def initGUI(self):
row = 0
self.grid = QGridLayout()
self.grid.setColumnStretch(0, 1)
self.grid.setColumnStretch(1, 1)
self.grid.setSpacing(5)
self.setLayout(self.grid)
# About
aboutLayout = QGridLayout()
gboxScan = QGroupBox("About", self)
gboxScan.setLayout(aboutLayout)
self.grid.addWidget(gboxScan, row, 0, 1, 2)
aboutLayout.addWidget(QLabel("Author:", self), 0, 0, 1, 2)
authorLabel = QLabel("<a href={0}>{1}</a>".format(self.homePageLink, self.homePageLink), self)
authorLabel.setTextFormat(Qt.RichText)
authorLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
aboutLayout.addWidget(authorLabel, 0, 2, 1, 2)
authorLabel.setOpenExternalLinks(True)
aboutLayout.addWidget(QLabel("Github:", self), 1, 0, 1, 2)
g = self.githubLink
homeLabel = QLabel("<a href={0}>{1}</a>".format(g, g), self)
homeLabel.setTextFormat(Qt.RichText)
homeLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
homeLabel.setOpenExternalLinks(True)
aboutLayout.addWidget(homeLabel, 1, 2, 1, 1)
aboutLayout.addWidget(QLabel("Version:", self), 2, 0, 1, 2)
aboutLayout.addWidget(QLabel(str(__version__), self), 2, 2, 1, 2)
# Mac Vender Lookup
row += 1
policyLayout = QHBoxLayout()
gboxPolicy = QGroupBox("Mac Vender Lookup", self)
gboxPolicy.setLayout(policyLayout)
self.grid.addWidget(gboxPolicy, row, 0, 1, 2)
policyLabel = QLabel(self.macVendorPolicy, self)
policyLabel.setWordWrap(True)
policyLabel.setTextFormat(Qt.RichText)
policyLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
policyLabel.setOpenExternalLinks(True)
policyLayout.addWidget(policyLabel)
# License
row += 1
self.grid.setRowStretch(row, 1)
gboxScanLayout = QHBoxLayout()
gboxScan = QGroupBox("License", self)
gboxScan.setLayout(gboxScanLayout)
self.grid.addWidget(gboxScan, row, 0, 1, 2)
licenseText = QTextEdit()
licenseText.setReadOnly(True)
licenseText.setAlignment(Qt.AlignCenter)
licenseText.setText(__license__)
gboxScanLayout.addWidget(licenseText)
if __name__ == "__main__":
app = QApplication(sys.argv)
gui = AboutDialog()
sys.exit(app.exec_()) | zippy-ip-scanner | /zippy-ip-scanner-1.1.0.tar.gz/zippy-ip-scanner-1.1.0/zippyipscanner/about.py | about.py |
import os
import sys
import json
import logging
from functools import partial
from PyQt5.QtCore import (Qt, QSize, QTimer, pyqtSlot, pyqtSignal)
from PyQt5.QtWidgets import (QApplication, QMainWindow, QSplashScreen)
from PyQt5.QtGui import (QIcon, QPixmap, QStandardItemModel)
appPath = ''
if __name__ != '__main__':
# this allows us to import relatively
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
appPath = os.path.dirname(os.path.realpath(__file__)) + '/'
if hasattr(Qt, 'AA_EnableHighDpiScaling'):
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
import functions
from about import AboutDialog
from dialogs.settings import SettingsDialog
from dialogs.checkforupdates import CheckForUpdates
from version import __version__
from forms.uimainwindow import Ui_MainWindow
from base.filteredmodel import FilteredModel
SYS_ARGS = {
'--verbose': 0,
}
# verbosity
LOG_LEVELS = {
'1': 20, # Info
'2': 10, # Debug
'3': 30, # Warning
'4': 40, # Error
'5': 50, # Critical
}
STOP_ICON = appPath + 'images/stop.png'
START_ICON = appPath + 'images/start.png'
CLEAR_ICON = appPath + 'images/clear.png'
MAX_HOSTNAME_CHECKS = 5
TIMER_CHECK_MS = 100
SPLASH_TIMEOUT = 1200
class MainWindow(QMainWindow):
signalAddPing = pyqtSignal(dict)
signalScanParams = pyqtSignal(dict)
signalStopScanning = pyqtSignal()
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self._isScanning = False
self._bitmaps = {}
self._sortBy = 0
self._addressResults = []
self.addressResultsCount = 0
self._addressDict = {}
self._hostnameCheck = {}
self._hostnameCheckThreads = {}
self.scanTotalCount = 0
self.pingThread = functions.PingAddress(self)
self.signalAddPing.connect(self.pingThread.slotAddPing)
self.signalScanParams.connect(self.pingThread.slotScanParams)
self.signalStopScanning.connect(self.pingThread.slotStopScanning)
self.parseIpthread = None
self.ipHeaders = ['IP Address', 'Hostname', 'Ping', 'TTL', 'Manufacturer', 'MAC Address']
self.currentIpList = None
self.setWindowTitle('Zippy IP Scanner v{0}'.format(__version__))
self.setWindowIcon(QIcon(appPath + 'zippyipscanner.ico'))
self._config = self.appDefaults
self.loadConfig()
self.statusBar()
self.updateUI()
self.show()
self.initTimers()
self.restoreConfigState()
if self.config.get('showSplash', None):
self.initSplash()
self.show()
@property
def appDefaults(self):
return {
'pos': None,
'size': [400, 300],
'ipStartHistory': [],
'ipEndHistory': [],
'customScanHistory': [],
'scanConfig': {'hostnameTimeout': '5',
'Hostname': True,
'Manufacturer': True,
'MAC Address': True},
'filter': {'showAliveOnly': True},
'rememberScanHistory': True,
'rememberWindowSize': True,
'showSplash': True,
}
@property
def appPath(self):
return appPath
@property
def config(self):
return self._config
@property
def configPath(self):
if sys.platform == 'linux':
from os.path import expanduser, join
from os import system
home = expanduser('~')
base = '{0}/.local/share/zippyipscanner/'.format(home)
system('mkdir -p {0}'.format(base))
path = join(base, 'config.json')
else:
path = 'config.json'
return path
@property
def isScanFiltered(self):
'''Are any of the filtering options enabled?
:returns: bool
'''
return self.checkBoxAlive.isChecked()
@property
def isScanning(self):
return self._isScanning
@isScanning.setter
def isScanning(self, value):
self._isScanning = value
@pyqtSlot(str)
def slotDebug(self, str):
logging.debug(str)
@pyqtSlot(str)
def slotLookupTimeout(self, address):
logging.info(address)
del self._hostnameCheck[address]
self.addressResultsCount += 1
@pyqtSlot(dict)
def slotHostnameResult(self, result):
'''
Receive a single hostname scan result
:param dict result: the result of a hostname scan
:returns: None
:raises KeyError: raises an exception
'''
logging.debug('MainWindow->slotHostnameResult %s' % str(result))
if self.isScanning is False:
return
try:
index = self._addressDict[result['address']]['index']
self.ipModel.setData(self.ipModel.index(index, self.ipHeaders.index('Hostname')), result['hostname'])
del self._hostnameCheck[result['address']]
del self._hostnameCheckThreads[result['address']]
self.addressResultsCount += 1
except KeyError:
logging.debug(KeyError)
@pyqtSlot(dict)
def slotScanIp(self, data):
'''
Append new scan entry to ip list and add to pingThread
:param dict data: contains IP address
:returns: None
:raises Exception: raises an exception
'''
self.ipModel.insertRow(self.ipModel.rowCount())
for col, header in enumerate(self.ipHeaders):
try:
index = self.ipModel.rowCount() - 1
self.ipModel.setData(self.ipModel.index(index, col), data[header])
address = data['IP Address']
self._addressDict[address] = {'index': index}
self.startScan(index, address)
except Exception as e:
logging.debug('MainWindow->slotScanIp: %s' % e)
@pyqtSlot(dict)
def slotScanResult(self, result):
'''
Receive and handle scan result
:param dict result: dict of ip scan result
:returns: None
:raises Error: if ipModel fails to setData
'''
logging.debug(result)
if self.isScanning is False:
return
try:
index = self._addressDict[result['IP Address']]['index']
except KeyError:
# Sometimes we receive a result even after stopping
self.stopScan()
return
if self.scanConfig['Hostname'].isChecked() and result['Ping']:
timeout = self.spinHostTimeout.value()
if timeout == -1:
timeout = 5
self._hostnameCheck[result['IP Address']] = functions.LookupHostname(self, result['IP Address'], timeout)
else:
self.addressResultsCount += 1
for k, v in result.items():
try:
self.ipModel.setData(self.ipModel.index(index, self.ipHeaders.index(k)), v)
except Exception as e:
logging.info('onTimerCheck::Exception: %s, k=%s, v=%s' % e, k, v)
@property
def scanParams(self):
'''Returns current user selected scan parameters'''
params = {}
for label, chkBox in self.scanConfig.items():
params[label] = chkBox.isChecked()
del params['Hostname']
return params
def checkForUpdates(self):
CheckForUpdates(self)
def clearIpListItems(self):
logging.info('MainWindow->clearIpListItems')
self.ipModel.removeRows(0, self.ipModel.rowCount())
def clearScanHistory(self, clear=['range', 'custom']):
logging.info('MainWindow->clearScanHistory')
if 'range' in clear:
self.config['ipStartHistory'] = []
self.config['ipEndHistory'] = []
if 'custom' in clear:
self.config['customScanHistory'] = []
self.restoreScanHistory()
self.saveConfig()
def cleanScan(self):
logging.info('MainWindow->cleanScan')
self._addressResults = []
self._addressDict = {}
self._addresses = {}
self._hostnameCheck = {}
self._hostnameCheckThreads = {}
self.setScanIcons(start=True)
def closeEvent(self, event):
logging.info('MainWindow->closeEvent')
self.stopScan()
self.saveConfig()
try:
self.splash.close()
except Exception:
pass
event.accept()
def createIpModel(self, parent):
logging.info('MainWindow->createIpModel')
model = QStandardItemModel(0, 6, parent)
for col, header in enumerate(self.ipHeaders):
logging.info('Adding column %s' % str(header))
model.setHeaderData(col, Qt.Horizontal, header)
return model
def createFilteredIpModel(self, parent):
logging.info('MainWindow->createIpModel')
model = FilteredModel(parent)
for col, header in enumerate(self.ipHeaders):
logging.info('Adding column %s' % str(header))
model.setHeaderData(col, Qt.Horizontal, header)
return model
def initSplash(self):
self.splash = QSplashScreen(QPixmap(appPath + 'splash.png'), Qt.WindowStaysOnTopHint)
self.splash.show()
QTimer.singleShot(SPLASH_TIMEOUT, lambda: self.splash.close())
def initTimers(self):
logging.debug('MainWindow->initTimers')
self.timerCheck = QTimer()
self.timerCheck.timeout.connect(self.onTimerCheck)
def loadConfig(self):
'''Try to load settings or create/overwrite config file'''
logging.info('MainWindow->loadConfig')
try:
with open(self.configPath, 'r') as file:
data = json.load(file)
file.close()
self.config.update(data)
except Exception as e:
logging.info('Could Not Load Settings File:', e)
self.saveConfig()
def onClearResults(self):
'''Clear scan results and stop scan
'''
self.stopScan()
self.clearIpListItems()
def onFilterCheckBox(self, state):
# if self.
self.saveConfig()
def onMenubar(self, action):
text = action.text()
logging.info('MainWindow->onMenubar->{}'.format(text))
if text == 'About':
self.showAbout()
elif text == 'All':
self.clearScanHistory()
elif text == 'Exit':
self.close()
elif text == 'Scan Range':
self.clearIpListItems()
elif text == 'Check For Updates':
self.checkForUpdates()
elif text == 'Custom Scan':
self.clearIpListItems()
elif text == 'Settings':
self.showSettings()
elif text == 'Start Range Scan':
self.onScan()
elif text == 'Start Custom Scan':
self.onScanCustom()
elif text == 'Stop Scan':
self.stopScan()
elif text == 'Submit Issue':
self.showSubmitIssue()
def onResultsFilter(self, event):
'''This function is invoked whenever a scan result filtering
option has been changed
'''
logging.info('MainWindow->onResultsFilter')
if self.isScanFiltered:
self.ipList.setModel(self.ipModelFilter)
else:
self.ipList.setModel(self.ipModel)
def onScan(self, event=None):
'''Scan range'''
logging.info('MainWindow->onScan')
if self.isScanning is True:
self.stopScan()
return
self.prepareScan()
start = self.startIp.currentText()
end = self.endIp.currentText()
if not start or not end:
logging.info('Invalid IP range defined. Start and/or end range empty.')
self.stopScan()
return
self.updateScanHistory()
ipRange = start + '-' + end
self.parseIpthread = functions.ParseIpRange(self, ipRange)
def onScanCheckBox(self, label, state):
logging.info('MainWindow->onScanCheckBox {0}, {1}'.format(label, state))
self.config['scanConfig'][label] = state
if label == 'MAC Address' and not state:
self.scanConfig['Manufacturer'].setChecked(False)
elif label == 'Manufacturer' and state:
self.scanConfig['MAC Address'].setChecked(True)
def onScanCustom(self):
logging.info('MainWindow->onScanCustom')
if self.isScanning is True:
self.stopScan()
return
self.prepareScan()
stringIp = self.stringIp.currentText()
if not stringIp:
self.stopScan()
return
self.updateScanHistory()
stringIp = stringIp.split(',')
for ipRange in stringIp:
self.parseIpthread = functions.ParseIpRange(self, ipRange)
def onTimerCheck(self):
'''Check if we have received any scan results'''
logging.debug('MainWindow->onTimerCheck')
logging.debug('_hostnameCheck: {0}'.format(self._hostnameCheck))
msg = 'Scanning: Addresses Pinged = {0}/{1}, '.format(self.addressResultsCount, self.ipModel.rowCount())
msg += 'Checking Hostname(s) = {0}'.format(len(self._hostnameCheck))
if self.addressResultsCount == self.ipModel.rowCount() and not self._hostnameCheck:
self.setStatusBar('Finished ' + msg)
self.stopScan()
return
self.setStatusBar(msg)
rm = []
for address, thread in self._hostnameCheckThreads.items():
thread.timeout -= TIMER_CHECK_MS
if thread.timeout < 0:
rm.append(address)
for addr in rm:
try:
self._hostnameCheck[addr].terminate()
except Exception as e:
logging.debug('MainWindow->onTimerCheck: %s' % e)
del self._hostnameCheck[addr]
del self._hostnameCheckThreads[addr]
if len(self._hostnameCheckThreads.keys()) > MAX_HOSTNAME_CHECKS:
return
elif self._hostnameCheck:
for address, thread in self._hostnameCheck.items():
if address in self._hostnameCheckThreads:
continue
self._hostnameCheckThreads[address] = thread
self._hostnameCheckThreads[address].start()
return
def prepareScan(self):
self.isScanning = True
self.setStatusBar('Scanning ...')
self.setScanIcons(start=False)
self.clearIpListItems()
def restoreConfigState(self):
'''Restore application state from config'''
logging.info('Menubar->Help->restoreConfigState')
self.restoreScanHistory()
try:
w, h = self.config['size']
w, h = int(w), int(h)
self.resize(w, h)
except Exception as e:
logging.debug('restoreConfigState Exception: %s' % e)
def restoreScanHistory(self):
'''Clears and adds the previous scans
'''
self.startIp.clear()
self.endIp.clear()
self.startIp.addItems(self.config['ipStartHistory'])
self.endIp.addItems(self.config['ipEndHistory'])
if self.config['ipStartHistory'] == []:
self.startIp.addItem('192.168.0.0')
if self.config['ipEndHistory'] == []:
self.endIp.addItem('192.168.0.255')
self.stringIp.clear()
self.stringIp.addItems(self.config['customScanHistory'])
if self.config['customScanHistory'] == []:
self.stringIp.addItem('192.168.0.1-255')
def saveConfig(self):
logging.info('Menubar->Help->saveConfig')
try:
self.config['scanConfig']['hostnameTimeout'] = self.spinHostTimeout.value()
self.config['filter']['showAliveOnly'] = self.checkBoxAlive.isChecked()
self.config['size'] = [self.frameGeometry().width(),
self.frameGeometry().height()]
for label in ['Hostname', 'MAC Address', 'Manufacturer']:
self.config['scanConfig'][label] = self.scanConfig[label].isChecked()
except Exception as e:
logging.debug(e)
try:
with open(self.configPath, 'w') as file:
json.dump(self.config, file, sort_keys=True, indent=2)
except PermissionError:
logging.info('PermissionError: you do not permission to save config')
logging.debug(self.config)
def setScanIcons(self, start=True):
if start:
icon = START_ICON
else:
icon = STOP_ICON
self.btnScan.setIcon(QIcon(icon))
self.btnCustomScan.setIcon(QIcon(icon))
def setStatusBar(self, message, timeout=0):
logging.debug('MainWindow->setStatusBar')
self.statusBar().showMessage(message, timeout)
def showAbout(self):
'''Show the About wndow'''
logging.info('Menubar->Help->showAbout')
AboutDialog(self)
def showSettings(self):
'''Show the About wndow'''
logging.info('Menubar->Settings->showPreferences')
SettingsDialog(self, config=self.config)
def sendScanParams(self):
# we cannot get Manufacturer if user disables MAC
params = self.scanParams
if params['MAC Address'] == 0:
params['Manufacturer'] = 0
self.signalScanParams.emit(params)
def startScan(self, index, address):
self.sendScanParams()
self.signalAddPing.emit({'index': index, 'address': address})
self.startTimerCheck()
def startTimerCheck(self):
logging.info('MainWindow->startTimerCheck')
self.timerCheck.start(TIMER_CHECK_MS)
def stopHostnameChecks(self):
for t in self._hostnameCheckThreads.values():
t.terminate()
def stopParseIpThread(self):
if self.parseIpthread:
self.parseIpthread.terminate()
self.parseIpthread = None
def stopPingThread(self):
self.signalStopScanning.emit()
def stopTimerCheck(self):
self.timerCheck.stop()
def stopScan(self):
logging.info('MainWindow->stopScan')
self.setStatusBar('Scan Finished: Addresses Checked = {0}'.format(self.addressResultsCount))
self.isScanning = False
self.addressResultsCount = 0
self.stopTimerCheck()
self.stopPingThread()
self.stopParseIpThread()
self.stopHostnameChecks()
self.cleanScan()
def updateFilteredResults(self):
'''Refreshes scan results
'''
pass
def updateScanHistory(self):
'''Save scan history to config'''
logging.info('MainWindow->updateScanHistory')
if not self.config.get('rememberScanHistory', None):
# self.clearScanHistory()
return
for cbox, dictKey in [(self.startIp, 'ipStartHistory'),
(self.endIp, 'ipEndHistory'),
(self.stringIp, 'customScanHistory')]:
items = [cbox.itemText(x) for x in range(cbox.count())]
value = cbox.currentText()
if value in items:
index = items.index(value)
del items[index]
items.insert(0, value)
cbox.clear()
for item in items:
cbox.addItem(item)
items = items[:10]
self.config[dictKey] = items
self.saveConfig()
def updateUI(self):
logging.info('MainWindow->updateUI')
self.ipList = self.ui.ipList
self.ipModel = self.createIpModel(self.ipList)
self.ipList.setModel(self.ipModel)
self.ipModelFilter = self.createFilteredIpModel(self.ipList)
self.ipModelFilter.setSourceModel(self.ipModel)
self.ipList.setModel(self.ipModelFilter)
self.startIp = self.ui.startIp
self.endIp = self.ui.endIp
self.btnScan = self.ui.btnScan
self.btnScan.setIcon(QIcon(START_ICON))
self.btnScan.setIconSize(QSize(48, 32))
self.stringIp = self.ui.stringIp
self.btnCustomScan = self.ui.btnCustomScan
self.btnCustomScan.setIcon(QIcon(START_ICON))
self.btnCustomScan.setIconSize(QSize(48, 32))
self.btnClearIpList = self.ui.btnClearIpList
self.btnClearIpList.setIcon(QIcon(CLEAR_ICON))
self.btnClearIpList.setIconSize(QSize(32, 32))
self.spinHostTimeout = self.ui.spinHostTimeout
self.spinHostTimeout.setValue(int(self.config['scanConfig']['hostnameTimeout']))
self.spinHostTimeout.valueChanged.connect(self.saveConfig)
self.scanConfig = {}
self.scanConfig['Hostname'] = self.ui.checkBoxHostname
self.scanConfig['MAC Address'] = self.ui.checkBoxMac
self.scanConfig['Manufacturer'] = self.ui.checkBoxManufacturer
for label in ['Hostname', 'MAC Address', 'Manufacturer']:
self.scanConfig[label].setChecked(self.config['scanConfig'][label])
self.scanConfig[label].toggled.connect(partial(self.onScanCheckBox, label))
self.checkBoxAlive = self.ui.checkBoxAlive
self.checkBoxAlive.setChecked(self.config['filter']['showAliveOnly'])
self.checkBoxAlive.toggled.connect(self.onFilterCheckBox)
def process_sys_args():
res = {}
for arg in sys.argv[1:]:
if '=' not in arg:
continue
key, value = arg.split('=')[:2]
res[key.lower()] = value.lower()
return res
def set_logging_level():
# Logging Configuration
try:
v = LOG_LEVELS[SYS_ARGS['--verbose']]
logging.basicConfig(level=v)
except KeyError:
pass
def main():
SYS_ARGS.update(process_sys_args())
set_logging_level()
app = QApplication(sys.argv)
MainWindow()
sys.exit(app.exec_())
try:
file = open('.devmode.txt', 'r')
file.close()
DEVMODE = True
except Exception:
DEVMODE = False
if __name__ == '__main__':
if not DEVMODE:
main()
else:
print('DEVMODE')
from subprocess import call
print([os.path.join(os.path.dirname(__file__), 'forms', 'generate_pyui.pyw')])
logging.basicConfig(level=logging.DEBUG)
call([sys.executable, os.path.join(os.path.dirname(__file__), 'forms', 'generate_pyui.pyw')])
os.chdir('..')
call([sys.executable, os.path.join(os.path.dirname(__file__), '..', 'setup.py'), 'test'])
os.chdir('zippyipscanner')
main() | zippy-ip-scanner | /zippy-ip-scanner-1.1.0.tar.gz/zippy-ip-scanner-1.1.0/zippyipscanner/zippyipscanner.py | zippyipscanner.py |
import time
import mathfunctions as mf
import logging
import json
import os
import re
import urllib.request
import socket
import subprocess
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSignal, pyqtSlot
def on_windows():
return os.name == "nt"
def startup_info():
"""Configure subprocess to hide the console window"""
if on_windows():
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE
return info
return None
def valid_ip4(address):
"""
Is a valid 4-byte address? If not, try to return the
next best valid address
Some leniency allowed on the first byte (8 LSB's). Every
other byte must be 0 - 255.
"""
logging.debug("functions->valid_ip4 (address=%s)" % address)
if not isinstance(address, list):
return False
if len(address) == 3:
address.append(0)
elif len(address) != 4:
return False
result = [0, 0, 0, 0]
try:
for n, x in enumerate(address):
if x > 255 and n == 3:
result[n] = 255
elif x > 255 or x < 0:
return False
else:
result[n] = x
except ValueError:
return False
return result
class ParseIpRange(QtCore.QThread):
signalScanIp = pyqtSignal(dict)
def __init__(self, parent, spec):
super(ParseIpRange, self).__init__()
self.parent = parent
self.spec = spec
self.signalScanIp.connect(self.parent.slotScanIp)
self.start()
def run(self):
self.parseIpRange(self.spec)
def parseIpRange(self, spec):
"""Is spec string a range a IP addresses?"""
logging.debug("functions->parseIpRange")
addresses = []
try:
ipStart, ipEnd = spec.split("-")[:2]
# Check start IP
ipStart = [int(x) for x in ipStart.split(".")]
start = valid_ip4(ipStart)
if start is False:
return
# Check end IP
ipEnd = [int(x) for x in ipEnd.split(".")]
if len(ipEnd) == 1:
ipEnd = start[:3] + ipEnd
end = valid_ip4(ipEnd)
if end is False:
return
if start == end:
ip = ".".join([str(x) for x in start])
self.signalScanIp.emit({"IP Address": ip})
return addresses
startDec = mf.byte_list_to_decimal(start)
endDec = mf.byte_list_to_decimal(end) + 1
if endDec < startDec:
startDec, endDec = endDec, startDec
logging.debug("functions->parseIpRange addresses=%s" % str((startDec, endDec)))
for _ in range(startDec, endDec):
temp = mf.decimal_to_byte_list(startDec, retbytes=4)
ip = ".".join([str(x) for x in temp])
self.signalScanIp.emit({"IP Address": ip})
startDec += 1
time.sleep(0.05)
logging.debug("functions->parseIpRange addresses=%s" % addresses)
except Exception as e:
logging.debug("functions->parseIpRange: %s" % e)
return
def startupInfo():
"""Configure subprocess to hide the console window"""
if on_windows():
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE
return info
return None
class LookupHostname(QtCore.QThread):
signalHostnameResult = pyqtSignal(dict)
def __init__(self, parent, address, timeout):
super(LookupHostname, self).__init__()
self.parent = parent
self.timeout = timeout * 1000
self.address = address
if self.parent:
self.signalHostnameResult.connect(self.parent.slotHostnameResult)
def run(self):
hostname = "n/a"
try:
hostname = socket.gethostbyaddr(self.address)[0]
except socket.herror:
pass
result = {"address": self.address, "hostname": hostname}
if not self.parent:
return result
self.signalHostnameResult.emit(result)
def LookupMacAddress(address):
"""
Finds the MAC Addresses using ARP
NOTE: This finds mac addresses only within the subnet.
It doesn't fetch mac addresses for routed network ips.
"""
if on_windows():
arp_cmd = ['arp', '-a']
else:
arp_cmd = ['arp', '-n']
info = startup_info()
pid = subprocess.Popen(arp_cmd + [address],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE, startupinfo=info)
out = pid.communicate()[0]
macRe = re.compile(r'(([a-f\d]{1,2}[:-]){5}[a-f\d]{1,2})')
macFound = macRe.search(out.decode('utf-8'))
if macFound:
mac = macFound.group(0).replace('-', ':')
else:
mac = "n/a"
logging.debug("address: %s, mac: %s" % (address, mac))
return mac
def LookupManufacturers(mac):
"""Request to macvendors.co for manufacturer name"""
macUrl = 'http://macvendors.co/api/{0}'.format(mac)
req = urllib.request.Request(macUrl, headers={'User-Agent': 'Mozilla/5.0'})
try:
result = urllib.request.urlopen(req).read()
result = result.decode("utf-8")
except Exception as e:
logging.debug("LookupManufacturers Exception: {0}".format(e))
return ""
logging.debug("LookupManufacturers:Result: %s" % result)
# logging.debug("request URL: %s" % r.text)
result = json.loads(result)["result"]
try:
mfn = result["company"]
return mfn
except Exception as e:
return ""
class PingAddress(QtCore.QThread):
signalScanResult = pyqtSignal(dict)
signalDebug = pyqtSignal(str)
def __init__(self, parent, scanParams={}):
super(PingAddress, self).__init__()
self.parent = parent
self.addresses = []
self.scanParams = scanParams
if self.parent:
self.signalScanResult.connect(self.parent.slotScanResult)
self.signalDebug.connect(self.parent.slotDebug)
self.start()
@pyqtSlot(dict)
def slotAddPing(self, item):
index = item["index"]
address = item["address"]
self.addresses.append((index, address))
@pyqtSlot(dict)
def slotScanParams(self, params):
self.scanParams = params
@pyqtSlot()
def slotStopScanning(self):
self.addresses = []
@property
def checkMac(self):
return self.scanParams["MAC Address"] is True
@property
def checkManufacturer(self):
return self.scanParams["Manufacturer"] is True
def extractMS(self, output):
try:
msStart = output.index("Average = ")
ms = output[msStart + len("Average = "):].strip("\r\n")
except ValueError:
msStart = output.index("time=")
msEnd = output.index(" ms")
ms = output[msStart + len("time="):msEnd]
return ms
def extractTTL(self, output):
try:
ttlStart = output.index("TTL=")
ttlEnd = output.index("\r\n\r\nPing statistics")
ttl = output[ttlStart + len("TTL="):ttlEnd]
except ValueError:
ttlStart = output.index("ttl=")
ttlEnd = output.index(" time=")
ttl = output[ttlStart + len("ttl="):ttlEnd]
return ttl
def gotResponse(self, output):
if on_windows():
return "Reply from" in output
else:
return "ttl=" in output
def outputResult(self, output):
"""Return result of output"""
self.signalDebug.emit(output)
result = {}
if self.gotResponse(output):
result["TTL"] = self.extractTTL(output)
result["Ping"] = self.extractMS(output)
return result
def pingCommand(self, address):
if on_windows():
cmd = ['ping', '-n', '1', '-w', '500', address]
else:
cmd = ['ping', '-c', '1', '-w', '1', address]
return cmd
def emitResult(self, result):
self.signalScanResult.emit(result)
def runCommand(self, cmd):
output = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
stdout=subprocess.PIPE, startupinfo=startup_info()).communicate()[0]
output = output.decode('utf-8')
return output
def run(self):
while True:
if not self.addresses:
time.sleep(0.5)
continue
index, address = self.addresses[0]
# For each IP address in the subnet, run the ping command
result = {
"IP Address": address,
"TTL": "",
"Ping": "",
"Manufacturer": "",
"MAC Address": ""
}
address = str(address)
cmd = self.pingCommand(address)
out = self.runCommand(cmd)
result.update(self.outputResult(out))
if result["TTL"]:
if self.checkMac:
result["MAC Address"] = LookupMacAddress(address)
if self.checkManufacturer:
result["Manufacturer"] = LookupManufacturers(result["MAC Address"])
self.emitResult(result)
try:
del self.addresses[0]
except IndexError:
pass | zippy-ip-scanner | /zippy-ip-scanner-1.1.0.tar.gz/zippy-ip-scanner-1.1.0/zippyipscanner/functions.py | functions.py |
# ZIPPY
### The
### ZIppy
### Pipeline
### Prototyping
### sYstem
ZIPPY is a powerful, easy-to-use NGS pipeline prototyping system, with batteries included. ZIPPY helps you create JSON-based pipeline specifications, which it then uses to execute a series of pipeline stages, with no user-written code required.
## With ZIPPY, you can:
- Generate a new pipeline without any coding required
- Auto-generate parameters files from just a list of stages
- Use our ultra-modular system for adding new modules, which can then interface with every other module
- Make a custom pipeline in 10 minutes or less
## ZIPPY includes a variety of modules, including:
- Bcl2Fastq
- BWA
- Picard alignment stats
- RSEM
- MACS
- BAM subsampling
There will be many more to come! (See the full list of modules [here](https://github.com/Illumina/zippy/wiki/Zippy-modules)).
## Limitations:
ZIPPY uses black magic that relies upon the CPython implementation of Python. Currently, only CPython 2.7 is supported. ZIPPY also requires several python modules. To make life easier, an executable version of ZIPPY is available (see the releases page!).
### Running ZIPPY from source
If you would like to run ZIPPY from source, there are a couple of things to note.
- You must use CPython 2.7
- You must install the modules 'commentjson' and 'pyflow' (note: pyflow is not in pypi, but can be found [here](https://github.com/Illumina/pyflow)). You may optionally install the package 'meta' which may improve the coverage of parameters from make_params if you do not have the source of some of your imported modules (e.g., only .pyc files).
- Run the tests file make_params_test.py and see if it's OK!
# Using ZIPPY:
0. Install ZIPPY by using 'pip install --process-dependency-links zippy-pipeline'
1. Make a proto-workflow file.
A proto-workflow is a very simple json file that lists the pipeline stages you want, in the order you want them. Here's a simple proto-workflow that I use for some RNA-seq applications:
```
{
"stages": ["bcl2fastq", "rsem"]
}
```
Yeah, that's really it.
2. Compile the proto-workflow
execute 'python -m zippy.make_params my_proto.json my_params.json'
3. Fill in the blanks and/or connect the dots
Open up my_params.json and fill in all the parameters that are currently blank.
4. Run ZIPPY
To run ZIPPY, execute 'python -m zippy.zippy my_params.json'
**More information is on the git wiki.**
v2.1.3 (01/28/2019)
- Improvements to RNA support (jsnedecor)
v2.1.2 (11/13/2018)
- Improvements to the bwa module (kwu)
- Added stage for copying a folder
v2.1.1 (6/14/2018)
- Improvements to execution in local mode and other minor fixes
v2.1.0 (4/11/2018)
- First public release
- Parameters 2.0. Support for subworkflows, parameter nesting and environments.
- Support for running docker containers through singularity
- Better optional parameters support. You can now create the function define_optionals(self), which returns a map of default values for optional parameters.
- New stages (Nirvana variant annotation, minimap2 aligner, primer dimer detection)
- New unit tests
- Fewer known bugs
v2.0.0 (2/14/2018)
It's here! Release 2.0 inaugurates ZIPPY-as-a-package. You can now pip install ZIPPY, and once you do so, run it as python -m zippy.zippy. Furthermore, you can import zippy from anywhere and use the API. Special thanks to Wilfred Li for this work. As a bonus, we're finally moving to semantic-ish versioning.
- ZIPPY as a package
- API interface should be finalized
- better docker support (can now support docker pull)
- several small bugfixes
- small documentation improvements
v1.9{6} (12/7/2017)
- Provisional ZIPPY API (function names are interfaces not final)
- Removed several external dependencies
- Parameter detection now defaults to the inspect module, instead of the meta module (i.e., we avoid decompilation when possible)
- Support for running locally instead of on SGE
- Memory/core requirements can now be set both per-stage and globally
- New stages (allowing you to delete intermediate outputs, to convert a bam to a fastq, and to downsample in style with a bloom filter)
- DataRunner improvements: can now load sample list from a samplesheet, and can now manually map file names to zippy types
- Better support for modules in external files (make_params now supports them fully)
- Yet fewer bugs! Or at least... different bugs.
v1.99999 (8/30/17)
- Support for external modules (Runners defined in external code)
- Lots of workflow improvements (argument passing for nearly everything, new bcl2fastq and BWA workflows)
- New workflows (DNA/RNA QC, edger and Salmon)
- New help system (run 'python zippy.py --help')
v1.9999 (5/1/17)
- Unit tests
- Wildcards in the parameters files
- Merge stages
- Support for optional parameters
v1.999 (2/16/17)
- Arbitrary stage chaining
- More stages
- Fewer bugs
v1.99
First end-to-end version of ZIPPY
## License
Copyright 2018 Illumina
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/README.md | README.md |
from __future__ import print_function
from .modular_runner import *
from .make_params import case_insensitive_list_match, ParamFinder, walk_all_methods
def run_help(arg):
print('Welcome to the ZIPPY help system.')
if arg is None:
print('ZIPPY is a powerful, easy-to-use NGS pipeline prototyping system, with batteries included.')
print('This help system can be used to learn more about the various modules included with ZIPPY')
print(' ')
print('To see a list of all modules, use "python zippy.py --help all"')
print('To get help for a specific module, use "python zippy.py --help <modulename>"')
print(' ')
print('ZIPPY command line arguments:')
print(' ')
print('zippy.py workflow [--defaults defaults_file]')
print('workflow\tThe ZIPPY workflow json file.')
print('--defaults\tDEFAULTS\tFile with default parameter values (in json format)\n\t\t(default: defaults.json)')
print('--run_local\tIf set, we will run things on the local node, rather than attempt to use SGE.')
elif arg == 'all':
ignore_set = set(['ModularRunner', 'WorkflowRunner'])
print('All built-in ZIPPY modules:')
print(' ')
print('\n'.join(sorted([x for x in globals().keys() if 'Runner' in x and x not in ignore_set])))
else:
if 'Runner' not in arg:
arg = case_insensitive_list_match('{}Runner'.format(arg), globals().keys())
module = globals()[arg]
print(module)
print(module.__doc__)
print("\tParameters for {}:".format(arg))
pf = ParamFinder()
pf.current_class = arg
walk_all_methods(pf, module)
pf.uniqueify()
for param in pf.params_found:
if param.param[0] == arg:
if param.is_optional:
print("\t\t{}\t(optional)".format(param.param[1]))
else:
print("\t\t{}".format(param.param[1]))
if __name__ == '__main__':
main() | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/modular_helper.py | modular_helper.py |
from __future__ import print_function
import re
import json
import copy
import sys
import subprocess
import imp
import os
import types
from functools import partial
from pyflow import WorkflowRunner
from .modular_runner import *
from .modular_helper import run_help
from .params import get_params, save_params_as_json
from .make_params import case_insensitive_list_match
def docker_task_reformat(params, current_stage_setup, command):
'''
Pulls docker information from the json file and wraps the command appropriately.
'''
stage_params = getattr(params, current_stage_setup)
if hasattr(stage_params, 'use_docker'):
docker_config = getattr(params.docker,stage_params.use_docker)
mount_points = []
for m in docker_config.mount_points:
mount_points.append('{prefix} {mount_dir}'.format(
prefix=_get_docker_mount_prefix(docker_config), mount_dir=m))
if getattr(docker_config, 'intercept_mounts', False):
(from_path,to_path) = m.split(':')
command = re.sub(r"(\s+)"+from_path, r'\1'+to_path, command)
command = re.sub("^"+from_path, to_path, command)
mount_points = " ".join(mount_points)
if getattr(docker_config, 'pull', True):
load_command = _get_docker_pull_command(docker_config)
else:
load_command = _get_docker_load_command(docker_config)
command = _get_docker_run_command(docker_config, mount_points, command)
command = load_command+" ; "+command
return command
def _get_docker_mount_prefix(docker_config):
if docker_config.engine == 'singularity':
return '-B'
else:
return '-v'
def _get_docker_load_command(docker_config):
if docker_config.engine == 'singularity':
raise NotImplementedError('must use "pull" mode with singularity. Set "pull" to true in the config.')
else:
return "cat {} | docker load".format(docker_config.image_file_path)
def _get_docker_pull_command(docker_config):
if docker_config.engine == 'singularity':
return 'singularity pull docker://{}'.format(docker_config.image_file_path)
else:
return 'docker pull {}'.format(docker_config.image_file_path)
def _get_docker_run_command(docker_config, mount_points, command):
if docker_config.engine == 'singularity':
return 'singularity exec {mount_points} docker://{docker_image} {command}'.format(
mount_points=mount_points, command=command, docker_image=docker_config.image)
else:
if hasattr(docker_config, 'uid'):
uid = docker_config.uid
else:
uid = subprocess.check_output('id -u', shell=True).strip()
return 'docker run --rm {mount_points} --user={uid} --entrypoint=/bin/bash {docker_image} -c "{command}"'.format(
mount_points=mount_points, command=command, docker_image=docker_config.image, uid=uid)
def subworkflow_addTask(current_stage_setup, params, self, label, command=None, **kwargs):
'''
Used to monkey patch pyflow's subworkflows, so that we can inject docker wrappers into them.
Very similar to the version used for the main workflow, but we have to hardcode current_stage_setup
and params using partial functions, to fix the context for the subworkflow.
'''
if current_stage_setup is not None and command is not None:
command = docker_task_reformat(params, current_stage_setup, command)
self.flowLog(command)
return WorkflowRunner.addTask(self, label, command=command, **kwargs)
class ModularMain(WorkflowRunner):
"""
ZIPPY, the modular pipeline execution system.
"""
def __init__(self, input_params, from_dict=False):
self.modules_loaded = 0
if from_dict: #initiate from api
self.params = input_params
else: #initiate from command line
if not os.path.exists(input_params.defaults):
print("Warning: Defaults file {} is not found.".format(input_params.defaults))
self.params = get_params(input_params.workflow)
else:
self.params = get_params(input_params.workflow, input_params.defaults)
self.stage_dict = {} # map from identifier to stage
for x in getattr(self.params, 'imports', []):
self.load_external_modules(x)
def addWorkflowTask(self, label, workflowRunnerInstance, dependencies=None):
'''
We inject a docker-aware addTask function into subworkflows.
'''
workflowRunnerInstance.addTask = types.MethodType(partial(subworkflow_addTask, self.current_stage_setup, self.params), workflowRunnerInstance)
return WorkflowRunner.addWorkflowTask(self, label, workflowRunnerInstance, dependencies=dependencies)
def addTask(self, label, command=None, **kwargs):
'''
We wrap pyflow's addTask function to inject docker commands when applicable.
self.current_stage_setup is set in run_stage, and is switched as each stage adds its tasks to the DAG.
'''
if self.current_stage_setup is not None and command is not None:
command = docker_task_reformat(self.params, self.current_stage_setup, command)
self.flowLog(command)
return WorkflowRunner.addTask(self, label, command=command, **kwargs)
def run_stage(self, stage, previous_stage):
'''
So this is some crazy stuff. What this does is allow us to name classes as strings
and then instantiate them as workflow tasks. Each workflow task is self contained, and takes as
input its previous stage, which knows where its outputs will be per-sample. Thus, so long
as the input/output formats line up, stages can be arbitrarily chained.
@return the newly instantiated stage
TODO: use __import__ to allow the importation of arbitrary dependencies.
'''
print(stage)
class_name = case_insensitive_list_match('{}Runner'.format(stage.stage), globals().keys())
print (class_name, stage, previous_stage)
try:
stage_out = globals()[class_name](stage.identifier, self.params, previous_stage)
except KeyError:
raise KeyError("Your workflow stage {} is not found. If it is defined in a custom file, make sure that file is imported in your params file. If it is built-in, make sure you are spelling it correctly!".format(stage.stage))
self.current_stage_setup = stage.identifier
stage_out.setup_workflow(self)
self.stage_dict[stage.identifier] = stage_out
self.current_stage_setup = None
return stage_out
def load_external_modules(self, module_path):
modules_to_add = {}
m = imp.load_source('user_module_import_{}'.format(self.modules_loaded), module_path)
self.modules_loaded += 1
for k in vars(m).keys():
if 'Runner' in k:
modules_to_add[k] = vars(m)[k]
globals().update(modules_to_add)
def workflow(self):
'''
For each stage, we add its workflow, passing along its explicit dependencies, if it has any. If it does not,
we assume it depends on the previous stage run.
'''
previous_stage = None
for stage in self.params.stages:
print("Adding stage {}".format(stage.identifier))
if hasattr(stage, 'previous_stage'):
if isinstance(stage.previous_stage, list):
previous_stages = [self.stage_dict[x] for x in stage.previous_stage]
previous_stage = self.run_stage(stage, previous_stages)
elif isinstance(stage.previous_stage, str):
previous_stage = self.run_stage(stage, [self.stage_dict[stage.previous_stage]])
elif isinstance(stage.previous_stage, unicode):
previous_stage = self.run_stage(stage, [self.stage_dict[str(stage.previous_stage)]])
else:
raise TypeError('Previous stage for {} is neither list or string'.format(stage.identifier))
else:
previous_stage = self.run_stage(stage, [previous_stage])
def run_zippy(self, mode='sge', mail_to=None, sge_arg_list=None, pyflow_dir=None):
"""
Runs the workflow. Returns 0 upon successful completion, 1 otherwise.
Args:
mail_to = e-mail address error information will be sent to
sge_arg_list = any SGE parameters to override pyflow's default qsub arguments.
pyflow_dir = overrides the default pyflow directory location (which is the scratch_path parameter by default)
"""
# pyflow.WorkflowRunner's run function by default already returns 0/1 for success/fail
if not pyflow_dir:
pyflow_dir = self.params.scratch_path
if mode == 'local':
if not hasattr(self.params, 'max_cores') or not hasattr(self.params, 'max_memory'):
raise IOError('In local mode, must specify max_cores and max_memory for the entire system.')
retval = self.run(mode=mode, dataDirRoot=pyflow_dir, retryMax=0, mailTo=mail_to, nCores=self.params.max_cores, memMb=self.params.max_memory)
else:
retval = self.run(mode=mode, dataDirRoot=pyflow_dir, retryMax=0, mailTo=mail_to, schedulerArgList=sge_arg_list)
return retval
def build_zippy(params_dictionary):
"""
Experimental! Call ZIPPY from python, specifying a params dictionary instead of going through makeparams. Returns a zippy object,
which can then be run using the call x.api_run_zippy()
"""
return ModularMain(params_dictionary, from_dict=True)
def load_params(fname, defaults_fname=None):
"""
Loads a valid zippy parameters file or template file from disk. Represents the file as a native python object (c.f., the python json module)
"""
if defaults_fname is not None:
return get_params(fname)
return get_params(fname, defaults_fname)
def save_params(params, fname):
"""
Writes a python object (structured as json) to a file. Used to write files which can then by run using 'python zippy.py your_file.json'
"""
save_params_as_json(copy.deepcopy(params), fname)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(usage='ZIPPY will run your workflow compiled by make_params and filled out by YOU! Run "python zippy.py --help" for more.', formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
parser.add_argument('workflow', help='The ZIPPY workflow json file.', nargs='?')
parser.add_argument('--defaults', default='defaults.json', help='File with default parameter values (in json format)')
parser.add_argument('--email', default=None, help='If specified, you will be emailed here upon job completion')
parser.add_argument('--run_local', dest='run_local', action='store_true', help='Setting this flag will run things on the local node, rather than attempt to use SGE.')
parser.add_argument('--help', dest='help', action='store_true', help='Our help system!')
parser.set_defaults(help=False)
parser.set_defaults(run_local=False)
input_params = parser.parse_args()
if input_params.help or input_params.workflow is None:
run_help(input_params.workflow)
if not input_params.help and input_params.workflow is not None:
print(parser.get_help())
else:
wflow = ModularMain(input_params)
if input_params.run_local:
mode = 'local'
else:
mode = 'sge'
retval = wflow.run_zippy(mode=mode, mail_to=input_params.email)
sys.exit(retval) | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/zippy.py | zippy.py |
import os.path
import math
from pyflow import WorkflowRunner
class BWAWorkflow(WorkflowRunner):
def __init__(self, output_dir,
bwa_exec, samtools_exec, genome_fa, cores, mem,
fastq, sample='', args=''):
self.output_dir = output_dir
self.bwa_exec = bwa_exec
self.samtools_exec = samtools_exec
self.genome_fa = genome_fa
self.cores = cores
self.mem = mem
self.fastq = fastq
self.sample = sample
self.args = args
def workflow(self):
# Create the output directory and create a dummy samplesheet
cmd = "mkdir -p {}".format(self.output_dir)
self.addTask(label="make_out_dir", command=cmd, isForceLocal=True)
out_bam = os.path.join(self.output_dir, "out.bam")
# from fastq:
if len(self.fastq) == 2:
fastq = " ".join(self.fastq)
elif len(self.fastq) == 1:
fastq = self.fastq
else:
raise("More than two FASTQs passed to bwamem!")
if self.args != "":
self.args=" "+self.args
else:
self.args = " -M -R \'@RG\\tID:1\\tLB:{0}\\tPL:ILLUMINA\\tSM:{0}\'".format(self.sample)
# Figure out the number of cores we can use for alignment and for bam compression
total_threads = self.cores * 2 # At least 2
addtl_compression_threads = max(int(0.1 * total_threads), 1) # At a minimum, allocate one extra thread for bam compression
bwa_threads = total_threads # Since BWA's output is thread-dependent, we don't decrement here in order to avoid surprises
assert bwa_threads >= 1
cmd = "%s mem" % self.bwa_exec \
+ " -t %i" % (bwa_threads) \
+ self.args \
+ " %s %s" % (self.genome_fa, fastq) \
+ " | %s view -@ %i -1 -o %s -" % (self.samtools_exec, addtl_compression_threads, out_bam)
self.flowLog(cmd)
self.addTask(label="bwamem", command=cmd, nCores=self.cores,
memMb=self.mem, dependencies="make_out_dir")
# Sort BAM
out_sorted_bam = os.path.join(self.output_dir, "out.sorted.bam")
out_temp = os.path.join(self.output_dir, "tmp")
# Calculate resources for sort
sort_threads = self.cores * 2
mem_per_thread = int(math.floor(float(self.mem) / sort_threads * 0.75)) # Per thread, underallocate to allow some overhead
cmd = self.samtools_exec \
+ " sort %s" % out_bam \
+ " -O bam" \
+ " -o " + out_sorted_bam \
+ " -T " + out_temp \
+ " -@ %i" % sort_threads
self.addTask(label="sort_bam", command=cmd, nCores=self.cores, memMb=self.mem, dependencies="bwamem")
# Clean up the unsorted BAM
cmd = "rm {}".format(out_bam)
self.addTask(label="del_unsorted_bam", command=cmd, dependencies="sort_bam")
if __name__ == "__main__":
pass | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/bwa.py | bwa.py |
import os
import re
import random
import string
import subprocess
from collections import defaultdict
from pyflow import WorkflowRunner
char_set = string.ascii_uppercase + string.ascii_lowercase + string.digits
def find_fastq_files(fastq_dir, rm_undetermined=False, no_crawl=False):
'''
@author: jtoung
'''
fastq_files = {}
if no_crawl:
find = subprocess.Popen(['find', '-L', fastq_dir, '-maxdepth', '1', '-name', '*.fastq.gz'], stdout=subprocess.PIPE)
else:
find = subprocess.Popen(['find', '-L', fastq_dir, '-name', '*.fastq.gz'], stdout=subprocess.PIPE)
fastq_regex = re.compile("^(.*)_(S[0-9]+)_([L0-9\-]+)?_?(R[1|2])_001\.fastq\.gz$")
for fastq_file in find.stdout:
fastq_file = fastq_file.rstrip('\n').split()[0]
fastq_file_basename = os.path.basename(fastq_file)
if fastq_regex.match(fastq_file_basename):
sample_name = fastq_regex.match(fastq_file_basename).group(1)
sample_id = fastq_regex.match(fastq_file_basename).group(2)
lane = fastq_regex.match(fastq_file_basename).group(3)
read = fastq_regex.match(fastq_file_basename).group(4)
if sample_name == "Undetermined":
continue
if not lane:
lane = 'None'
if lane not in fastq_files:
fastq_files[lane] = {}
sample = (sample_id, sample_name)
if sample not in fastq_files[lane]:
fastq_files[lane][sample] = {}
if read in fastq_files[lane][sample]:
raise Exception('already observed fastq file for lane %s, sample_id %s, sample_name %s, read %read in fastq_dir %s' % (lane, sample_id, sample_name, read, fastq_dir))
fastq_files[lane][sample][read] = fastq_file
return fastq_files
class starFlow(WorkflowRunner):
"""
Pyflow workflow to call the STAR aligner. We follow file formatting guidelines from the isaac workflow
from bioxutils.
"""
def __init__(self, star_path, star_index, fastq_dir, out_dir, max_job_cores=8):
self.star_path = star_path
self.star_index = star_index
self.fastq_dir = fastq_dir
self.out_dir = out_dir
self.max_job_cores = max_job_cores
def workflow(self):
if not os.path.exists(self.out_dir):
os.makedirs(self.out_dir)
project_name = 'autogen_project'
fastq_files = find_fastq_files(self.fastq_dir, rm_undetermined=True)
mv_fastq_tasks = []
fastq_cleanup_cmds = []
sample_id_TO_sample_name = {}
fastq_by_sample_1 = defaultdict(list)
fastq_by_sample_2 = defaultdict(list)
for (lane, sample_data) in fastq_files.iteritems():
for (sample, reads) in sample_data.iteritems():
self.flowLog(reads.keys())
fastq_by_sample_1[sample].append(reads['R1'])
try:
fastq_by_sample_2[sample].append(reads['R2'])
except KeyError:
no_r2 = True
for sample in fastq_by_sample_1.keys():
(sample_id, sample_name) = sample
sample_path = os.path.join(self.out_dir, '_'.join(sample))
if not os.path.exists(sample_path):
os.makedirs(sample_path)
# STAR alignment
if no_r2:
read_files_string = ','.join(fastq_by_sample_1[sample])
else:
read_files_string = ','.join(fastq_by_sample_1[sample])+" "+','.join(fastq_by_sample_2[sample])
self.star_command = "{star_path} --genomeDir {star_index} --readFilesIn {read_files_string} --runThreadN {max_job_cores} --outFileNamePrefix {out_dir} --outTmpDir {tmp_dir} --readFilesCommand zcat --outSAMtype BAM SortedByCoordinate --outSAMunmapped Within".format(
star_path=self.star_path, star_index=self.star_index,
read_files_string=read_files_string, max_job_cores=self.max_job_cores,
out_dir=sample_path+"/", tmp_dir = os.path.join(self.out_dir, 'tmp'+str(sample_id)))
self.flowLog(self.star_command)
star_task = self.addTask("star"+str(sample_id), self.star_command, nCores=self.max_job_cores, memMb=40000, dependencies=mv_fastq_tasks)
# cleanup
self.addTask("delete_tmp"+str(sample_id), "rm -r {tmp_dir}".format(tmp_dir=os.path.join(self.out_dir, 'tmp'+str(sample_id))), dependencies=star_task)
rename_task = self.addTask("rename_star"+str(sample_id), "mv {path}/Aligned.sortedByCoord.out.bam {path}/{sample_id}_{sample_name}.raw.bam".format(path=sample_path, sample_id=sample_id, sample_name=sample_name), dependencies=star_task)
# build bai
self.addTask("bai"+str(sample_id), "samtools index {path}/{sample_id}_{sample_name}.raw.bam".format(path=sample_path, sample_id=sample_id, sample_name=sample_name), dependencies=rename_task)
class SingleStarFlow(WorkflowRunner):
"""
Pyflow workflow to call the STAR aligner. We follow file formatting guidelines from the isaac workflow
from bioxutils.
"""
def __init__(self, star_path, star_index, sample, fastqs, out_dir, max_job_cores=8, tmp_path='', command_args=''):
self.star_path = star_path
self.star_index = star_index
self.sample = sample
self.fastqs = fastqs
self.out_dir = out_dir
self.max_job_cores = max_job_cores
if tmp_path !='':
self.tmp_path = tmp_path
else:
self.tmp_path = os.path.join(self.out_dir, 'tmp'+self.sample)
self.tmp_path+=''.join(random.choice(char_set) for _ in range(4))
self.command_args = command_args
def workflow(self):
if not os.path.exists(self.out_dir):
os.makedirs(self.out_dir)
pre_out_prefix = os.path.join(self.out_dir, self.sample)
fastq_files = self.fastqs
fastq_cleanup_cmds = []
fastq_by_sample_1 = [x for x in fastq_files if '_R1_' in x]
fastq_by_sample_2 = [x for x in fastq_files if '_R2_' in x]
if len(fastq_by_sample_2) > 0:
read_files_string = ','.join(fastq_by_sample_1)+" "+','.join(fastq_by_sample_2)
else:
read_files_string = ','.join(fastq_by_sample_1)
self.star_command = "{star_path} --genomeDir {star_index} --readFilesIn {read_files_string} --runThreadN {max_job_cores} --outFileNamePrefix {out_dir} --outTmpDir {tmp_dir} --readFilesCommand zcat --outSAMunmapped Within".format(
star_path=self.star_path, star_index=self.star_index,
read_files_string=read_files_string, max_job_cores=self.max_job_cores,
out_dir=pre_out_prefix, tmp_dir = self.tmp_path)
if self.command_args != "":
self.star_command+=" "+self.command_args
if not '--outSAMtype' in self.star_command.split(' '):
self.flowLog("Missing --outSAMtype param. Output will default to SAM type.", 2)
self.flowLog(self.star_command)
star_task = self.addTask("star", self.star_command, nCores=self.max_job_cores, memMb=100*1024, dependencies=None)
#self.addTask("delete_tmp", "rm -r {tmp_dir}".format(tmp_dir=os.path.join(self.out_dir, 'tmp'+self.sample)), dependencies=star_task)
output_bam_file = pre_out_prefix + 'Aligned.sortedByCoord.out.bam'
make_index = True
if re.search('--outSAMtype\s+.?BAM.?\s+.?Unsorted.?', self.star_command):
output_bam_file = pre_out_prefix + 'Aligned.out.bam'
make_index = False
rename_task = self.addTask("rename_star"+str(self.sample), "mv {output_bam_file} {path}/{sample}.raw.bam".format(output_bam_file=output_bam_file, path=self.out_dir, sample=self.sample), dependencies=star_task)
# build bai
if make_index:
self.addTask("bai", "samtools index {path}/{sample}.raw.bam".format(path=self.out_dir, sample=self.sample), dependencies=rename_task)
if __name__ == '__main__':
wflow = STARFlow()
retval = wflow.run(mode='sge')
sys.exit(retval) | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/star.py | star.py |
import os
import random
import subprocess
import csv
def parse_rsem(f_name):
'''
Returns a map from gene name to a list with one item, the expected count.
'''
rsem_map = {}
with open(f_name, 'rb') as f:
c = csv.reader(f, delimiter='\t')
c.next()
for line in c:
gene = line[0]
rsem_map[gene] = [float(line[4])]
return rsem_map
def add_to_data_grid(data_grid, sample_map):
if data_grid is None:
data_grid = sample_map
else:
for k in sample_map.keys():
try:
data_grid[k].extend(sample_map[k])
except KeyError:
continue
return data_grid
def write_data_grid(data_grid, key_ordering, temp_folder):
#we write out every gene that has the
random_path_suffix = str(random.randint(0,100000))
data_grid_path = os.path.join(temp_folder, 'datagrid'+random_path_suffix+'.csv')
print 'DGP: {}'.format(data_grid_path)
with open(data_grid_path, 'wb') as f:
c = csv.writer(f)
c.writerow(['Symbol']+key_ordering)
for symbol in data_grid.keys():
if len(data_grid[symbol]) == len(key_ordering):
c.writerow([symbol]+data_grid[symbol])
else:
print len(data_grid[s])
return data_grid_path
def run_edger(params):
data_grid = None
key_ordering = []
for (group_index, samples) in enumerate([params.group1, params.group2]):
for sample in samples:
sample_map = parse_rsem(sample)
data_grid = add_to_data_grid(data_grid, sample_map)
key_ordering.append(os.path.basename(sample))
data_grid_path = write_data_grid(data_grid, key_ordering, params.temp_folder)
subprocess.call('{r_path} edger.r {data_grid_path} {group1_len} {group2_len} {out_file} {temp_path}'.format(
data_grid_path=data_grid_path,
group1_len=len(params.group1),
group2_len=len(params.group2),
out_file=params.out_file,
r_path=params.r_path,
temp_path=params.temp_folder), shell=True)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--group1', nargs='+')
parser.add_argument('--group2', nargs='+')
parser.add_argument('--temp_folder')
parser.add_argument('--out_file')
parser.add_argument('--r_path')
params = parser.parse_args()
run_edger(params) | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/run_edger.py | run_edger.py |
import argparse
import os
import random
import pybloomfilter
import pysam
import time
import multiprocessing
import shutil
BF_PROB = 0.0001
MAX_ITERS = 10 # Maximum times we'll loop through a bam
def partition(lst, n):
"""Given a list, partition it into n chunks of approximately equal size"""
# https://stackoverflow.com/questions/2659900/python-slicing-a-list-into-n-nearly-equal-length-partitions
return [lst[i::n] for i in xrange(n)]
class allReadNamesProcess(multiprocessing.Process):
"""
Outputs all read names from given chromosomes and writes to a centralized queue
This is meant for the non-downsampling branch of this script.
"""
def __init__(self, bamfile, chromosome_list, outqueue):
multiprocessing.Process.__init__(self)
self.out_queue = outqueue
self.chromosomes = chromosome_list
self.bam = bamfile
def run(self):
"""
Walks through each chromosome, outputting every single readname
"""
for chromosome in self.chromosomes:
with pysam.AlignmentFile(self.bam, 'rb') as alignment:
for read in alignment.fetch(chromosome):
self.out_queue.put(read.query_name)
class sampleReadNamesProcess(multiprocessing.Process):
"""
Sample read names from the given chromosomes and writes them to a centralized queue
"""
def __init__(self, bamfile, perChromSingleEndReads, perChromUniqueReadnamesTarget, outQueue):
multiprocessing.Process.__init__(self)
self.bam = bamfile
# The dictionary keys in the perChrom things should be the same
assert isinstance(perChromSingleEndReads, dict)
assert isinstance(perChromUniqueReadnamesTarget, dict)
for key in perChromSingleEndReads.keys():
assert key in perChromUniqueReadnamesTarget
self.chromosomes = perChromSingleEndReads.keys()
self.perChromSingleEndReads = perChromSingleEndReads
self.perChromReadnamesTarget = perChromUniqueReadnamesTarget
# assert isinstance(outQueue, multiprocessing.Queue)
self.outQueue = outQueue
def run(self):
"""
Walk through this thread's assigned chromosomes, getting readnames for each.
"""
for chromosome in self.chromosomes:
# Sanity checks
assert chromosome in self.perChromSingleEndReads
assert chromosome in self.perChromReadnamesTarget
# Initialize values for this chromosome's sampling
targetReadnamesCount = self.perChromReadnamesTarget[chromosome]
numSingleEndReads = self.perChromSingleEndReads[chromosome]
if numSingleEndReads > 0:
acceptedProbability = float(targetReadnamesCount) / float(numSingleEndReads)
acceptedReadnames = pybloomfilter.BloomFilter(targetReadnamesCount * 2, BF_PROB)
else:
print("No reads in current chromosome %s, skipping" % chromosome)
continue
numIters = 0
keepGoing = True
with pysam.AlignmentFile(self.bam, 'rb') as alignment:
while keepGoing and numIters < MAX_ITERS:
for read in alignment.fetch(region=chromosome):
read_name, flag = read.query_name, int(read.flag)
# If read is supplementary/seconadary, skip it
if (flag & 2048) or (flag & 256):
continue
if random.random() <= acceptedProbability:
# False output from add indicates that item was not already in bloom filter
# So we tehn add it to the output queue
if not acceptedReadnames.add(read.query_name):
self.outQueue.put(read_name)
if len(acceptedReadnames) >= targetReadnamesCount:
keepGoing = False
break
numIters += 1
# Write to stdout
print("Processed %s %s: (readnames selected/readnames desired) (%i/%i)" % (os.path.basename(self.bam), chromosome, len(acceptedReadnames), targetReadnamesCount))
class readnameConsumer(multiprocessing.Process):
"""
Consumes readnames and writes the output bam.
"""
def __init__(self, totalTargetReadnameCount, bamfileIn, bamfileOut, readnameQueue):
multiprocessing.Process.__init__(self)
# assert isinstance(readnameQueue, multiprocessing.Queue)
assert isinstance(totalTargetReadnameCount, int)
self.bamIn = bamfileIn
self.bamOut = bamfileOut
self.queue = readnameQueue
self.readnameCount = totalTargetReadnameCount
def run(self):
# Combine the readnames from each of the child processes into one single bloom filter
masterBF = pybloomfilter.BloomFilter(self.readnameCount * 2, BF_PROB)
counter = 0
while True:
readname = self.queue.get()
if readname is None:
break
masterBF.add(readname)
counter += 1
print("Finished sampling readnames. Writing output bam...")
# Finished getting all the reads, now write the output bam
with pysam.AlignmentFile(self.bamIn, 'rb') as bamSource:
with pysam.AlignmentFile(self.bamOut, 'wb', template=bamSource) as bamOutput:
for read in bamSource:
if read.query_name in masterBF:
bamOutput.write(read)
print("Finished downsampling %s to %s. Outputted (selected/desired) %i/%i readnames." % (self.bamIn, self.bamOut, counter, self.readnameCount))
def getTotalReads(bam, chromosomes):
totalReads = 0
perChromCount = {}
for chromosome in chromosomes:
#filter supplementary and secondary alignments
c = int(pysam.view('-F', '2304', '-c', bam, chromosome))
perChromCount[chromosome] = c
totalReads += c
return totalReads, perChromCount
def downsample(inputBam, outputBam, targetNumUniqueReadnames, unmapped, numThreads=4):
# Sanity checks
if not os.path.isfile(inputBam):
raise RuntimeError("Cannot find %s" % inputBam)
indexFile = inputBam + ".bai"
if not os.path.isfile(indexFile):
raise RuntimeError("Input bam %s must be sorted" % inputBam)
# Get the chromosomes included in this bam
with pysam.AlignmentFile(inputBam, 'rb') as bIn:
chromosomes = bIn.references
if unmapped: chromosomes += ('*',)
totalSingleEndReads, perChromSingleEndReads = getTotalReads(inputBam, chromosomes)
assert totalSingleEndReads != -1
# Skip downsampling if we already have fewer than downsampled amount
if targetNumUniqueReadnames * 2 >= totalSingleEndReads:
print("%s does not need downsampling. Copying old bam to new path." % inputBam)
# Copy the file over
needs_downsampling = False
else:
print("Starting downsampling for %s" % inputBam)
needs_downsampling = True
# Split the chromosomes into per-thread lists of chromosomes
chromosomeChunks = partition(chromosomes, numThreads)
readnamesQueue = multiprocessing.Queue()
# Initialize the readnames consumer
consumerProcess = readnameConsumer(targetNumUniqueReadnames, inputBam, outputBam, readnamesQueue)
consumerProcess.start()
producerProcesses = []
for chunk in chromosomeChunks:
if needs_downsampling:
perThreadSingleEndReads = {}
for chrom in chunk:
perThreadSingleEndReads[chrom] = perChromSingleEndReads[chrom]
perThreadTargetReadnames = {}
for chrom in chunk:
perThreadTargetReadnames[chrom] = int(float(perChromSingleEndReads[chrom]) / float(totalSingleEndReads) * float(targetNumUniqueReadnames))
chunk_process = sampleReadNamesProcess(inputBam, perThreadSingleEndReads, perThreadTargetReadnames, readnamesQueue)
else:
chunk_process = allReadNamesProcess(inputBam, chunk, readnamesQueue)
chunk_process.start()
producerProcesses.append(chunk_process)
# Wait for all the per-chrom threads to terminate
for proc in producerProcesses:
proc.join()
# Signal to the writer that we're done
readnamesQueue.put(None)
# Wait for the writer to finish
consumerProcess.join()
def buildParser():
parser = argparse.ArgumentParser(
description = __doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("--bam", type=str, required=True,
help="Bam file to downsample")
parser.add_argument("--downsampled_pairs", type=int, required=True,
help="Number of unique pairs to downsample to")
parser.add_argument("--output", type=str, required=True,
help="Path to output bam file")
parser.add_argument("--threads", type=int, default=4,
help="Number of threads to use")
parser.add_argument("--unmapped", action='store_true', help="If set, include unmapped reads")
return parser
if __name__ == "__main__":
# main()
parser = buildParser()
args = parser.parse_args()
downsample(args.bam, args.output, args.downsampled_pairs, args.unmapped, args.threads) | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/downsampling_bloom.py | downsampling_bloom.py |
import cProfile
import os
import gzip
import csv
import time
from collections import defaultdict
from itertools import combinations
from pybloomfilter import BloomFilter
#from pybloom import ScalableBloomFilter, BloomFilter #pybloom used cryptographic hashes in a bloom filter. This is a bad idea.
import numpy
class BloomKmerFinder():
"""
Finds all kmers that show up more than a certain number of times. Can choose to ignore dimerized reads
or do only dimerized reads. Useful for finding common kmers in unmapped reads. We use a bloom filter
to do this, so it is very fast, but requires a few GB of ram to keep the filter in memory.
"""
def __init__(self, params, k, exclude_monomers=False, exclude_dimers=False):
self.params = params
self.k = k #kmer for global matching
self.primer_k = 15 #kmer for primer matching
self.exclude_monomers = exclude_monomers
self.exclude_dimers = exclude_dimers
self.run_dimer_detector = False
self.bloom = BloomFilter(1e9, 0.01, None)
self.count_map = defaultdict(int)
if exclude_monomers or exclude_dimers:
self.run_dimer_detector = True
self.reads_read = 0 # how many lines we've looked at
self.dimer_reads_read = 0 # how many lines we've looked at with at least 2 primers
self.monomer_reads_read = 0 # how many lines we've looked at with exactly 1 primer
self.out_stats_file = open(os.path.join(self.params.output_dir,'count_stats'), 'w')
def reverse_complement(self, seq):
rev_map = {'A':'T','C':'G','G':'C','T':'A', 'N':'N'}
new_seq = ''.join([rev_map[x] for x in seq]) #sub letters
new_seq = new_seq[::-1] # reverse it
return new_seq
def parse_probe_list(self):
"""
Creates probe map, which is a map of probe names to sequence.
"""
probe_map = {}
with open(self.params.probe_list, 'r') as f:
c = csv.reader(f, delimiter="\t")
for line in c:
probe_map[line[0]] = line[1].upper()
return probe_map
def build_kmer_map(self, probe_map, k):
"""
Builds a map from kmer to probenames that have this kmer.
Also does reverse complements.
"""
kmer_map = defaultdict(set)
for (probe, seq) in probe_map.iteritems():
seq_rc = self.reverse_complement(seq)
for i in range(0, len(seq)-k):
kmer_map[seq[i:i+k]].add(probe)
kmer_map[seq_rc[i:i+k]].add(probe+"rc")
return kmer_map
def run_matcher(self, input_file, kmer_map):
"""
Goes through a fastq, and registers all the kmers in it.
"""
if input_file is None: # we don't require the input files... one of them can be undefined
return
debug = 0
with open(input_file, 'r') as f:
counter = 0 # 0: header 1: sequence 2: junk 3: quality
for line in f:
if counter == 0:
read_name = line.strip()
if counter == 1:
line = line.upper()
if self.run_dimer_detector:
probe_matches = self.find_matches(line.strip(), kmer_map)
if len(probe_matches) > 1 and not self.exclude_dimers:
self.dimer_reads_read += 1
self.register_kmers(line.strip())
elif len(probe_matches) == 1 and not self.exclude_monomers:
self.monomer_reads_read += 1
self.register_kmers(line.strip())
elif len(probe_matches) == 0:
debug += 1
self.register_kmers(line.strip())
else:
self.register_kmers(line.strip())
self.reads_read += 1
counter += 1
counter = counter % 4
print '{} dimer: {}'.format(input_file, self.dimer_reads_read)
print '{} monomer: {}'.format(input_file, self.monomer_reads_read)
print '{} none: {}'.format(input_file, debug)
print '{} total: {}'.format(input_file, self.reads_read)
def register_kmers(self, read):
"""
Adds the read and its reverse complement to our bloom filter, and if we have seen it before,
adds it to the count map. The idea is that the bloom filter can approximately determine
if we've seen something before or not, and to the count map are added all kmers that the bloom
filter reports that we've seen before.
"""
for i in range(0, len(read)-self.k):
seq = read[i:i+self.k]
seq_rc = self.reverse_complement(seq)
if self.bloom.add(seq):
self.count_map[seq]+=1
if self.bloom.add(seq_rc):
self.count_map[seq_rc]+=1
def find_matches(self, line, kmer_map):
"""
For a single read, reports all found primers
"""
in_primer = None
matches = []
for i in range(0, len(line)-self.primer_k):
sub_seq = line[i:i+self.primer_k]
if in_primer is None: #we are not currently in a primer.
if len(kmer_map[sub_seq]) == 1: # If we see a uniquely mappable kmer, we enter a primer.
(in_primer,) = kmer_map[sub_seq]
matches.append(in_primer)
else: # Otherwise, we continue
continue
else: # we are in the middle of seeing a primer sequence
if in_primer in kmer_map[sub_seq]: # we see this primer again, and are thus still reading it. Continue.
continue
elif len(kmer_map[sub_seq]) == 1: # We no longer see our current primer, but this sequence is mappable to another primer. We are now in a different primer.
(in_primer,) = kmer_map[sub_seq]
matches.append(in_primer)
else: # We aren't in our current primer, and aren't uniquely in a different primer.
in_primer = None
return matches
def output_stats(self, kmer_map):
"""
We print the top-two unique maximal strings, and then a sorted list of all kmers that appear
at least twice in our reads.
"""
sorted_map = sorted(self.count_map.items(), key=lambda x: -x[1])
first_string = self.extend(sorted_map[0][0], self.count_map)
for (kmer, count) in sorted_map[1:]:
if kmer not in first_string and self.reverse_complement(kmer) not in first_string:
second_string = self.extend(kmer, self.count_map)
second_score = count
break
self.out_stats_file.write("{}\t{}\n".format(sorted_map[0][1], first_string))
self.out_stats_file.write("{}\t{}\n".format(second_score, second_string))
for (kmer, count) in sorted_map:
probe_matches = self.find_matches(kmer, kmer_map)
if len(probe_matches) == 0:
self.out_stats_file.write("{}\t{}\n".format(kmer, count))
else:
self.out_stats_file.write("{}\t{}\t{}\n".format(probe_matches, kmer, count))
def extend(self, seed, kmer_map):
"""
Given a kmer, we greedily extend it in both directions by looking for kmers that differ by 1 on either side. We add
the new kmer if its count is at least half of our peak kmer.
"""
final_string = [seed]
value = kmer_map[seed]
forward_extend = True
current_seed = seed
while forward_extend:
extender = current_seed[1:]
new_kmers = [extender+x for x in 'ACGT']
new_scores = [kmer_map[x] for x in new_kmers]
if numpy.max(new_scores)>value*0.5: #we extend
new_kmer = new_kmers[numpy.argmax(new_scores)]
if new_kmer == current_seed: #we hit a pathological (recursive) read
forward_extend = False
final_string.append(new_kmer[-1])
current_seed = new_kmer
else:
forward_extend = False
reverse_extend = True
current_seed = seed
while reverse_extend:
extender = current_seed[:-1]
new_kmers = [x+extender for x in 'ACGT']
new_scores = [kmer_map[x] for x in new_kmers]
if numpy.max(new_scores)>value*0.5: #we extend
new_kmer = new_kmers[numpy.argmax(new_scores)]
if new_kmer == current_seed: #we hit a pathological read
reverse_extend = False
final_string = [new_kmer[0]]+final_string
current_seed = new_kmer
else:
reverse_extend = False
return ''.join(final_string)
def run(self):
"""
Main execution function for kmer finder
"""
if self.run_dimer_detector:
probe_map = self.parse_probe_list()
kmer_map = self.build_kmer_map(probe_map, self.primer_k) #kmer-map for dimer detection
else:
kmer_map = defaultdict(set)
for input_file in [self.params.input_file1, self.params.input_file2]:
self.run_matcher(input_file, kmer_map)
self.output_stats(kmer_map)
self.out_stats_file.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--probe_list', type=str, help="Needed if you want to filter by dimers. tsv with 2 columns: (probe_name, sequence). If you are looking for adapters or other short sequences, they should be added to the probe list.")
parser.add_argument('--kmer', type=int, default=30, help="How big a fragment size to count")
parser.add_argument('--input_file1', help="A fastq file with reads to analyze")
parser.add_argument('--input_file2', help="Another fastq file (Optional)")
parser.add_argument('--output_dir')
parser.add_argument('--exclude_monomers', dest='exclude_monomers', action='store_true', help="Whether we exclude primer monomers from kmer counting")
parser.set_defaults(exclude_monomers=False)
parser.add_argument('--exclude_dimers', dest='exclude_dimers', action='store_true', help="Whether we exclude primer dimers from kmer counting")
parser.set_defaults(exclude_dimers=False)
params = parser.parse_args()
bloomy = BloomKmerFinder(params, params.kmer, params.exclude_monomers, params.exclude_dimers)
start = time.time()
bloomy.run()
print time.time()-start | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/bloom_kmer_finder.py | bloom_kmer_finder.py |
import re
from collections import defaultdict
valid_sections = set(('Header', 'Reads', 'Settings', 'Data'))
def check_valid_samplename(name):
if "_R1_" in name or "_R2_" in name or name.endswith("_R1") or name.endswith("_R2"):
raise RuntimeError('Sample name {} contains _R1_ or endswith _R1. This interferes with how paired-end reads are formatted. Please rename your samples'.format(name))
def check_valid_section(section):
if section not in valid_sections:
raise Exception('invalid section %s; valid sections are %s' % (section, " ".join(valid_sections)))
class SampleSheet(object):
def __init__(self, sample_sheet, fix_dup_sample_names=False):
self.unique_sample_name_map = {}
if not sample_sheet:
raise AttributeError('samplesheet is required for SampleSheet')
self.sample_sheet = sample_sheet
self.fix_dup_sample_names = fix_dup_sample_names
self._parse_sample_sheet(self.sample_sheet)
self._check_names()
def _check_names(self):
'''
Ensures that names are unique (it either fails, or fixes them
if fix_dup_sample_names is true. Also ensures that names fit in
our sample name guidelines (do not end with _R1/_R2 and do not
contain _R1_/_R2_)
'''
name_to_ids = defaultdict(set)
ids_to_names = defaultdict(set)
for sample_id in self.get_sample_ids():
sample_lines = self.get_samples_for_id(sample_id)
check_valid_samplename(sample_id)
for line in sample_lines:
name = line.get("Sample_Name")
name_to_ids[name].add(sample_id)
ids_to_names[sample_id].add(name)
check_valid_samplename(name)
for (identifier, name_set) in ids_to_names.iteritems():
if len(name_set) > 1:
raise IOError('Sample ID {} has multiple sample names. Sample name and sample ID must be unique'.format(identifier))
for (name, id_set) in name_to_ids.iteritems():
if len(id_set) > 1:
if self.fix_dup_sample_names:
for sample_id in id_set:
self.uniqueify_sample_names(sample_id)
if name == '':
self.overwrite_sample_name(sample_id)
else:
raise IOError('Sample name {} has multiple sample IDs. Sample name and sample ID must be unique'.format(name))
else:
self.unique_sample_name_map[list(id_set)[0]] = name
def sample_id_to_sample_index(self, sample_id):
sample_indices = 1
samples_seen = set()
for line in self._ss["Data"]:
current_id = line.get("Sample_ID")
if current_id == sample_id:
return sample_indices
else:
if current_id not in samples_seen:
sample_indices += 1
samples_seen.add(current_id)
raise ValueError('Sample id {} not found in samplesheet'.format(sample_id))
def uniqueify_sample_names(self, sample_id):
self.unique_sample_name_map[sample_id] = sample_id
def overwrite_sample_name(self, sample_id):
sample_lines = self.get_samples_for_id(sample_id)
for line in sample_lines:
line.set("Sample_Name", sample_id)
def print_sample_sheet(self, output):
"""prints sample sheet to output"""
fh_out = open(output, 'wb')
for line in self._l:
fh_out.write(",".join(line) + "\n")
fh_out.close()
def _parse_sample_sheet(self, sample_sheet):
"""parse the sample sheet into two objects: _l is a list of each line in the original file; _ss is a dictionary that lets us look up the index of each line conveniently"""
"""first, _ss points to sections Header, Reads, or Settings. the value of these keys are themselves dictionaries whose keys are the first column, and values are the line idx of the original file, which let's us get the corresponding line in _l"""
"""second, _ss points to sections Data, which contains a list of "Data" elements, each of which contain a link to the original sample sheet (self), as well as the line idx of the original file"""
header_regex = re.compile("^\[(.*)\]$")
section_name = None
# _ss is a dictionary that stores keys called "Header", "Reads", or "Settings"
#
self._ss = {}
# _l is a list that of the original file
self._l = []
_data_header = None
_data_i = 1
with open(sample_sheet, 'rb') as f:
for i, line in enumerate(f):
line = line.rstrip('\n\r').split(',')
self._l.append(line)
if len(line) == 1 and line[0] == '': #skip blank lines
continue
if header_regex.match(line[0]):
section_name = header_regex.match(line[0]).group(1)
continue
if not section_name:
raise Exception('could not parse section name in string %s in sample sheet %s' % (line[0], self.sample_sheet))
if section_name not in self._ss:
if section_name in ["Data", "Reads"]:
self._ss[section_name] = []
else:
self._ss[section_name] = {}
if section_name in ["Header", "Settings"]:
(key, value) = (line[0], line[1])
if key in self._ss[section_name]:
raise Exception('key %s observed twice in section %s' % (key, section_name))
self._ss[section_name][key] = i
if section_name in ["Data"]:
if not _data_header:
_data_header = line
else:
self._ss[section_name].append(Data(_data_header, _data_i, self, i))
_data_i += 1
if section_name in ["Reads"]:
self._ss[section_name].append(line)
def get(self, section, attribute=None):
check_valid_section(section)
if section in ["Data",]:
# returns a list of "Data" items
return self._ss[section]
else:
if attribute in self._ss[section]:
i = self.ss_[section][attribute]
return self._l[i][1]
elif attribute is None:
return self._ss[section]
else:
return None
def set(self, section, attribute, new_value):
check_valid_section(section)
if section in ["Data",]:
raise Exception('set method not defined for Data')
if not attribute in self._ss[section]:
raise Exception('%s not found in section %s' % (attribute, section))
i = self._ss[section][attribute]
self._l[i][1] = new_value
def calculate_number_of_lanes(self):
lanes = set()
for d in self._ss["Data"]:
for lane in d.get("Lane").split("+"):
lanes.add(lane)
lanes = sorted([int(lane) for lane in lanes])
return lanes
def get_sample_ids(self):
sample_ids = set()
for line in self._ss["Data"]:
sample_ids.add(line.get("Sample_ID"))
return sample_ids
def get_samples_for_id(self, sample_id):
sample_lines = []
for line in self._ss["Data"]:
if line.get("Sample_ID") == sample_id:
sample_lines.append(line)
return sample_lines
def sample_id_to_sample_name(self, sample_id):
'''
Will return the first sample name associated with this sample id
'''
sample_lines = self.get_samples_for_id(sample_id)
return sample_lines[0].get("Sample_Name")
def is_paired_end(self):
count = 0
for line in self._ss["Reads"]:
if len(line) > 0 and line[0] != '':
count += 1
if count == 2:
return True
if count == 1:
return False
raise ValueError("Reads section of samplesheet is malformed")
class Data(object):
def __init__(self,
data_header,
data_i, # the ith data object (order of this data object relative to other data objects in the spreadsheet)
sample_sheet, # the original sample sheet object
sample_sheet_i # the line number in the original sample sheet
):
for i in ('data_i', 'sample_sheet', 'sample_sheet_i'):
setattr(self, i, locals()[i])
self.data_header_idx = {}
for (i, v) in enumerate(data_header):
if v == '':
continue
if v in self.data_header_idx:
raise Exception('observed Data header %s twice' % v)
self.data_header_idx[v] = i
def __repr__(self):
return str(self.sample_sheet._l[self.sample_sheet_i])
def set(self, attribute, new_value):
# get the line from the original sample sheet
line = self.sample_sheet._l[self.sample_sheet_i]
if attribute not in self.data_header_idx:
raise AttributeError('invalid attribute for Data %s' % attribute)
line[self.data_header_idx[attribute]] = new_value
def get(self, attribute):
# row_idx is another synonym for the ith data object or 'data_i'
if attribute == "row_idx":
return self.data_i
# get the line from the original sample sheet
line = self.sample_sheet._l[self.sample_sheet_i]
if attribute not in self.data_header_idx:
raise AttributeError('invalid attribute for Data %s' % attribute)
return line[self.data_header_idx[attribute]]
def has(self, attribute):
# row_idx is another synonym for the ith data object or 'data_i'
if attribute == "row_idx":
return True
if attribute not in self.data_header_idx:
return False
return True | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/samplesheet.py | samplesheet.py |
import subprocess
import numpy
import csv
import os
import pysam
def star_keep_line(line):
if 'Started job on' in line:
return False
if 'Started mapping on' in line:
return False
if 'Finished on' in line:
return False
if 'Mapping speed' in line:
return False
if '|' in line:
return True
def parse_starlog(fname):
results = []
number_reads = -1
unique_reads = -1
with open(fname, 'r') as f:
for line in f:
line = line.strip()
if star_keep_line(line):
split_line = line.split('|')
split_line = [x.strip() for x in split_line]
if 'Number of input reads' in line:
number_reads = int(split_line[1])
if 'Uniquely mapped reads number' in line:
unique_reads = int(split_line[1])
results.append("\t".join(split_line)) #we swap the | divider with :
return (results, number_reads, unique_reads)
def parse_insert_size(fname):
data = []
results = []
with open(fname, 'rb') as f:
c = csv.reader(f, delimiter='\t')
for line in c:
if 'sameTranscript=No' in line or 'sameChrom=No' in line or 'dist=genomic' in line: #we remove non-traditional transcripts
continue
if int(line[1]) > 1000: #we remove the extreme large insert sizes as not 'real'
continue
data.append(int(line[1]))
results.append('Average insert size\t{}'.format(numpy.mean(data)))
results.append('Standard deviation insert size\t{}'.format(numpy.std(data)))
return results
def get_intron_read_count(params):
subprocess.call("bedtools intersect -a {bam_path} -b {intron_bed} -u -wa -f 0.1 -sorted > {temp_path}.temp.bam".format(bam_path=params.bam_path, intron_bed=params.intron_bed, temp_path=params.temp_path), shell=True)
read_names = set()
samfile = pysam.AlignmentFile("{}.temp.bam".format(params.temp_path), "rb")
for line in samfile:
read_names.add(line.query_name)
samfile.close()
#count = subprocess.check_output("samtools view -c {temp_path}.temp".format(temp_path=params.temp_path), shell=True)
#subprocess.call("rm {temp_path}.temp".format(temp_path=params.temp_path), shell=True)
return len(read_names)
def get_ribosome_read_count(params):
''' deprecated '''
subprocess.call("samtools view {bam_path} -b -L {ribosome_bed} -o {temp_path}.bam".format(bam_path=params.bam_path, ribosome_bed=params.ribosome_bed, temp_path=params.temp_path), shell=True)
read_names = set()
samfile = pysam.AlignmentFile("{}.bam".format(params.temp_path), "rb")
for line in samfile:
read_names.add(line.query_name)
samfile.close()
print "{temp_path}.bam".format(temp_path=params.temp_path)
#subprocess.call("rm {temp_path}.bam".format(temp_path=params.temp_path), shell=True)
return len(read_names)
def get_unique_read_count(bam_path, bed_path, temp_bam_file):
exit_code = subprocess.call("samtools view {bam_path} -b -L {bed_path} -o {temp_bam_file}".format(bam_path=bam_path, bed_path=bed_path, temp_bam_file=temp_bam_file), shell=True)
if exit_code != 0:
raise RuntimeError('Samtools exited with nonzero exit code.')
read_names = set()
samfile = pysam.AlignmentFile(temp_bam_file, "rb")
for line in samfile:
read_names.add(line.query_name)
samfile.close()
subprocess.call("rm {}".format(temp_bam_file), shell=True)
return len(read_names)
def get_dup_count(bam_path):
dup_count = subprocess.check_output("samtools view -c -f 1024 -q 255 {}".format(bam_path), shell=True)
return int(dup_count.strip())/2 #per paired-read
def analyze_rna(params):
results = []
sample_name = os.path.basename(params.output_path)
results.append('Sample\t{}'.format(sample_name))
number_reads = -1
if params.starlog_path is not None:
(star_results, number_reads, unique_reads) = parse_starlog(params.starlog_path)
results.extend(star_results)
if params.ribosome_bed is not None:
#ribosome_read_count = get_ribosome_read_count(params)
ribosome_read_count = get_unique_read_count(params.bam_path, params.ribosome_bed, params.temp_path+'.ribosome.bam')
results.append('Ribosomal reads\t{}'.format(ribosome_read_count))
if number_reads > 0:
results.append('Ribosomal read percentage\t{:.2%}'.format(float(ribosome_read_count)/float(number_reads)))
print results
#if params.intron_bed is not None:
# intron_read_count = get_intron_read_count(params)
# results.append('Intron-overlapping reads\t{}'.format(intron_read_count))
# if number_reads > 0:
# results.append('Intron-overlapping read percentage\t{:.2%}'.format(float(intron_read_count)/float(number_reads))) #2*x because the read count is paired end reads, but our ribosomal count is not.
# print results
if params.manifest_bed is not None:
manifest_read_count = get_unique_read_count(params.bam_path, params.manifest_bed, params.temp_path+'.manifest.bam')
#manifest_read_count = subprocess.check_output("samtools view {bam_path} -c -L {manifest_bed}".format(bam_path=params.bam_path, manifest_bed=params.manifest_bed), shell=True)
results.append('Manifest reads\t{}'.format(manifest_read_count))
if number_reads > 0:
results.append('Manifest read percentage\t{:.2%}'.format(float(manifest_read_count)/float(number_reads))) #2*x because the read count is paired end reads, but our ribosomal count is not.
print results
if params.rseqc_inner_distance is not None:
results.extend(parse_insert_size(params.rseqc_inner_distance))
if params.dup_stats:
dup_count = get_dup_count(params.bam_path)
results.append('Duplicate uniquely mapping reads\t{}'.format(dup_count))
if unique_reads > 0:
results.append('Duplicate read percentage (of all uniquely mapped reads)\t{:.2%}'.format(float(dup_count)/float(number_reads))) #2*x because the read count is paired end reads, but our ribosomal count is not.
with open(params.output_path, 'w') as fout:
print results
fout.write('\n'.join(results))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(usage='', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('bam_path', help='The bam to analyze.')
parser.add_argument('output_path', help='Where to place the stats file.')
parser.add_argument('--ribosome_bed')
parser.add_argument('--intron_bed')
parser.add_argument('--manifest_bed')
parser.add_argument('--temp_path')
parser.add_argument('--rseqc_inner_distance')
parser.add_argument('--starlog_path', help="Star's Final.log.out file.")
parser.add_argument('--dup_stats', dest='dup_stats', action='store_true', help="Whether we generate duplicate statistics")
parser.set_defaults(dup_stats=False)
input_params = parser.parse_args()
analyze_rna(input_params) | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/rna_stats.py | rna_stats.py |
from __future__ import print_function
import copy
import commentjson as json
import inspect
import sys
from .utils import sub_check_wilds
from .modular_runner import ModularRunner
class ObjectDict(object):
'''
It is required that all bound methods of ObjectDict be private (start with _)
Note: need to figure out how to deal with nested function names. Like an if not in dir(this object) or something?
'''
def __init__(self, **kwargs):
self._self_flag = False
for (k,v) in kwargs.iteritems():
setattr(self, k, v)
def _lookup_identifier_doublestack(self):
try:
stack = inspect.stack()
parentframe = stack[2][0]
print(parentframe.f_locals['self'])
if isinstance(parentframe.f_locals['self'], ModularRunner):
return parentframe.f_locals['self'].identifier
else:
return None
except (AttributeError,KeyError):
return None
def _update_from_dict(self, d):
if self._self_flag:
identifier = self._lookup_identifier_doublestack()
if identifier is not None:
stage_params = object.__getattribute__(self, identifier)
stage_params._update_from_dict(d)
self._self_flag = False
else:
for (k,v) in d.iteritems():
if not hasattr(self, k):
setattr(self, k, v)
def __getattribute__(self, attr):
'''
When .self is encountered, a flag (self.self_mode) is set so that the next non-'self' getattribute will be in 'self mode'.
Thus, we first check in the params.self namespace, and then (if not in self mode) look in the broader namespace.
After every parameter lookup, it sets the self_mode flag to false
Downside: lookups to the params object are not threadsafe. This shouldn't be a big issue.
'''
if attr == 'self':
self._self_flag = True
return self
elif attr == 'optional':
return self
elif attr[0] == '_': # no magic for private references
return object.__getattribute__(self, attr)
else:
try:
stack = inspect.stack()
parentframe = stack[1][0]
if isinstance(parentframe.f_locals['self'], ModularRunner):
identifier = parentframe.f_locals['self'].identifier
else:
self._self_flag = False
return object.__getattribute__(self, attr)
except (AttributeError,KeyError): # This handles other failures where the calling frame of reference is not a stage
self._self_flag = False
return object.__getattribute__(self, attr)
stage_params = object.__getattribute__(self, identifier)
try: #check in self.params.self
value = object.__getattribute__(stage_params, attr)
self._self_flag = False
return value
except AttributeError:
if not self._self_flag: # if we have not required self, we can check the top level
self._self_flag = False
return object.__getattribute__(self, attr)
else:
self._self_flag = False
raise AttributeError('Stage level parameter {} not found'.format(attr))
def __repr__(self):
return str(self.__dict__)
def _json_object_hook(d, fname, proto):
"""
Turns the dictionary into a simple object, emulating a Namespace object from argparse.
"""
if not proto and 'stages' in d:
for (i,stage) in enumerate(copy.copy(d['stages'])):
if stage['identifier'] in d:
raise KeyError('Stage identifier {} is the same as a parameter name. This is not allowed.'.format(stage['identifier']))
print(stage)
d[stage['identifier']] = ObjectDict(**stage)
d['stages'][i] = d[stage['identifier']]
if 'docker' in d:
for docker in copy.copy(d['docker']).keys():
d['docker'][docker] = ObjectDict(**d['docker'][docker])
d['docker'] = ObjectDict(**d['docker'])
d['params'] = fname
return ObjectDict(**d)
def merge_defaults(defaults, params):
"""
There's some subtlety to this. Currently, we merge over:
1. All top-level keys
2. Every stage matched by it's .stage
"""
for k in defaults.keys():
if k not in params:
params[k] = defaults[k]
for (i,stage) in enumerate(copy.copy(params['stages'])):
if stage['stage'] not in defaults['stages']:
continue
for (k,v) in defaults['stages'][stage['stage']].iteritems():
if k not in stage:
params['stages'][i][k] = v
return params
def resolve_wildcards(wildcard_map, params):
new_params_map = {}
for (k, v) in params.iteritems():
k = sub_check_wilds(wildcard_map, k)
if isinstance(v, dict):
v = resolve_wildcards(wildcard_map, v)
elif isinstance(v, list):
v = resolve_wildcards_list(wildcard_map, v)
elif isinstance(v, str) or isinstance(v, unicode):
v = sub_check_wilds(wildcard_map, v)
new_params_map[k] = v
return new_params_map
def resolve_wildcards_list(wildcard_map, params_list):
'''
Helper function for resolve wildcards that iterates over a list, not a dict.
'''
new_members = []
for x in params_list:
if isinstance(x, dict):
new_members.append(resolve_wildcards(wildcard_map, x))
elif isinstance(x, list):
new_members.append(resolve_wildcards_list(wildcard_map, x))
else:
new_members.append(sub_check_wilds(wildcard_map, x))
return new_members
def old_get_params(fname, defaults_fname=None, proto=False):
"""
Returns an object with fields defined for every value in the json file. Hardcodes its own file location
to the 'params' entry.
proto: whether this is a prototype params file or not. If it is, then we do not unroll stages (because it is flat)
"""
with open(fname, 'rb') as f:
params = json.load(f)
if 'wildcards' in params:
params = resolve_wildcards(params['wildcards'], params)
if defaults_fname is not None:
with open(defaults_fname, 'rb') as def_f:
default_params = json.load(def_f)
params = merge_defaults(default_params, params)
params = _json_object_hook(params, fname, proto=proto)
return params
def get_params(fname, proto=False):
'''
To build a params object:
0. Turn the json into a python object
1. Resolve wildcards
2. Build dockers
3. Build stages.
3a. Expand subworkflows
3b. Turn stage_dict into an ObjectDict
3c. Update stage_dict and docker_dict from stage environment
4. Build global
4a. Turn d into an ObjectDict
4b. Update global environment
'''
subworkflow_index = 0
with open(fname, 'rb') as f:
d = json.load(f)
if proto:
return ObjectDict(**d)
if 'wildcards' in d:
d = resolve_wildcards(d['wildcards'], d)
if 'docker' in d:
for docker in copy.copy(d['docker']).keys():
d['docker'][docker] = ObjectDict(**d['docker'][docker])
d['docker'] = ObjectDict(**d['docker'])
if 'stages' in d:
stages = copy.deepcopy(d['stages'])
d['stages'] = []
for stage in stages:
if 'subworkflow' in stage:
handle_subworkflow(stage, d, subworkflow_index)
subworkflow_index += 1
elif 'identifier' in stage:
stage_dict = ObjectDict(**stage)
handle_stage(stage_dict, d)
else:
raise ValueError('Stage must either define identifier (and be a stage) or subworkflow (and be a subworkflow)')
d['params'] = fname
d = ObjectDict(**d)
if hasattr(d, 'environment'):
env = get_params(d.environment)
if hasattr(env, 'docker'):
d.docker._update_from_dict(env.docker.__dict__)
d._update_from_dict(env.__dict__)
return d
def handle_stage(stage_dict, d):
'''
Adds a stage to the params workflow representation, and uses the environment
file to fill in any missing parameters (if defined)
'''
if stage_dict.identifier in d:
raise KeyError('Stage identifier {} is the same as a parameter name. This is not allowed.'.format(stage['identifier']))
# set up an alias for the stage at params.stage_identifier.
d[stage_dict.identifier] = stage_dict
d['stages'].append(stage_dict)
if hasattr(stage_dict, 'environment'):
env = get_params(stage_dict.environment)
stage_dict._update_from_dict(getattr(env, stage_dict.identifier).__dict__)
if hasattr(env, 'docker'):
d['docker']._update_from_dict(env.docker.__dict__)
def handle_subworkflow(stage, d, subworkflow_index):
'''
Adds a subworkflow to the params representation by iteratively adding its stages.
'''
subworkflow = get_params(stage['subworkflow'])
subworkflow_feedins = stage['previous_stage'] if 'previous_stage' in stage else {}
subworkflow_identifier = stage['identifier'] if 'identifier' in stage else subworkflow_index
for stage_dict in subworkflow.stages:
# we add the subworkflow identifier to internal previous_stage references
if hasattr(stage_dict, 'previous_stage') and stage_dict.previous_stage !='':
if isinstance(stage_dict.previous_stage, list):
stage_dict.previous_stage = [x+'{}'.format(subworkflow_identifier) for x in stage_dict.previous_stage]
else:
stage_dict.previous_stage+='{}'.format(subworkflow_identifier)
# we add external previous_stages defined in the feedins
if stage_dict.identifier in subworkflow_feedins:
add_feedins_to_previous_stage(stage_dict, subworkflow_feedins[stage_dict.identifier])
# by default, we append the subworkflow identifier to output paths.
if not getattr(stage_dict, 'zippy_do_not_append_identifier_to_paths', False):
if hasattr(stage_dict, 'output_dir'):
stage_dict.output_dir+='{}'.format(subworkflow_identifier)
# now we add the stage to the workflow
stage_dict.identifier+='{}'.format(subworkflow_identifier)
handle_stage(stage_dict, d)
def add_feedins_to_previous_stage(stage_dict, feedins):
'''
We add the new feedins into the dependencies of the curent stage.
'''
if feedins == '': #there's a feedin defined, but it's not an identifier. We can ignore it.
return ''
if not isinstance(feedins, list):
feedins = [feedins]
if isinstance(stage_dict.previous_stage, list): # formerly, there were multiple previous stages
stage_dict.previous_stage.extend(feedins)
elif stage_dict.previous_stage != '': # formerly, there was one previous stage
stage_dict.previous_stage = [stage_dict.previous_stage]+feedins
else: # formerly, there was no prvious stage
stage_dict.previous_stage = feedins
def save_params_as_json(params, fname):
params = rejsonify(params)
for stage in params['stages']: #we delete the duplicate copies of the stages, to match the input json style
del params[stage['identifier']]
with open(fname, 'w') as f:
json.dump(params, f, indent=4)
def rejsonify(params):
'''
Used to convert ObjectDicts to serializable dicts
'''
if isinstance(params, ObjectDict):
to_return = params.__dict__
#strip out private members
to_return = {k:v for (k,v) in to_return.iteritems() if k[0]!='_'}
for (k,v) in copy.copy(to_return).iteritems():
to_return[k] = rejsonify(v)
elif isinstance(params, list):
for (i,v) in enumerate(copy.copy(params)):
params[i] = rejsonify(v)
to_return = params
else:
to_return = params
return to_return | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/params.py | params.py |
import os
import gzip
import csv
from collections import defaultdict
from itertools import combinations
class PrimerDimerMiner():
"""
A primer dimer detector. Looks for kmers that can be uniquely mapped to a primer or its reverse complement,
and reports all reads that have kmers belonging to at least 2 such primers. Note that a primer and its reverse
complement are counted separately. We also report autodimers, defined as non-contiguous kmers that map to the same
primer.
#TODO: we ignore whether reads are paired end; not sure if there's anything smart we want to do there.
#TODO: all matches must be exact. if there's a read error somewhere, we won't catch it, or we might call it an autodimer
# if it results in 15bp matches on each end of the error.
"""
def __init__(self, params):
self.params = params
self.k = self.params.kmer
self.reads_read = 0 # how many lines we've looked at
self.dimer_reads_read = 0 # how many lines we've looked at with at least 2 primers
self.monomer_reads_read = 0 # how many lines we've looked at with exactly 1 primer
self.pairs_map = defaultdict(int) # map from tuple of 2 primers (alphabetical) to dimer count
self.out_reads_file = open(os.path.join(self.params.output_dir,'matched_reads'), 'w')
self.out_pairs_file = open(os.path.join(self.params.output_dir,'pair_stats'), 'w')
self.out_stats_file = open(os.path.join(self.params.output_dir,'run_stats'), 'w')
def reverse_complement(self, seq):
rev_map = {'A':'T','C':'G','G':'C','T':'A'}
new_seq = ''.join([rev_map[x] for x in seq]) #sub letters
new_seq = new_seq[::-1] # reverse it
return new_seq
def parse_probe_list(self):
"""
Creates probe map, which is a map of probe names to sequence.
"""
probe_map = {}
with open(self.params.probe_list, 'r') as f:
c = csv.reader(f, delimiter="\t")
for line in c:
probe_map[line[0]] = line[1].upper()
return probe_map
def build_kmer_map(self, probe_map, k):
"""
Builds a map from kmer to probenames that have this kmer.
Also does reverse complements.
"""
kmer_map = defaultdict(set)
for (probe, seq) in probe_map.iteritems():
seq_rc = self.reverse_complement(seq)
for i in range(0, len(seq)-k):
kmer_map[seq[i:i+k]].add(probe)
kmer_map[seq_rc[i:i+k]].add(probe+"rc")
return kmer_map
def run_matcher_helper(self, f, kmer_map):
counter = 0 # 0: header 1: sequence 2: junk 3: quality
for line in f:
if counter == 0:
read_name = line.strip()
if counter == 1:
line = line.upper()
probe_matches = self.find_matches(line.strip(), kmer_map)
if len(probe_matches) > 1:
self.output_matches(read_name, probe_matches, line.strip())
self.register_pairs(probe_matches)
self.dimer_reads_read += 1
elif len(probe_matches) == 1:
self.monomer_reads_read += 1
self.reads_read += 1
counter += 1
counter = counter % 4
def run_matcher(self, input_file, kmer_map):
"""
Goes through a fastq, and finds all dimerized reads
"""
if input_file is None: # we don't require the input files... one of them can be undefined
return
try:
with gzip.open(input_file, 'r') as f:
self.run_matcher_helper(f, kmer_map)
except IOError: #not a gzip
with open(input_file, 'r') as f:
self.run_matcher_helper(f, kmer_map)
def find_matches(self, line, kmer_map):
"""
For a single read, reports all found primers
"""
in_primer = None
matches = []
for i in range(0, len(line)-self.k):
sub_seq = line[i:i+self.k]
if in_primer is None: #we are not currently in a primer.
if len(kmer_map[sub_seq]) == 1: # If we see a uniquely mappable kmer, we enter a primer.
(in_primer,) = kmer_map[sub_seq]
matches.append(in_primer)
else: # Otherwise, we continue
continue
else: # we are in the middle of seeing a primer sequence
if in_primer in kmer_map[sub_seq]: # we see this primer again, and are thus still reading it. Continue.
continue
elif len(kmer_map[sub_seq]) == 1: # We no longer see our current primer, but this sequence is mappable to another primer. We are now in a different primer.
(in_primer,) = kmer_map[sub_seq]
matches.append(in_primer)
else: # We aren't in our current primer, and aren't uniquely in a different primer.
in_primer = None
return matches
def output_matches(self, read_name, probe_matches, line):
self.out_reads_file.write(read_name+"\n")
self.out_reads_file.write(line+"\n")
self.out_reads_file.write("\t".join(probe_matches)+"\n")
def register_pairs(self, probe_matches):
"""
Increments the occurrence count of all unique dimer pairs found in a line.
"""
seen_pairs = set()
probe_matches = sorted(probe_matches)
for pair in combinations(probe_matches, 2):
if pair not in seen_pairs:
self.pairs_map[pair] += 1
seen_pairs.add(pair)
def output_stats(self):
self.out_pairs_file.write("\t".join(["Primer 1", "Primer 2", "# reads containing both", "% reads containing both"])+"\n")
for (pair, count) in sorted(self.pairs_map.items(), key=lambda x: -x[1]):
self.out_pairs_file.write("\t".join([pair[0], pair[1], str(count), "{:.4%}".format(float(count)/float(self.dimer_reads_read))])+"\n")
self.out_stats_file.write("Number of reads seen: {}".format(self.reads_read)+"\n")
self.out_stats_file.write("Number of reads with dimers: {}, ({:.4%})\n".format(self.dimer_reads_read, float(self.dimer_reads_read)/float(self.reads_read)))
self.out_stats_file.write("Number of reads with exactly 1 primer: {}, ({:.4%})\n".format(self.monomer_reads_read, float(self.monomer_reads_read)/float(self.reads_read)))
def run(self):
"""
Main execution function for PDM
"""
probe_map = self.parse_probe_list()
kmer_map = self.build_kmer_map(probe_map, self.k)
for input_file in [self.params.input_file1, self.params.input_file2]:
self.run_matcher(input_file, kmer_map)
self.output_stats()
self.out_reads_file.close()
self.out_stats_file.close()
self.out_pairs_file.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--probe_list', type=str, help="tsv with 2 columns: (probe_name, sequence). If you are looking for adapters or other short sequences, they should be added to the probe list.")
parser.add_argument('--kmer', type=int, default=15, help="How big a fragment size to require for a match")
parser.add_argument('--input_file1', help="A fastq file with reads to analyze")
parser.add_argument('--input_file2', help="Another fastq file (Optional)")
parser.add_argument('--output_dir')
params = parser.parse_args()
if not os.path.exists(params.output_dir):
os.makedirs(params.output_dir)
pdm = PrimerDimerMiner(params)
pdm.run() | zippy-pipeline | /zippy-pipeline-2.1.3.0.tar.gz/zippy-pipeline-2.1.3.0/zippy/primer_dimer_miner.py | primer_dimer_miner.py |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.