text
stringlengths 3
1.05M
|
|---|
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Lood Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test loodd with different proxy configuration.
Test plan:
- Start loodd's with different proxy configurations
- Use addnode to initiate connections
- Verify that proxies are connected to, and the right connection command is given
- Proxy configurations to test on loodd side:
- `-proxy` (proxy everything)
- `-onion` (proxy just onions)
- `-proxyrandomize` Circuit randomization
- Proxy configurations to test on proxy side,
- support no authentication (other proxy)
- support no authentication + user/pass authentication (Tor)
- proxy on IPv6
- Create various proxies (as threads)
- Create loodds that connect to them
- Manipulate the loodds using addnode (onetry) an observe effects
addnode connect to IPv4
addnode connect to IPv6
addnode connect to onion
addnode connect to generic DNS name
"""
import socket
import os
from test_framework.socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType
from test_framework.test_framework import LoodTestFramework
from test_framework.util import (
PORT_MIN,
PORT_RANGE,
assert_equal,
)
from test_framework.netutil import test_ipv6_local
RANGE_BEGIN = PORT_MIN + 2 * PORT_RANGE # Start after p2p and rpc ports
class ProxyTest(LoodTestFramework):
def set_test_params(self):
self.num_nodes = 4
def setup_nodes(self):
self.have_ipv6 = test_ipv6_local()
# Create two proxies on different ports
# ... one unauthenticated
self.conf1 = Socks5Configuration()
self.conf1.addr = ('127.0.0.1', RANGE_BEGIN + (os.getpid() % 1000))
self.conf1.unauth = True
self.conf1.auth = False
# ... one supporting authenticated and unauthenticated (Tor)
self.conf2 = Socks5Configuration()
self.conf2.addr = ('127.0.0.1', RANGE_BEGIN + 1000 + (os.getpid() % 1000))
self.conf2.unauth = True
self.conf2.auth = True
if self.have_ipv6:
# ... one on IPv6 with similar configuration
self.conf3 = Socks5Configuration()
self.conf3.af = socket.AF_INET6
self.conf3.addr = ('::1', RANGE_BEGIN + 2000 + (os.getpid() % 1000))
self.conf3.unauth = True
self.conf3.auth = True
else:
self.log.warning("Testing without local IPv6 support")
self.serv1 = Socks5Server(self.conf1)
self.serv1.start()
self.serv2 = Socks5Server(self.conf2)
self.serv2.start()
if self.have_ipv6:
self.serv3 = Socks5Server(self.conf3)
self.serv3.start()
# Note: proxies are not used to connect to local nodes
# this is because the proxy to use is based on CService.GetNetwork(), which return NET_UNROUTABLE for localhost
args = [
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'],
['-listen', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'],
['-listen', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'],
[]
]
if self.have_ipv6:
args[3] = ['-listen', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0', '-noonion']
self.add_nodes(self.num_nodes, extra_args=args)
self.start_nodes()
def node_test(self, node, proxies, auth, test_onion=True):
rv = []
# Test: outgoing IPv4 connection through node
node.addnode("15.61.23.23:1234", "onetry")
cmd = proxies[0].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: loodd's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"15.61.23.23")
assert_equal(cmd.port, 1234)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if self.have_ipv6:
# Test: outgoing IPv6 connection through node
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
cmd = proxies[1].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: loodd's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"1233:3432:2434:2343:3234:2345:6546:4534")
assert_equal(cmd.port, 5443)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
if test_onion:
# Test: outgoing onion connection through node
node.addnode("loodostk4e4re.onion:26679", "onetry")
cmd = proxies[2].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"loodostk4e4re.onion")
assert_equal(cmd.port, 26679)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing DNS name connection through node
node.addnode("node.noumenon:26679", "onetry")
cmd = proxies[3].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, b"node.noumenon")
assert_equal(cmd.port, 26679)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
return rv
def run_test(self):
# basic -proxy
self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False)
# -proxy plus -onion
self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False)
# -proxy plus -onion, -proxyrandomize
rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True)
# Check that credentials as used for -proxyrandomize connections are unique
credentials = set((x.username,x.password) for x in rv)
assert_equal(len(credentials), len(rv))
if self.have_ipv6:
# proxy on IPv6 localhost
self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False, False)
def networks_dict(d):
r = {}
for x in d['networks']:
r[x['name']] = x
return r
# test RPC getnetworkinfo
n0 = networks_dict(self.nodes[0].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n0[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n0[net]['proxy_randomize_credentials'], True)
assert_equal(n0['onion']['reachable'], True)
n1 = networks_dict(self.nodes[1].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n1[net]['proxy'], '%s:%i' % (self.conf1.addr))
assert_equal(n1[net]['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n1['onion']['proxy_randomize_credentials'], False)
assert_equal(n1['onion']['reachable'], True)
n2 = networks_dict(self.nodes[2].getnetworkinfo())
for net in ['ipv4','ipv6','onion']:
assert_equal(n2[net]['proxy'], '%s:%i' % (self.conf2.addr))
assert_equal(n2[net]['proxy_randomize_credentials'], True)
assert_equal(n2['onion']['reachable'], True)
if self.have_ipv6:
n3 = networks_dict(self.nodes[3].getnetworkinfo())
for net in ['ipv4','ipv6']:
assert_equal(n3[net]['proxy'], '[%s]:%i' % (self.conf3.addr))
assert_equal(n3[net]['proxy_randomize_credentials'], False)
assert_equal(n3['onion']['reachable'], False)
if __name__ == '__main__':
ProxyTest().main()
|
var mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/assets/js/app.js', 'public/js/app.js');
mix.combine([
'resources/assets/js/mascaraCampos.min.js',
'resources/assets/js/index.js',
'resources/assets/js/mascaraCampos.js',
'resources/assets/js/calculaParcela.js',
'resources/assets/js/plugins.js',
'resources/assets/js/Funcoes.js'
], 'public/js/main.js');
mix.copy('resources/assets/sass/select2.css', 'public/css/select2.css');
mix.copy('resources/assets/js/select2.js', 'public/js/select2.js');
|
import axios from "axios";
export default {
// Gets all events
getEvents: function () {
return axios.get("/api/events");
},
// Gets the event with the given id
getEvent: function (id) {
return axios.get("/api/events/" + id);
},
// Deletes the event with the given id
deleteEvent: function (id) {
return axios.delete("/api/events/" + id);
},
// Saves a event to the database
addEvent: function (eventData) {
return axios.post("/api/events", eventData);
},
addNewUser: function (data) {
return axios.post("/api/user", data)
},
getAllUsers: function () {
return axios.get("/api/users")
},
getAllUsersWithToken: async function (token) {
return axios.get("/api/users", {
headers: {
authorization: `Bearer ${token}`
}
})
},
getUser: function (token) {
return axios.get("/api/user/", {
headers: {
authorization: `Bearer ${token}`
}
})
},
updateUser: function (data, token) {
return axios.post('/api/updateUser/', data, {
headers: {
authorization: `Bearer ${token}`
}
})
},
setUserRole: function (data, token) {
return axios.post('/api/setUserRole/', data, {
headers: {
authorization: `Bearer ${token}`
}
})
},
getUserDegrees: function (token) {
// console.log("getUserDegrees")
return axios.get('/api/getUserDegreesWithUid', {
headers: {
authorization: `Bearer ${token}`
}
})
},
updateDegreeInfo: function (data, token) {
// console.log("updateDegreeInfo: ", data)
return axios.post('/api/updateDegreeInfo/', data, {
headers: {
authorization: `Bearer ${token}`
}
})
},
/**
* payDues - submit payment for dues
* @param {} data
* {memberType,
* memberId}
* @param {*} token
*/
payDues: function (data, token) {
// console.log("payDues")
return axios.post("/api/payDues", data, {
headers: {
authorization: `Bearer ${token}`
}
})
},
getUserPayments: function (token) {
// console.log("getUserPayments")
return axios.get("/api/getUserPayments", {
headers: {
authorization: `Bearer ${token}`
}
})
},
getUserEvents: function (token) {
// console.log("getUserEvents")
return axios.get("/api/getUserEvents", {
headers: {
authorization: `Bearer ${token}`
}
})
},
newEventRSVP: function (newEventRSVP, token){
// console.log("newEventRSVP")
// console.log(newEventRSVP)
return axios.post("/api/newEventRSVP", newEventRSVP, {
headers: {
authorization: `Bearer ${token}`
}
});
},
/**
* makeDonation - Make a donation towards scholarships
* @param {} data
* {donationType,
* memberId}
* @param {*} token
*/
makeDonation: function (data, token) {
// console.log("Make Donation")
return axios.post("/api/makeDonation", data, {
headers: {
authorization: `Bearer ${token}`
}
})
},
/**
* @param {} data object {donationType, memberId}
*/
makeAnonymousDonation: function (data) {
return axios.post("/api/makeAnonymousDonation", data)
},
makePayment: function (data, token=null) {
// console.log('makePayment')
if (data.type.includes("donation") & !!token) {
// console.log("makeDonation")
return this.makeDonation(data, token);
} else if (data.type.includes("donation")) {
// console.log("makeAnonymousDonation")
return this.makeAnonymousDonation(data, token);
} else if (data.categoryId === "membership") {
// console.log("payDues")
return this.payDues(data, token);
}
}
};
|
'use strict';
const SAVE_MODE_MAX = 25;
const SAVE_MODE_OFF_MAX = 32;
const DEFAULT_TEMP = 20;
const MIN_TEMP = 10;
const LOW_USAGE_LIMIT = 18;
const MEDIUM_USAGE_LIMIT = 25;
class Thermostat {
constructor() {
this._temp = DEFAULT_TEMP;
this._MINIMUM_TEMP = MIN_TEMP;
this._maxTemp = SAVE_MODE_MAX;
this._saveStatus = true;
}
increaseTemp() {
if(this._temp === this._maxTemp) {
throw new Error('Cannot exceed max. temperature!');
}
this._temp++;
}
decreaseTemp() {
if(this._temp === this._MINIMUM_TEMP) {
throw new Error('Cannot exceed min. temperature!');
}
this._temp--;
}
saveModeOff() {
this._maxTemp = SAVE_MODE_OFF_MAX;
this._saveStatus = false;
}
saveModeOn() {
this._maxTemp = SAVE_MODE_MAX;
this._saveStatus = true;
}
reset() {
this.saveModeOn();
this._temp = DEFAULT_TEMP;
}
usage() {
if(this._temp < LOW_USAGE_LIMIT) {
return "LOW"
}
else if(this._temp <= MEDIUM_USAGE_LIMIT) {
return "MEDIUM"
}
return "HIGH"
}
}
|
from __future__ import unicode_literals
import logging
from django.utils import six
from django.utils.html import escape, strip_tags
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from djblets.markdown import iter_markdown_lines
from djblets.registries.errors import ItemLookupError
from djblets.registries.registry import ALREADY_REGISTERED, NOT_REGISTERED
from reviewboard.diffviewer.diffutils import get_line_changed_regions
from reviewboard.diffviewer.myersdiff import MyersDiffer
from reviewboard.diffviewer.templatetags.difftags import highlightregion
from reviewboard.registries.registry import Registry, OrderedRegistry
from reviewboard.reviews.markdown_utils import (is_rich_text_default_for_user,
normalize_text_for_edit,
render_markdown)
class FieldSetRegistry(OrderedRegistry):
"""A registry for field sets.
This keeps the fieldsets in the registered order, so iterating through them
will do so in the same order.
"""
lookup_attrs = ('fieldset_id',)
errors = {
ALREADY_REGISTERED: _(
'"%(item)s" is already a registered review request fieldset.'
),
NOT_REGISTERED: _(
'%(attr_value)s is not a registered review request fieldset.'
),
}
def __init__(self):
self._key_order = []
super(FieldSetRegistry, self).__init__()
def register(self, fieldset):
"""Register the fieldset.
This will also register all field classes registered on the fieldset on
the field registry.
Args:
fieldset (type):
The fieldset to register, as a
:py:class:`BaseReviewRequestFieldSet` subclass.
"""
super(FieldSetRegistry, self).register(fieldset)
# Set the field_classes to an empty list by default if it doesn't
# explicitly provide its own, so that entries don't go into
# BaseReviewRequestFieldSet's global list.
if fieldset.field_classes is None:
fieldset.field_classes = []
for field_cls in fieldset.field_classes:
field_registry.register(field_cls)
def unregister(self, fieldset):
"""Unregister the fieldset.
This will unregister all field classes on the fieldset from the field
registry.
Args:
fieldset (type):
The field to remove, as a
:py:class:`BaseReviewRequestFieldSet` subclass.
"""
super(FieldSetRegistry, self).unregister(fieldset)
for field_cls in fieldset.field_classes:
fieldset.remove_field(field_cls)
def get_defaults(self):
"""Return the list of built-in fieldsets.
Returns:
list:
A list of the built-in
:py:class:`~reviewboard.reviews.fields.BaseReviewRequestFieldSet`
subclasses.
"""
from reviewboard.reviews.builtin_fields import builtin_fieldsets
return builtin_fieldsets
class FieldRegistry(Registry):
"""A registry for review request fields."""
lookup_attrs = ['field_id']
errors = {
ALREADY_REGISTERED: _(
'"%(item)s" is already a registered review request field. Field '
'IDs must be unique across all fieldsets.'
),
NOT_REGISTERED: _(
'"%(attr_value)s is not a registered review request fieldset.'
),
}
def populate(self):
# Fields are only ever registered via the FieldSetRegistry, so we
# ensure that it has been populated as well.
fieldset_registry.populate()
fieldset_registry = FieldSetRegistry()
field_registry = FieldRegistry()
class BaseReviewRequestFieldSet(object):
"""Base class for sets of review request fields.
A fieldset stores a list of fields that are rendered on the review
request page. They may contain default fields, and new fields can be
added or removed.
Review Board provides three main fieldsets: "main", "info", and
"reviewers". Others can be added by subclassing and registering
through ``register_review_request_fieldset``.
"""
fieldset_id = None
label = None
show_required = False
field_classes = None
tag_name = None
def __init__(self, review_request_details):
self.review_request_details = review_request_details
@classmethod
def is_empty(cls):
"""Returns whether the fieldset is empty.
A fieldset is empty if there are no field classes registered.
An empty fieldset will not be displayed on the page.
"""
return not cls.field_classes
@classmethod
def add_field(cls, field_cls):
"""Adds a field class to this fieldset.
The field will be rendered inside this fieldset on the page.
A given field class can only be in one fieldset. Its ``field_id``
must be unique.
"""
field_registry.register(field_cls)
cls.field_classes.append(field_cls)
@classmethod
def remove_field(cls, field_cls):
"""Removes a field class from this fieldset.
The field class must have been previously added to this fieldset.
"""
cls.field_classes.remove(field_cls)
try:
field_registry.unregister(field_cls)
except ItemLookupError as e:
logging.error('Failed to unregister unknown review request '
'field "%s"',
field_cls.field_id)
raise e
def __str__(self):
"""Represent the field set as a byte string.
Returns:
bytes:
The field set's ID as a byte string.
"""
if isinstance(self.fieldset_id, six.binary_type):
return self.fieldset_id
return self.fieldset_id.encode('utf-8')
def __unicode__(self):
"""Represent the field set as a unicode string.
Returns:
unicode:
The field set's ID as a unicode string.
"""
if isinstance(self.fieldset_id, six.binary_type):
return self.fieldset_id.decode('utf-8')
return self.fieldset_id
class BaseReviewRequestField(object):
"""Base class for a field on a review request.
A field is responsible for displaying data from a review request,
handling any editing requirements if necessary, recording changes
in the ChangeDescription, and rendering those changes.
Each field must have its own unique ``field_id``. This ID will be used
when looking up or storing the field's value.
It is recommended that fields provided by extensions prefix their
field ID with some sort of identifier for the extension or the vendor.
Creating a new field requires subclassing BaseReviewRequestField and
overriding any fields or functions necessary. Its class must then be
added to a fieldset.
A field will be instantiated with either a ReviewRequest or a
ReviewRequestDraft, depending on what is being edited. This is stored
in ``review_request_details``. Functions should optimistically fetch
values from that, if possible. They can call ``get_review_request()``
on ``review_request_details`` to fetch the actual ReviewRequest.
If the function takes a ``review_request_details`` parameter, it must
use that instead.
"""
field_id = None
label = None
is_editable = False
is_required = False
default_css_classes = set()
change_entry_renders_inline = True
model = None
can_record_change_entry = property(lambda self: self.is_editable)
def __init__(self, review_request_details, request=None):
self.review_request_details = review_request_details
self.request = request
@property
def value(self):
"""Returns the value loaded from the database.
This will fetch the value with the associated ReviewRequest or
ReviewRequestDraft, and then cache it for future lookups.
"""
if not hasattr(self, '_value'):
self._value = self.load_value(self.review_request_details)
return self._value
def has_value_changed(self, old_value, new_value):
"""Returns whether the value has changed.
By default, it performs an inequality check on the values. This
can be overridden to perform more specialized checks.
"""
return old_value != new_value
def record_change_entry(self, changedesc, old_value, new_value):
"""Records information on the changed values in a ChangeDescription.
By default, the values are stored as-is along with the field ID.
This can be overridden to perform more specialized storage.
"""
changedesc.record_field_change(self.field_id, old_value, new_value)
def serialize_change_entry(self, changedesc):
"""Serialize a change entry for public consumption.
This will output a version of the change entry for use in the API.
It can be the same content stored in the
:py:class:`~reviewboard.changedescs.models.ChangeDescription`, but
does not need to be.
Args:
changedesc (reviewboard.changedescs.models.ChangeDescription):
The change description whose field is to be serialized.
Returns:
dict:
An appropriate serialization for the field.
"""
field_info = changedesc.fields_changed[self.field_id]
if self.model:
return self.serialize_change_entry_for_model_list(field_info)
else:
return self.serialize_change_entry_for_singleton(field_info)
def serialize_change_entry_for_model_list(self, field_info):
"""Return the change entry for a list of models.
Args:
field_info (dict):
A dictionary describing how the field has changed. This is
guaranteed to have ``new`` and ``old`` keys, but may also
contain ``added`` and ``removed`` keys as well.
Returns:
dict:
A mapping of each key present in ``field_info`` to its list of
model instances.
"""
pks = [
value[2]
for key in ('new', 'old', 'added', 'removed')
if key in field_info
for value in field_info[key]
]
pk_to_objects = dict([
(obj.pk, obj)
for obj in self.model.objects.filter(pk__in=pks)
])
return dict([
(key, [
pk_to_objects[value[2]]
for value in field_info[key]
])
for key in ('new', 'old', 'added', 'removed')
if key in field_info
])
def serialize_change_entry_for_singleton(self, field_info):
"""Return the change entry for a singleton.
Singleton fields (e.g., summaries) are stored in
:py:class:`~reviewboard.changedescs.models.ChangeDescription`\s as
a list with a single element.
Args:
field_info (dict):
A dictionary describing how the field has changed. This is
guaranteed to have ``new`` and ``old`` keys, but may also
contain ``added`` and ``removed`` keys as well.
Returns:
dict:
A mapping of each key in ``field_info`` to a single value.
"""
return dict([
(key, field_info[key][0])
for key in ('new', 'old', 'added', 'removed')
if key in field_info
])
def serialize_change_entry_for_list(self, field_info):
"""Return the change entry for a list of plain data.
Args:
field_info (dict):
A dictionary describing how the field has changed. This is
guaranteed to have ``new`` and ``old`` keys, but may also
contain ``added`` and ``removed`` keys as well.
Returns:
dict:
A mapping of each key in ``field_info`` to a list of values.
"""
return dict([
(key, [
value[0]
for value in field_info[key]
])
for key in ('new', 'old', 'added', 'removed')
if key in field_info
])
def get_change_entry_sections_html(self, info):
"""Returns sections of change entries with titles and rendered HTML.
By default, this just returns a single section for the field, with
the field's title and rendered change HTML.
Subclasses can override this to provide more information.
"""
return [{
'title': self.label,
'rendered_html': mark_safe(self.render_change_entry_html(info)),
}]
def render_change_entry_html(self, info):
"""Renders a change entry to HTML.
By default, this returns a simple "changed from X to Y" using the old
and new values. This can be overridden to generate more specialized
output.
This function is expected to return safe, valid HTML. Any values
coming from a field or any other form of user input must be
properly escaped.
Subclasses can override ``render_change_entry_value_html`` to
change how the value itself will be rendered in the string.
"""
old_value = ''
new_value = ''
if 'old' in info:
old_value = info['old'][0]
if 'new' in info:
new_value = info['new'][0]
s = ['<table class="changed">']
if old_value:
s.append(self.render_change_entry_removed_value_html(
info, old_value))
if new_value:
s.append(self.render_change_entry_added_value_html(
info, new_value))
s.append('</table>')
return ''.join(s)
def render_change_entry_added_value_html(self, info, value):
value_html = self.render_change_entry_value_html(info, value)
if value_html:
return ('<tr class="new-value"><th class="marker">+</th>'
'<td class="value">%s</td></tr>' % value_html)
else:
return ''
def render_change_entry_removed_value_html(self, info, value):
value_html = self.render_change_entry_value_html(info, value)
if value_html:
return ('<tr class="old-value"><th class="marker">-</th>'
'<td class="value">%s</td></tr>' % value_html)
else:
return ''
def render_change_entry_value_html(self, info, value):
"""Renders the value for a change description string to HTML.
By default, this just converts the value to text and escapes it.
This can be overridden to customize how the value is displayed.
"""
return escape(six.text_type(value or ''))
def load_value(self, review_request_details):
"""Loads a value from the review request or draft.
By default, this loads the value as-is from the extra_data field.
This can be overridden if you need to deserialize the value in some
way.
This must use ``review_request_details`` instead of
``self.review_request_details``.
"""
return review_request_details.extra_data.get(self.field_id)
def save_value(self, value):
"""Saves the value in the review request or draft.
By default, this saves the value as-is in the extra_data field.
This can be overridden if you need to serialize the value in some
way.
"""
self.review_request_details.extra_data[self.field_id] = value
def render_value(self, value):
"""Renders the value in the field.
By default, this converts to text and escapes it. This can be
overridden if you need to render it in a more specific way.
This must use ``value`` instead of ``self.value``.
"""
return escape(six.text_type(value or ''))
def should_render(self, value):
"""Returns whether the field should be rendered.
By default, the field is always rendered, but this can be overridden
if you only want to show under certain conditions (such as if it has
a value).
This must use ``value`` instead of ``self.value``.
"""
return True
def get_css_classes(self):
"""Returns the list of CSS classes to apply to the element.
By default, this will include the contents of ``default_css_classes``,
and ``required`` if it's a required field.
This can be overridden to provide additional CSS classes, if they're
not appropraite for ``default_css_classes``.
"""
css_classes = set(self.default_css_classes)
if self.is_required:
css_classes.add('required')
return css_classes
def get_data_attributes(self):
"""Returns any data attributes to include in the element.
By default, this returns nothing.
"""
return {}
def as_html(self):
"""Returns the field rendered as HTML.
By default, this just calls ``render_value`` with the value
from the database.
"""
return self.render_value(self.value)
def __str__(self):
"""Represent the field as a byte string.
Returns:
bytes:
The field's ID as a byte string.
"""
if isinstance(self.field_id, six.binary_type):
return self.field_id
return self.field_id.encode('utf-8')
def __unicode__(self):
"""Represent the field as a unicode string.
Returns:
unicode:
The field's ID as a unicode string.
"""
if isinstance(self.field_id, six.binary_type):
return self.field_id.decode('utf-8')
return self.field_id
class BaseEditableField(BaseReviewRequestField):
"""Base class for an editable field.
This simply marks the field as editable.
"""
default_css_classes = ['editable']
is_editable = True
class BaseCommaEditableField(BaseEditableField):
"""Base class for an editable comma-separated list of values.
This is used for dealing with lists of items that appear
comma-separated in the UI. It works with stored lists of content
on the review request or draft, and on the ChangeDescription.
Subclasses can override this to provide specialized rendering
on a per-item-basis. That's useful for showing links to items,
for example.
"""
default_css_classes = ['editable', 'comma-editable']
order_matters = False
one_line_per_change_entry = True
def has_value_changed(self, old_value, new_value):
"""Returns whether two values have changed.
If ``order_matters`` is set to ``True``, this will do a strict
list comparison. Otherwise, it will compare the items in both
lists without caring about the ordering.
"""
if self.order_matters:
return old_value != new_value
else:
return set(old_value or []) != set(new_value or [])
def serialize_change_entry(self, changedesc):
"""Serialize a change entry for public consumption.
This will output a version of the change entry for use in the API.
It can be the same content stored in the
:py:class:`~reviewboard.changedescs.models.ChangeDescription`, but
does not need to be.
Args:
changedesc (reviewboard.changedescs.models.ChangeDescription):
The change description whose field is to be serialized.
Returns:
dict:
An appropriate serialization for the field.
"""
field_info = changedesc.fields_changed[self.field_id]
if self.model:
return self.serialize_change_entry_for_model_list(field_info)
else:
return self.serialize_change_entry_for_list(field_info)
def render_value(self, values):
"""Renders the list of items.
This will call out to ``render_item`` for every item. The list
of rendered items will be separated by a comma and a space.
"""
return ', '.join([
self.render_item(value)
for value in values
])
def render_item(self, item):
"""Renders an item from the list.
By default, this will convert the item to text and then escape it.
"""
return escape(six.text_type(item or ''))
def render_change_entry_html(self, info):
"""Renders a change entry to HTML.
By default, this returns HTML containing a list of removed items,
and a list of added items. This can be overridden to generate
more specialized output.
This function is expected to return safe, valid HTML. Any values
coming from a field or any other form of user input must be
properly escaped.
"""
s = ['<table class="changed">']
if 'removed' in info:
values = info['removed']
if self.one_line_per_change_entry:
s += [
self.render_change_entry_removed_value_html(info, [value])
for value in values
]
else:
s.append(self.render_change_entry_removed_value_html(
info, values))
if 'added' in info:
values = info['added']
if self.one_line_per_change_entry:
s += [
self.render_change_entry_added_value_html(info, [value])
for value in values
]
else:
s.append(self.render_change_entry_added_value_html(
info, values))
s.append('</table>')
return ''.join(s)
def render_change_entry_value_html(self, info, values):
"""Renders a list of items for change description HTML.
By default, this will call ``render_change_entry_item_html`` for every
item in the list. The list of rendered items will be separated by a
comma and a space.
"""
return ', '.join([
self.render_change_entry_item_html(info, item)
for item in values
])
def render_change_entry_item_html(self, info, item):
"""Renders an item for change description HTML.
By default, this just converts the value to text and escapes it.
This can be overridden to customize how the value is displayed.
"""
return escape(six.text_type(item[0]))
class BaseTextAreaField(BaseEditableField):
"""Base class for a multi-line text area field.
The text area can take either plain text or Markdown text. By default,
Markdown is supported, but this can be changed by setting
``enable_markdown`` to ``False``.
"""
default_css_classes = ['editable', 'field-text-area']
enable_markdown = True
always_render_markdown = False
tag_name = 'pre'
def is_text_markdown(self, value):
"""Returns whether the text is in Markdown format.
This can be overridden if the field needs to check something else
to determine if the text is in Markdown format.
"""
if self.field_id == 'text':
text_type_key = 'text_type'
else:
text_type_key = '%s_text_type' % self.field_id
text_type = self.review_request_details.extra_data.get(
text_type_key, 'plain')
return text_type == 'markdown'
def get_css_classes(self):
"""Returns the list of CSS classes.
If Markdown is enabled, and the text is in Markdown format,
this will add a "rich-text" field.
"""
css_classes = super(BaseTextAreaField, self).get_css_classes()
if (self.enable_markdown and self.value and
(self.should_render_as_markdown(self.value) or
(self.request.user and
is_rich_text_default_for_user(self.request.user)))):
css_classes.add('rich-text')
return css_classes
def get_data_attributes(self):
attrs = super(BaseTextAreaField, self).get_data_attributes()
if self.enable_markdown:
if self.request:
user = self.request.user
else:
user = None
attrs.update({
'allow-markdown': True,
'raw-value': normalize_text_for_edit(
user, self.value,
self.should_render_as_markdown(self.value)),
})
return attrs
def render_value(self, text):
"""Returns the value of the field.
If Markdown is enabled, and the text is not in Markdown format,
the text will be escaped.
"""
text = text or ''
if self.should_render_as_markdown(text):
return render_markdown(text)
else:
return escape(text)
def should_render_as_markdown(self, value):
"""Returns whether the text should be rendered as Markdown.
By default, this checks if the field is set to always render
any text as Markdown, or if the given text is in Markdown format.
"""
return self.always_render_markdown or self.is_text_markdown(value)
def render_change_entry_html(self, info):
old_value = ''
new_value = ''
if 'old' in info:
old_value = info['old'][0] or ''
if 'new' in info:
new_value = info['new'][0] or ''
old_value = render_markdown(old_value)
new_value = render_markdown(new_value)
old_lines = list(iter_markdown_lines(old_value))
new_lines = list(iter_markdown_lines(new_value))
differ = MyersDiffer(old_lines, new_lines)
return ('<table class="diffed-text-area">%s</table>'
% ''.join(self._render_all_change_lines(differ, old_lines,
new_lines)))
def _render_all_change_lines(self, differ, old_lines, new_lines):
for tag, i1, i2, j1, j2 in differ.get_opcodes():
if tag == 'equal':
lines = self._render_change_lines(differ, tag, None, None,
i1, i2, old_lines)
elif tag == 'insert':
lines = self._render_change_lines(differ, tag, None, '+',
j1, j2, new_lines)
elif tag == 'delete':
lines = self._render_change_lines(differ, tag, '-', None,
i1, i2, old_lines)
elif tag == 'replace':
lines = self._render_change_replace_lines(differ, i1, i2,
j1, j2, old_lines,
new_lines)
else:
raise ValueError('Unexpected tag "%s"' % tag)
for line in lines:
yield line
def _render_change_lines(self, differ, tag, old_marker, new_marker,
i1, i2, lines):
old_marker = old_marker or ' '
new_marker = new_marker or ' '
for i in range(i1, i2):
line = lines[i]
yield ('<tr class="%s">'
' <td class="marker">%s</td>'
' <td class="marker">%s</td>'
' <td class="line rich-text">%s</td>'
'</tr>'
% (tag, old_marker, new_marker, line))
def _render_change_replace_lines(self, differ, i1, i2, j1, j2,
old_lines, new_lines):
replace_new_lines = []
for i, j in zip(range(i1, i2), range(j1, j2)):
old_line = old_lines[i]
new_line = new_lines[j]
old_regions, new_regions = \
get_line_changed_regions(strip_tags(old_line),
strip_tags(new_line))
old_line = highlightregion(old_line, old_regions)
new_line = highlightregion(new_line, new_regions)
yield (
'<tr class="replace-old">'
' <td class="marker">~</td>'
' <td class="marker"> </td>'
' <td class="line rich-text">%s</td>'
'</tr>'
% old_line)
replace_new_lines.append(new_line)
for line in replace_new_lines:
yield (
'<tr class="replace-new">'
' <td class="marker"> </td>'
' <td class="marker">~</td>'
' <td class="line rich-text">%s</td>'
'</tr>'
% line)
def get_review_request_fields():
"""Yield all registered field classes.
Yields:
type:
The field classes, as subclasses of :py:class:`BaseReviewRequestField`
"""
for field in field_registry:
yield field
def get_review_request_fieldsets(include_main=False,
include_change_entries_only=False):
"""Returns a list of all registered fieldset classes.
As an internal optimization, the "main" fieldset can be filtered out,
to help with rendering the side of the review request page.
Args:
include_main (boolean):
Whether or not the main fieldset should be included.
include_change_entries_only (bool):
Whether or not to include the change-entry only fieldset.
Returns:
list:
The requested :py:class:`fieldsets <BaseReviewRequestFieldSet>`.
"""
if include_main and include_change_entries_only:
return list(fieldset_registry)
else:
excluded_ids = []
if not include_main:
excluded_ids.append('main')
if not include_change_entries_only:
excluded_ids.append('_change_entries_only')
return [
fieldset
for fieldset in fieldset_registry
if fieldset.fieldset_id not in excluded_ids
]
def get_review_request_fieldset(fieldset_id):
"""Return the fieldset with the specified ID.
Args:
fieldset_id (unicode):
The fieldset's ID.
Returns:
BaseReviewRequestFieldSet:
The requested fieldset, or ``None`` if it could not be found.
"""
return fieldset_registry.get('fieldset_id', fieldset_id)
def get_review_request_field(field_id):
"""Return the field with the specified ID.
Args:
field_id (unicode):
The field's ID.
Returns:
BaseReviewRequestField:
The requested field, or ``None`` if it could not be found.
"""
return field_registry.get('field_id', field_id)
def register_review_request_fieldset(fieldset):
"""Register a custom review request fieldset.
The fieldset must have a :py:attr:`~BaseReviewRequestFieldSet.fieldset_id`
attribute. This ID **must** be unique across all registered fieldsets, or
an exception will be thrown.
Args:
fieldset (type):
The :py:class:`BaseReviewRequestFieldSet` subclass.
Raises:
djblets.registries.errors.ItemLookupError:
This will be thrown if a fieldset is already registered with the
same ID.
"""
fieldset_registry.register(fieldset)
def unregister_review_request_fieldset(fieldset):
"""Unregister a previously registered review request fieldset.
Args:
fieldset (type):
The :py:class:`BaseReviewRequestFieldSet` subclass.
Raises:
djblets.registries.errors.ItemLookupError:
This will be thrown if the fieldset is not already registered.
"""
try:
fieldset_registry.unregister(fieldset)
except ItemLookupError as e:
logging.error('Failed to unregister unknown review request fieldset '
'"%s"',
fieldset.fieldset_id)
raise e
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details.
//>>built
define({"widgets/Screening/nls/strings":{_widgetLabel:"Klasyfikowanie",geometryServicesNotFound:"Us\u0142uga geometrii jest niedost\u0119pna.",unableToDrawBuffer:"Nie mo\u017cna wy\u015bwietli\u0107 bufora. Spr\u00f3buj ponownie.",invalidConfiguration:"Nieprawid\u0142owa konfiguracja",clearAOIButtonLabel:"Rozpocznij od nowa",noGraphicsShapefile:"Przes\u0142any plik shape nie zawiera grafik.",zoomToLocationTooltipText:"Powi\u0119ksz do lokalizacji",noGraphicsToZoomMessage:"Nie znaleziono grafik do powi\u0119kszenia.",
placenameWidget:{placenameLabel:"Wyszukaj lokalizacj\u0119"},drawToolWidget:{useDrawToolForAOILabel:"Wybierz tryb rysowania",toggleSelectability:"Kliknij, aby prze\u0142\u0105czy\u0107 mo\u017cliwo\u015b\u0107 wybierania",chooseLayerTitle:"Wybierz warstwy podlegaj\u0105ce selekcji",selectAllLayersText:"Zaznacz wszystkie",layerSelectionWarningTooltip:"Aby utworzy\u0107 obszar zainteresowania, nale\u017cy zaznaczy\u0107 co najmniej jedn\u0105 warstw\u0119",selectToolLabel:"Wybierz narz\u0119dzie"},
shapefileWidget:{shapefileLabel:"Prze\u015blij spakowany plik shape",uploadShapefileButtonText:"Prze\u015blij",unableToUploadShapefileMessage:"Nie mo\u017cna przes\u0142a\u0107 pliku shape."},coordinatesWidget:{selectStartPointFromSearchText:"Zdefiniuj punkt pocz\u0105tkowy",addButtonTitle:"Dodaj",deleteButtonTitle:"Usu\u0144",mapTooltipForStartPoint:"Kliknij map\u0119, aby zdefiniowa\u0107 punkt pocz\u0105tkowy",mapTooltipForUpdateStartPoint:"Kliknij map\u0119, aby zaktualizowa\u0107 punkt pocz\u0105tkowy",
locateText:"Lokalizuj",locateByMapClickText:"Wybierze wsp\u00f3\u0142rz\u0119dne pocz\u0105tkowe",enterBearingAndDistanceLabel:"Wprowad\u017a k\u0105t kierunkowy i odleg\u0142o\u015b\u0107 od punktu pocz\u0105tkowego",bearingTitle:"K\u0105t kierunkowy",distanceTitle:"Odleg\u0142o\u015b\u0107",planSettingTooltip:"Ustawienia planu",invalidLatLongMessage:"Wprowad\u017a prawid\u0142owe warto\u015bci."},bufferDistanceAndUnit:{bufferInputTitle:"Odleg\u0142o\u015b\u0107 wyszukiwania (opcjonalnie)",bufferInputLabel:"Wy\u015bwietl wyniki w obr\u0119bie",
bufferDistanceLabel:"Odleg\u0142o\u015b\u0107 buforowania",bufferUnitLabel:"Jednostka buforowania"},traverseSettings:{bearingLabel:"K\u0105t kierunkowy",lengthLabel:"d\u0142ugo\u015b\u0107",addButtonTitle:"Dodaj",deleteButtonTitle:"Usu\u0144",deleteBearingAndLengthLabel:"Usu\u0144 wiersz k\u0105ta kierunkowego i d\u0142ugo\u015bci",addButtonLabel:"Dodaj k\u0105t kierunkowy i d\u0142ugo\u015b\u0107"},planSettings:{expandGridTooltipText:"Rozwi\u0144 siatk\u0119",collapseGridTooltipText:"Zwi\u0144 siatk\u0119",
directionUnitLabelText:"Jednostka kierunku",distanceUnitLabelText:"Jednostki odleg\u0142o\u015bci i d\u0142ugo\u015bci",planSettingsComingSoonText:"Ju\u017c wkr\u00f3tce"},newTraverse:{invalidBearingMessage:"Nieprawid\u0142owy k\u0105t kierunkowy.",invalidLengthMessage:"Nieprawid\u0142owa d\u0142ugo\u015b\u0107.",negativeLengthMessage:"Ujemna d\u0142ugo\u015b\u0107"},reportsTab:{aoiAreaText:"Powierzchnia obszaru zainteresowania",downloadButtonTooltip:"Pobierz",printButtonTooltip:"Drukuj",uploadShapefileForAnalysisText:"Prze\u015blij plik shape do uwzgl\u0119dnienia w analizie",
uploadShapefileForButtonText:"Przegl\u0105daj",downloadLabelText:"Wybierz format:",downloadBtnText:"Pobierz",noDetailsAvailableText:"Nie odnaleziono wynik\u00f3w",featureCountText:"Liczba",featureAreaText:"obszar",featureLengthText:"d\u0142ugo\u015b\u0107",attributeChooserTooltip:"Wybierz atrybuty do wy\u015bwietlenia",csv:"CSV",filegdb:"Geobaza plikowa",shapefile:"Plik shape",noFeaturesFound:"Nie znaleziono wynik\u00f3w dla wybranego formatu pliku",selectReportFieldTitle:"Wybierz pola",noFieldsSelected:"Nie wybrano p\u00f3l",
intersectingFeatureExceedsMsgOnCompletion:"Osi\u0105gni\u0119to maksymaln\u0105 liczb\u0119 rekord\u00f3w dla co najmniej jednej warstwy.",unableToAnalyzeText:"Nie mo\u017cna przeprowadzi\u0107 analizy. Osi\u0105gni\u0119to maksymaln\u0105 liczb\u0119 rekord\u00f3w.",errorInPrintingReport:"Nie mo\u017cna wydrukowa\u0107 raportu. Sprawd\u017a, czy ustawienia raportu s\u0105 prawid\u0142owe.",aoiInformationTitle:"Informacje o obszarze zainteresowania",summaryReportTitle:"Podsumowanie",notApplicableText:"Nie dotyczy",
downloadReportConfirmTitle:"Potwierd\u017a pobieranie",downloadReportConfirmMessage:"Czy na pewno chcesz pobra\u0107 plik?",noDataText:"Brak danych",createReplicaFailedMessage:"Operacja pobierania nie powiod\u0142a si\u0119 dla nast\u0119puj\u0105cych warstw: \x3cbr/\x3e ${layerNames}",extractDataTaskFailedMessage:"Operacja pobierania nie powiod\u0142a si\u0119.",printLayoutLabelText:"Kompozycja",printBtnText:"Drukuj",printDialogHint:"Uwaga: Tytu\u0142 raportu i komentarze mo\u017cna edytowa\u0107 w podgl\u0105dzie raportu.",
unableToDownloadFileGDBText:"Nie mo\u017cna pobra\u0107 geobazy plikowej w przypadku obszaru zainteresowania zawieraj\u0105cego lokalizacje punkt\u00f3w lub linii",unableToDownloadShapefileText:"Nie mo\u017cna pobra\u0107 pliku shape w przypadku obszaru zainteresowania zawieraj\u0105cego lokalizacje punkt\u00f3w lub linii",analysisAreaUnitLabelText:"Poka\u017c wyniki obliczania pola powierzchni w:",analysisLengthUnitLabelText:"Poka\u017c wyniki obliczania d\u0142ugo\u015bci w:",analysisUnitButtonTooltip:"Wybierz jednostki do analizy",
analysisCloseBtnText:"Zamknij",areaSquareFeetUnit:"Stopy kwadratowe",areaAcresUnit:"Akry",areaSquareMetersUnit:"Metry kwadratowe",areaSquareKilometersUnit:"Kilometry kwadratowe",areaHectaresUnit:"Hektary",areaSquareMilesUnit:"Mile kwadratowe",lengthFeetUnit:"Stopy",lengthMilesUnit:"Mile",lengthMetersUnit:"Metry",lengthKilometersUnit:"Kilometry",hectaresAbbr:"hektary",squareMilesAbbr:"Mile kwadratowe",layerNotVisibleText:"Nie mo\u017cna przeprowadzi\u0107 analizy. Warstwa jest wy\u0142\u0105czona lub jest poza zakresem skali widoczno\u015bci.",
refreshBtnTooltip:"Od\u015bwie\u017c raport",featureCSVAreaText:"Obszar przecinania",featureCSVLengthText:"D\u0142ugo\u015b\u0107 przecinania",errorInFetchingPrintTask:"Wyst\u0105pi\u0142 b\u0142\u0105d podczas pobierania informacji o zadaniu drukowania. Spr\u00f3buj ponownie.",selectAllLabel:"Wybierz wszystkie",errorInLoadingProjectionModule:"Wyst\u0105pi\u0142 b\u0142\u0105d podczas wczytywania zale\u017cno\u015bci modu\u0142\u00f3w odwzorowania. Spr\u00f3buj ponownie pobra\u0107 ten plik.",expandCollapseIconLabel:"Przeci\u0119te obiekty",
intersectedFeatureLabel:"Szczeg\u00f3\u0142y przeci\u0119tego obiektu",valueAriaLabel:"Warto\u015b\u0107",countAriaLabel:"Liczba",layerNameWithFeatureCount:"Warstwa ${layerName} z nast\u0119puj\u0105c\u0105 liczb\u0105 przecinaj\u0105cych si\u0119 obiekt\u00f3w: ${featureCount}"},_localized:{}}});
|
import { Matrix3 } from '../../math/Matrix3.js';
import { Plane } from '../../math/Plane.js';
function WebGLClipping( properties ) {
const scope = this;
let globalState = null,
numGlobalPlanes = 0,
localClippingEnabled = false,
renderingShadows = false;
const plane = new Plane(),
viewNormalMatrix = new Matrix3(),
uniform = { value: null, needsUpdate: false };
this.uniform = uniform;
this.numPlanes = 0;
this.numIntersection = 0;
this.init = function ( planes, enableLocalClipping, camera ) {
const enabled =
planes.length !== 0 ||
enableLocalClipping ||
// enable state of previous frame - the clipping code has to
// run another frame in order to reset the state:
numGlobalPlanes !== 0 ||
localClippingEnabled;
localClippingEnabled = enableLocalClipping;
globalState = projectPlanes( planes, camera, 0 );
numGlobalPlanes = planes.length;
return enabled;
};
this.beginShadows = function () {
renderingShadows = true;
projectPlanes( null );
};
this.endShadows = function () {
renderingShadows = false;
resetGlobalState();
};
this.setState = function ( material, camera, useCache ) {
const planes = material.clippingPlanes,
clipIntersection = material.clipIntersection,
clipShadows = material.clipShadows;
const materialProperties = properties.get( material );
if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
// there's no local clipping
if ( renderingShadows ) {
// there's no global clipping
projectPlanes( null );
} else {
resetGlobalState();
}
} else {
const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
lGlobal = nGlobal * 4;
let dstArray = materialProperties.clippingState || null;
uniform.value = dstArray; // ensure unique state
dstArray = projectPlanes( planes, camera, lGlobal, useCache );
for ( let i = 0; i !== lGlobal; ++ i ) {
dstArray[ i ] = globalState[ i ];
}
materialProperties.clippingState = dstArray;
this.numIntersection = clipIntersection ? this.numPlanes : 0;
this.numPlanes += nGlobal;
}
};
function resetGlobalState() {
if ( uniform.value !== globalState ) {
uniform.value = globalState;
uniform.needsUpdate = numGlobalPlanes > 0;
}
scope.numPlanes = numGlobalPlanes;
scope.numIntersection = 0;
}
function projectPlanes( planes, camera, dstOffset, skipTransform ) {
const nPlanes = planes !== null ? planes.length : 0;
let dstArray = null;
if ( nPlanes !== 0 ) {
dstArray = uniform.value;
if ( skipTransform !== true || dstArray === null ) {
const flatSize = dstOffset + nPlanes * 4,
viewMatrix = camera.matrixWorldInverse;
viewNormalMatrix.getNormalMatrix( viewMatrix );
if ( dstArray === null || dstArray.length < flatSize ) {
dstArray = new Float32Array( flatSize );
}
for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
plane.normal.toArray( dstArray, i4 );
dstArray[ i4 + 3 ] = plane.constant;
}
}
uniform.value = dstArray;
uniform.needsUpdate = true;
}
scope.numPlanes = nPlanes;
scope.numIntersection = 0;
return dstArray;
}
}
export { WebGLClipping };
|
// This is the "Offline page" service worker
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-gpcasas_sw.js');
const CACHE = "pwabuilder-page";
// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
const offlineFallbackPage = "/home/offline";
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
self.addEventListener('install', async (event) => {
event.waitUntil(
caches.open(CACHE)
.then((cache) => cache.add(offlineFallbackPage))
);
});
if (workbox.navigationPreload.isSupported()) {
workbox.navigationPreload.enable();
}
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResp = await event.preloadResponse;
if (preloadResp) {
return preloadResp;
}
const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {
const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})());
}
});
|
""" Utilities app."""
# Django
from django.apps import AppConfig
class UtilsConfig(AppConfig):
name = 'locfilm.utils'
verbose_name = 'Utilities'
|
var CTD1list = [[36.8, -0.797], [36.846, -0.799], [36.892, -0.799], [36.94, -0.798], [36.985, -0.796], [37.031, -0.797], [37.077, -0.799], [37.077, -0.684], [37.03, -0.681], [36.985, -0.681], [36.938, -0.683], [36.891, -0.681], [36.846, -0.683], [36.8, -0.681], [36.8, -0.567], [36.847, -0.562], [36.892, -0.568], [36.938, -0.568], [36.984, -0.568], [37.031, -0.569], [37.078, -0.569], [37.077, -0.454], [37.029, -0.454], [36.983, -0.455], [36.937, -0.454], [36.891, -0.453], [36.845, -0.453], [36.799, -0.453], [36.8, -0.34], [36.845, -0.338], [36.891, -0.341], [36.983, -0.34], [37.031, -0.339], [37.076, -0.338], [36.752, -0.452], [36.753, -0.338]]
|
import FeedItem from "./feed-item";
import { getContent, excerpt, getContentAttr, html2text } from './util';
export default class AtomFeedItem extends FeedItem {
constructor() {
super();
}
static fromAtomXmlItem = (url, xmlItem) => {
var title = excerpt(getContent(xmlItem, 'title'), 200);
var titleType = getContentAttr(xmlItem, 'title', 'type');
if (titleType === 'text/html' || titleType === 'html') title = html2text(title);
var link = excerpt(getContent(xmlItem, 'link') || getContentAttr(xmlItem, 'link', 'href'), 20000);
var summaryType = excerpt(getContentAttr(xmlItem, 'summary', 'type'), 20000);
var summary = excerpt(getContent(xmlItem, 'summary'), 300000);
var content = excerpt(getContent(xmlItem, 'content'), 1000000);
var contentType = excerpt(getContentAttr(xmlItem, 'content', 'type'), 20000);
if (contentType === 'text/html') contentType = 'html';
else contentType = 'text';
var description = !summary
? html2text(content.slice(0, 300)).slice(0, 200)
: html2text(summary.slice(0, 3000)).slice(0, 2000);
const instance = new AtomFeedItem();
instance.title = title;
instance.link = link;
instance.description = description; // description is a short description without html
instance.summary = summary; // summary is long description with unsanitized html
instance.descIsExcerpt = !summary;
instance.contentType = contentType;
instance.author = excerpt(getContent(xmlItem, 'author'), 200);
instance.content = content; // the article with html
instance.contentType = contentType;
instance.contentBase = excerpt(getContentAttr(xmlItem, 'content', 'xml:base'), 2000);
instance.category = excerpt(getContent(xmlItem, 'category') || getContentAttr(xmlItem, 'category', 'term'), 4000);
instance.date = new Date((getContent(xmlItem, 'published') || getContent(xmlItem, 'updated')) || 0).getTime();
instance.should_update_token = description.length;
return instance;
}
}
|
/**
* @param { Array } arr
* @param { number } depth
* @returns { Array }
*/
function flat(arr, depth = 1) {
return arr.reduce((acc, item) => {
if (depth && Array.isArray(item)) {
return [...acc, ...flat(item, depth - 1)];
}
return [...acc, item];
}, []);
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _Tooltip = require('../Tooltip');
var _Tooltip2 = _interopRequireDefault(_Tooltip);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var propTypes = {
cellFormatter: _react.PropTypes.func, // Used by the Table component to format the cell content for this "column"
className: _react.PropTypes.string,
name: _react.PropTypes.string.isRequired,
numeric: _react.PropTypes.bool,
onClick: _react.PropTypes.func,
nosort: _react.PropTypes.bool,
sortFn: _react.PropTypes.func, // Used by the Sortable component
tooltip: _react.PropTypes.node
};
var TableHeader = function TableHeader(props) {
var className = props.className;
var name = props.name;
var numeric = props.numeric;
var onClick = props.onClick;
var nosort = props.nosort;
var tooltip = props.tooltip;
var children = props.children;
var otherProps = _objectWithoutProperties(props, ['className', 'name', 'numeric', 'onClick', 'nosort', 'tooltip', 'children']);
// remove unwanted props
// see https://github.com/Hacker0x01/react-datepicker/issues/517#issuecomment-230171426
delete otherProps.cellFormatter;
delete otherProps.sortFn;
var classes = (0, _classnames2.default)({
'mdl-data-table__cell--non-numeric': !numeric
}, className);
var clickFn = !nosort && onClick ? function (e) {
return onClick(e, name);
} : null;
return _react2.default.createElement(
'th',
_extends({ className: classes, onClick: clickFn }, otherProps),
!!tooltip ? _react2.default.createElement(
_Tooltip2.default,
{ label: tooltip },
children
) : children
);
};
TableHeader.propTypes = propTypes;
exports.default = TableHeader;
|
#
# Copyright (c) 2003-2010 Greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
from rdkit import RDConfig
import os, sys, time
try:
import subprocess
except ImportError:
subprocess = None
TEST_FAILED = -1
TEST_PASSED = 0
def RunTest(exeName, args, extras):
if exeName == "python":
exeName = RDConfig.pythonExe
args = args.split(' ')
startDir = os.getcwd()
if 'dir' in extras:
os.chdir(extras['dir'])
expectedReturn = extras.get('returns', 0)
if not subprocess:
raise NotImplementedError('cannot run tests if the subprocess module is not available.')
else:
try:
retVal = subprocess.call([exeName] + list(args))
except OSError:
print("Could not find executable: %s." % exeName, file=sys.stderr)
return TEST_FAILED
if 'dir' in extras:
os.chdir(startDir)
if retVal != expectedReturn:
return TEST_FAILED
else:
return TEST_PASSED
def RunScript(script, doLongTests, verbose):
# support python 2.7 style -f argument for failfast
if sys.argv[-1] == '-f':
# setting environment allows this setting to recursively pass to all child
# processes
os.environ['PYTHON_TEST_FAILFAST'] = '1'
if len(sys.argv) == 3 and sys.argv[1] == '--testDir':
os.chdir(sys.argv[2])
# -------------------------------------------------------
# this is pretty funny. Whatever directory we started python in
# will be in the search path, and if we've changed to another
# directory, that'll be there too. HOWEVER... the starting
# directory will be searched first (at least in python2.2), so we
# need to make sure that '.' is at the front of the search path
if sys.path[0] != '.':
sys.path = ['.'] + sys.path
script = script.split('.py')[0]
mod = __import__(script)
try:
tests = mod.tests
except AttributeError:
return [], 0
longTests = []
if doLongTests:
try:
longTests = mod.longTests
except AttributeError:
pass
failed = []
for i, entry in enumerate(tests):
try:
exeName, args, extras = entry
except ValueError:
print('bad entry:', entry)
sys.exit(-1)
try:
res = RunTest(exeName, args, extras)
except Exception:
import traceback
traceback.print_exc()
res = TEST_FAILED
if res != TEST_PASSED:
failed.append((exeName, args, extras))
# check failfast setting
if os.environ.get('PYTHON_TEST_FAILFAST', '') == '1':
# return immediately
sys.stderr.write("Exiting from %s\n" % str([exeName] + list(args)))
return failed, i + 1
for i, (exeName, args, extras) in enumerate(longTests):
res = RunTest(exeName, args, extras)
if res != TEST_PASSED:
failed.append((exeName, args, extras))
if os.environ.get('PYTHON_TEST_FAILFAST', '') == '1':
# return immediately
sys.stderr.write("Exitng from %s\n" % str([exeName] + list(args)))
return failed, len(tests) + i + 1
nTests = len(tests) + len(longTests)
del sys.modules[script]
if verbose and failed:
for exeName, args, extras in failed:
print("!!! TEST FAILURE: ", exeName, args, extras, file=sys.stderr)
return failed, nTests
def ReportResults(script, failedTests, nTests, runTime, verbose, dest):
if not nTests:
dest.write('!-!-!-!-!-!-!-!-!-!-!\n')
dest.write('\tScript: %s. No tests run!\n' % (script))
elif not len(failedTests):
dest.write('-----------------\n')
dest.write('\tScript: %s. Passed %d tests in %.2f seconds\n' % (script, nTests, runTime))
else:
dest.write('!-!-!-!-!-!-!-!-!-!-!\n')
dest.write('\tScript: %s. Failed %d (of %d) tests in %.2f seconds\n' %
(script, len(failedTests), nTests, runTime))
if verbose:
for exeName, args, extras in failedTests:
dirName = extras.get('dir', '.')
dirName = os.path.abspath(dirName)
dest.write('\t\t(%s): %s %s\n' % (dirName, exeName, args))
if __name__ == '__main__':
import getopt
args, extras = getopt.getopt(sys.argv[1:], 'lv')
doLongTests = 0
verbose = 1
for arg, val in args:
if arg == '-l':
doLongTests = 1
elif arg == '-v':
verbose = 0
pwd = os.getcwd()
totNumFailed = 0
totNumRun = 0
failures = []
timeAccum = 0.0
for script in extras:
try:
open(script, 'r')
except IOError:
sys.stderr.write('ERROR: Test script %s could not be opened.\n' % (script))
else:
dirName = os.path.dirname(script)
scriptBase = os.path.basename(script)
if dirName:
os.chdir(dirName)
try:
t1 = time.time()
failed, nTests = RunScript(scriptBase, doLongTests, verbose)
t2 = time.time()
except ImportError:
import traceback
traceback.print_exc()
sys.stderr.write('ERROR: Could not import test script %s\n' % (script))
else:
runTime = t2 - t1
ReportResults(script, failed, nTests, runTime, verbose, sys.stderr)
timeAccum += runTime
if dirName:
os.chdir(pwd)
if len(extras) > 1:
totNumFailed += len(failed)
totNumRun += nTests
if len(failed):
failures.append(script)
if totNumRun > 1:
sys.stderr.write('\n\n-*-*-*-*-*-*- Test Results Summary -*-*-*-*-*-*-\n')
sys.stderr.write('\t\tTotal run time: %.2f seconds\n' % (timeAccum))
if totNumFailed:
sys.stderr.write('!!!!!--- %d Failures in %d tests ---!!!!!\n' % (totNumFailed, totNumRun))
sys.stderr.write('\tModules with failures:\n')
for failure in failures:
sys.stderr.write('\t\t%s\n' % failure)
else:
sys.stderr.write(' All %d tests (in %d modules) passed\n' % (totNumRun, len(extras)))
sys.exit(totNumFailed)
class _RedirectStream:
_stream = None
def __init__(self, new_target):
self._new_target = new_target
# We use a list of old targets to make this CM re-entrant
self._old_targets = []
def __enter__(self):
self._old_targets.append(getattr(sys, self._stream))
setattr(sys, self._stream, self._new_target)
return self._new_target
def __exit__(self, exctype, excinst, exctb):
setattr(sys, self._stream, self._old_targets.pop())
class redirect_stdout(_RedirectStream):
"""Context manager for temporarily redirecting stdout to another file.
# How to send help() to stderr
with redirect_stdout(sys.stderr):
help(dir)
# How to write help() to a file
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
"""
_stream = "stdout"
class redirect_stderr(_RedirectStream):
"""Context manager for temporarily redirecting stderr to another file."""
_stream = "stderr"
class OutputRedirectC:
"""Context manager which uses low-level file descriptors to suppress
output to stdout/stderr, optionally redirecting to the named file(s).
Suppress all output
with Silence():
<code>
Redirect stdout to file
with OutputRedirectC(stdout='output.txt', mode='w'):
<code>
Redirect stderr to file
with OutputRedirectC(stderr='output.txt', mode='a'):
<code>
http://code.activestate.com/recipes/577564-context-manager-for-low-level-redirection-of-stdou/
>>>
"""
def __init__(self, stdout=os.devnull, stderr=os.devnull, mode='wb'):
self.outfiles = stdout, stderr
self.combine = (stdout == stderr)
self.mode = mode
self.saved_streams = None
self.fds = None
self.saved_fds = None
self.null_fds = None
self.null_streams = None
def __enter__(self):
# save previous stdout/stderr
self.saved_streams = saved_streams = sys.__stdout__, sys.__stderr__
self.fds = fds = [s.fileno() for s in saved_streams]
self.saved_fds = [os.dup(fd) for fd in fds]
# flush any pending output
for s in saved_streams:
s.flush()
# open surrogate files
if self.combine:
null_streams = [open(self.outfiles[0], self.mode, 0)] * 2
if self.outfiles[0] != os.devnull:
# disable buffering so output is merged immediately
sys.stdout, sys.stderr = [os.fdopen(fd, 'wb', 0) for fd in fds]
else:
null_streams = [open(f, self.mode, 0) for f in self.outfiles]
self.null_fds = null_fds = [s.fileno() for s in null_streams]
self.null_streams = null_streams
# overwrite file objects and low-level file descriptors
for null_fd, fd in zip(null_fds, fds):
os.dup2(null_fd, fd)
def __exit__(self, *args):
# flush any pending output
for s in self.saved_streams:
s.flush()
# restore original streams and file descriptors
for saved_fd, fd in zip(self.saved_fds, self.fds):
os.dup2(saved_fd, fd)
sys.stdout, sys.stderr = self.saved_streams
# clean up
for s in self.null_streams:
s.close()
for fd in self.saved_fds:
os.close(fd)
return False
|
import React from "react";
import { Link, Redirect, Route } from "react-router-dom";
// reactstrap components
import { } from "reactstrap";
import AuthService from "services/AuthService.js"
function PrivateRoute({ component: Component, ...rest }) {
return (
<Route {...rest} render={(props) => (
localStorage.getItem('isAuth') === "true"
? <Component {...props}></Component>
: <Redirect to={{
pathname: '/cms/login',
state: { from: props.location }
}} />
)} />
)
}
export default PrivateRoute;
|
const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const { SignedXml } = require('xml-crypto')
const { encrypt } = require('xml-encryption')
const xpath = require('xpath')
module.exports = (serviceProvider) => {
// NOTE - the typo in keyEncryptionAlgorighm is deliberate
const ENCRYPT_OPTIONS = {
rsa_pub: serviceProvider.pubKey,
pem: serviceProvider.cert,
encryptionAlgorithm: 'http://www.w3.org/2001/04/xmlenc#aes256-cbc',
keyEncryptionAlgorighm: 'http://www.w3.org/2001/04/xmlenc#rsa-1_5',
}
const apexBaseString = function apexBaseString ({
httpMethod,
url,
appId,
clientId,
singpassEserviceId,
nonce,
requestedAttributes,
timestamp,
}) {
return httpMethod.toUpperCase() +
// url string replacement was dictated by MyInfo docs - no explanation
// was provided for why this is necessary
'&' + url.replace('.api.gov.sg', '.e.api.gov.sg') +
'&apex_l2_eg_app_id=' + appId +
'&apex_l2_eg_nonce=' + nonce +
'&apex_l2_eg_signature_method=SHA256withRSA' +
'&apex_l2_eg_timestamp=' + timestamp +
'&apex_l2_eg_version=1.0' +
'&attributes=' + requestedAttributes +
'&client_id=' + clientId +
'&singpassEserviceId=' + singpassEserviceId
}
const pkiBaseString = function pkiBaseString ({
httpMethod,
appId,
nonce,
timestamp,
}) {
return httpMethod.toUpperCase() +
'&app_id=' + appId +
'&nonce=' + nonce +
'&signature_method=RS256' +
'×tamp=' + timestamp
}
return {
verifySignature (xml) {
const [signature] =
xpath.select("//*[local-name(.)='Signature']", xml) || []
const [artifactResolvePayload] =
xpath.select("//*[local-name(.)='ArtifactResolve']", xml) || []
const verifier = new SignedXml()
verifier.keyInfoProvider = { getKey: () => ENCRYPT_OPTIONS.pem }
verifier.loadSignature(signature.toString())
return verifier.checkSignature(artifactResolvePayload.toString())
},
sign (payload, reference) {
const sig = new SignedXml()
const transforms = [
'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
'http://www.w3.org/2001/10/xml-exc-c14n#',
]
const digestAlgorithm = 'http://www.w3.org/2001/04/xmlenc#sha256'
sig.addReference(reference, transforms, digestAlgorithm)
sig.signingKey = fs.readFileSync(path.resolve(__dirname, '../static/certs/spcp-key.pem'))
sig.signatureAlgorithm = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'
const options = {
prefix: 'ds',
location: { reference, action: 'prepend' },
}
sig.computeSignature(payload, options)
return sig.getSignedXml()
},
promiseToEncryptAssertion: assertion => new Promise((resolve, reject) => {
encrypt(
assertion,
ENCRYPT_OPTIONS,
(err, data) => err
? reject(err)
: resolve(`<saml:EncryptedAssertion>${data}</saml:EncryptedAssertion>`)
)
}),
verifyMyInfoSignature (signature, baseStringFields, baseString = apexBaseString) {
const verifier = crypto.createVerify('RSA-SHA256')
verifier.update(baseString(baseStringFields))
verifier.end()
return verifier.verify(serviceProvider.pubKey, signature, 'base64')
},
apexBaseString,
pkiBaseString,
}
}
|
const mongoose = require('mongoose');
const { setupApp } = require('../helper-functions');
const translationsService = require('../../modules/translations/translations.service');
const { translations, newTranslations } = require('./translations.variables');
let firstTranslationsId;
let secondTranslationsId;
let response;
describe('translations service test', () => {
beforeAll(async () => {
await setupApp();
});
afterAll(async () => {
await mongoose.connection.db.dropDatabase();
});
it('should create new translations', async () => {
const firstCreatedTranslations = await translationsService.addTranslations(
translations
);
const secondCreatedTranslations = await translationsService.addTranslations(
translations
);
firstTranslationsId = firstCreatedTranslations._id;
secondTranslationsId = secondCreatedTranslations._id;
expect(firstCreatedTranslations).toHaveProperty(
'ua.name',
translations.ua.name
);
});
it('should update translations', async () => {
const updatedTranslations = await translationsService.updateTranslations(
firstTranslationsId,
newTranslations
);
expect(updatedTranslations).toHaveProperty(
'ua.name',
newTranslations.ua.name
);
});
it('should get all translations', async () => {
await translationsService.getAllTranslations(
{},
{
json: data => {
response = data;
},
}
);
expect(response).toHaveProperty('ua');
});
it('should delete translations', async () => {
const deletedTranslations = await translationsService.deleteTranslations(
firstTranslationsId
);
await translationsService.deleteTranslations(secondTranslationsId);
expect(deletedTranslations._id).toEqual(firstTranslationsId);
});
});
|
#!/usr/bin/env python2
# Copyright 2011 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""emcc - compiler helper script
=============================
emcc is a drop-in replacement for a compiler like gcc or clang.
See emcc --help for details.
emcc can be influenced by a few environment variables:
EMCC_DEBUG - "1" will log out useful information during compilation, as well as
save each compiler step as an emcc-* file in the temp dir
(by default /tmp/emscripten_temp). "2" will save additional emcc-*
steps, that would normally not be separately produced (so this
slows down compilation).
EMMAKEN_NO_SDK - Will tell emcc *not* to use the emscripten headers. Instead
your system headers will be used.
EMMAKEN_COMPILER - The compiler to be used, if you don't want the default clang.
"""
from __future__ import print_function
import json
import logging
import os
import re
import shlex
import shutil
import stat
import sys
import time
from subprocess import PIPE
import emscripten
from tools import shared, system_libs, client_mods, js_optimizer, jsrun, colored_logger
from tools.shared import unsuffixed, unsuffixed_basename, WINDOWS, safe_copy, safe_move, run_process, asbytes, read_and_preprocess, exit_with_error, DEBUG
from tools.response_file import substitute_response_files
import tools.line_endings
from tools.toolchain_profiler import ToolchainProfiler
if __name__ == '__main__':
ToolchainProfiler.record_process_start()
try:
from urllib.parse import quote
except ImportError:
# Python 2 compatibility
from urllib import quote
logger = logging.getLogger('emcc')
# endings = dot + a suffix, safe to test by filename.endswith(endings)
C_ENDINGS = ('.c', '.C', '.i')
CXX_ENDINGS = ('.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.CC', '.C++', '.ii')
OBJC_ENDINGS = ('.m', '.mi')
OBJCXX_ENDINGS = ('.mm', '.mii')
SPECIAL_ENDINGLESS_FILENAMES = ('/dev/null',)
SOURCE_ENDINGS = C_ENDINGS + CXX_ENDINGS + OBJC_ENDINGS + OBJCXX_ENDINGS + SPECIAL_ENDINGLESS_FILENAMES
C_ENDINGS = C_ENDINGS + SPECIAL_ENDINGLESS_FILENAMES # consider the special endingless filenames like /dev/null to be C
JS_CONTAINING_ENDINGS = ('.js', '.mjs', '.html')
OBJECT_FILE_ENDINGS = ('.bc', '.o', '.obj', '.lo')
DYNAMICLIB_ENDINGS = ('.dylib', '.so') # Windows .dll suffix is not included in this list, since those are never linked to directly on the command line.
STATICLIB_ENDINGS = ('.a',)
ASSEMBLY_ENDINGS = ('.ll',)
HEADER_ENDINGS = ('.h', '.hxx', '.hpp', '.hh', '.H', '.HXX', '.HPP', '.HH')
WASM_ENDINGS = ('.wasm', '.wast')
SUPPORTED_LINKER_FLAGS = (
'--start-group', '--end-group',
'-(', '-)',
'--whole-archive', '--no-whole-archive',
'-whole-archive', '-no-whole-archive')
LIB_PREFIXES = ('', 'lib')
DEFERRED_RESPONSE_FILES = ('EMTERPRETIFY_BLACKLIST', 'EMTERPRETIFY_WHITELIST', 'EMTERPRETIFY_SYNCLIST')
# Mapping of emcc opt levels to llvm opt levels. We use llvm opt level 3 in emcc
# opt levels 2 and 3 (emcc 3 is unsafe opts, so unsuitable for the only level to
# get llvm opt level 3, and speed-wise emcc level 2 is already the slowest/most
# optimizing level)
LLVM_OPT_LEVEL = {
0: ['-O0'],
1: ['-O1'],
2: ['-O3'],
3: ['-O3'],
}
# Do not compile .ll files into .bc, just compile them with emscripten directly
# Not recommended, this is mainly for the test runner, or if you have some other
# specific need.
# One major limitation with this mode is that libc and libc++ cannot be
# added in. Also, LLVM optimizations will not be done, nor dead code elimination
LEAVE_INPUTS_RAW = int(os.environ.get('EMCC_LEAVE_INPUTS_RAW', '0'))
# If emcc is running with LEAVE_INPUTS_RAW and then launches an emcc to build
# something like the struct info, then we don't want LEAVE_INPUTS_RAW to be
# active in that emcc subprocess.
if LEAVE_INPUTS_RAW:
del os.environ['EMCC_LEAVE_INPUTS_RAW']
# If set to 1, we will run the autodebugger (the automatic debugging tool, see
# tools/autodebugger). Note that this will disable inclusion of libraries. This
# is useful because including dlmalloc makes it hard to compare native and js
# builds
AUTODEBUG = os.environ.get('EMCC_AUTODEBUG')
# Target options
final = None
UBSAN_SANITIZERS = {
'alignment',
'bool',
'builtin',
'bounds',
'enum',
'float-cast-overflow',
'float-divide-by-zero',
'function',
'implicit-unsigned-integer-truncation',
'implicit-signed-integer-truncation',
'implicit-integer-sign-change',
'integer-divide-by-zero',
'nonnull-attribute',
'null',
'nullability-arg',
'nullability-assign',
'nullability-return',
'object-size',
'pointer-overflow',
'return',
'returns-nonnull-attribute',
'shift',
'signed-integer-overflow',
'unreachable',
'unsigned-integer-overflow',
'vla-bound',
'vptr',
'undefined',
'undefined-trap',
'implicit-integer-truncation',
'implicit-integer-arithmetic-value-change',
'implicit-conversion',
'integer',
'nullability',
}
class Intermediate(object):
counter = 0
# this function uses the global 'final' variable, which contains the current
# final output file. if a method alters final, and calls this method, then it
# must modify final globally (i.e. it can't receive final as a param and
# return it)
# TODO: refactor all this, a singleton that abstracts over the final output
# and saving of intermediates
def save_intermediate(name, suffix='js'):
if not DEBUG:
return
name = os.path.join(shared.get_emscripten_temp_dir(), 'emcc-%d-%s.%s' % (Intermediate.counter, name, suffix))
if isinstance(final, list):
logger.debug('(not saving intermediate %s because deferring linking)' % name)
return
shutil.copyfile(final, name)
Intermediate.counter += 1
def save_intermediate_with_wasm(name, wasm_binary):
if not DEBUG:
return
save_intermediate(name) # save the js
name = os.path.join(shared.get_emscripten_temp_dir(), 'emcc-%d-%s.wasm' % (Intermediate.counter - 1, name))
shutil.copyfile(wasm_binary, name)
class TimeLogger(object):
last = time.time()
@staticmethod
def update():
TimeLogger.last = time.time()
def log_time(name):
"""Log out times for emcc stages"""
if DEBUG:
now = time.time()
logger.debug('emcc step "%s" took %.2f seconds', name, now - TimeLogger.last)
TimeLogger.update()
class EmccOptions(object):
def __init__(self):
self.opt_level = 0
self.debug_level = 0
self.shrink_level = 0
self.requested_debug = ''
self.profiling = False
self.profiling_funcs = False
self.tracing = False
self.emit_symbol_map = False
self.js_opts = None
self.force_js_opts = False
self.llvm_opts = None
self.llvm_lto = None
self.default_cxx_std = '-std=c++03' # Enforce a consistent C++ standard when compiling .cpp files, if user does not specify one on the cmdline.
self.use_closure_compiler = None
self.closure_args = []
self.js_transform = None
self.pre_js = '' # before all js
self.post_js = '' # after all js
self.preload_files = []
self.embed_files = []
self.exclude_files = []
self.ignore_dynamic_linking = False
self.shell_path = shared.path_from_root('src', 'shell.html')
self.source_map_base = ''
self.js_libraries = []
self.emrun = False
self.cpu_profiler = False
self.thread_profiler = False
self.memory_profiler = False
self.save_bc = False
self.memory_init_file = None
self.use_preload_cache = False
self.no_heap_copy = False
self.use_preload_plugins = False
self.proxy_to_worker = False
self.default_object_extension = '.o'
self.valid_abspaths = []
self.separate_asm = False
self.cfi = False
# Specifies the line ending format to use for all generated text files.
# Defaults to using the native EOL on each platform (\r\n on Windows, \n on
# Linux & MacOS)
self.output_eol = os.linesep
self.binaryen_passes = []
# Whether we will expand the full path of any input files to remove any
# symlinks.
self.expand_symlinks = True
def use_source_map(options):
return options.debug_level >= 4
def will_metadce(options):
return options.opt_level >= 3 or options.shrink_level >= 1
class JSOptimizer(object):
def __init__(self, target, options, js_transform_tempfiles, in_temp):
self.queue = []
self.extra_info = {}
self.queue_history = []
self.blacklist = os.environ.get('EMCC_JSOPT_BLACKLIST', '').split(',')
self.minify_whitespace = False
self.cleanup_shell = False
self.target = target
self.opt_level = options.opt_level
self.debug_level = options.debug_level
self.emit_symbol_map = options.emit_symbol_map
self.profiling_funcs = options.profiling_funcs
self.use_closure_compiler = options.use_closure_compiler
self.closure_args = options.closure_args
self.js_transform_tempfiles = js_transform_tempfiles
self.in_temp = in_temp
def flush(self, title='js_opts'):
self.queue = [p for p in self.queue if p not in self.blacklist]
assert not shared.Settings.WASM_BACKEND, 'JSOptimizer should not run with pure wasm output'
if self.extra_info is not None and len(self.extra_info) == 0:
self.extra_info = None
if len(self.queue) and not(not shared.Settings.ASM_JS and len(self.queue) == 1 and self.queue[0] == 'last'):
passes = self.queue[:]
if DEBUG != 2 or len(passes) < 2:
# by assumption, our input is JS, and our output is JS. If a pass is going to run in the native optimizer in C++, then we
# must give it JSON and receive from it JSON
chunks = []
curr = []
for p in passes:
if len(curr) == 0:
curr.append(p)
else:
native = js_optimizer.use_native(p, source_map=use_source_map(self))
last_native = js_optimizer.use_native(curr[-1], source_map=use_source_map(self))
if native == last_native:
curr.append(p)
else:
curr.append('emitJSON')
chunks.append(curr)
curr = ['receiveJSON', p]
if len(curr):
chunks.append(curr)
if len(chunks) == 1:
self.run_passes(chunks[0], title, just_split=False, just_concat=False)
else:
for i, chunk in enumerate(chunks):
self.run_passes(chunk, 'js_opts_' + str(i),
just_split='receiveJSON' in chunk,
just_concat='emitJSON' in chunk)
else:
# DEBUG 2, run each pass separately
extra_info = self.extra_info
for p in passes:
self.queue = [p]
self.flush(p)
self.extra_info = extra_info # flush wipes it
log_time('part of js opts')
self.queue_history += self.queue
self.queue = []
self.extra_info = {}
def run_passes(self, passes, title, just_split, just_concat):
global final
passes = ['asm'] + passes
if shared.Settings.PRECISE_F32:
passes = ['asmPreciseF32'] + passes
if (self.emit_symbol_map or shared.Settings.CYBERDWARF) and 'minifyNames' in passes:
passes += ['symbolMap=' + self.target + '.symbols']
if self.profiling_funcs and 'minifyNames' in passes:
passes += ['profilingFuncs']
if self.minify_whitespace and 'last' in passes:
passes += ['minifyWhitespace']
if self.cleanup_shell and 'last' in passes:
passes += ['cleanup']
logger.debug('applying js optimization passes: %s', ' '.join(passes))
final = shared.Building.js_optimizer(final, passes, use_source_map(self),
self.extra_info, just_split=just_split,
just_concat=just_concat,
output_filename=self.in_temp(os.path.basename(final) + '.jsopted.js'),
extra_closure_args=self.closure_args)
self.js_transform_tempfiles.append(final)
save_intermediate(title, suffix='js' if 'emitJSON' not in passes else 'json')
def do_minify(self):
"""minifies the code.
this is also when we do certain optimizations that must be done right before or after minification
"""
if self.opt_level >= 2:
if self.debug_level < 2 and not self.use_closure_compiler == 2:
self.queue += ['minifyNames']
if self.debug_level == 0:
self.minify_whitespace = True
if self.use_closure_compiler == 1:
self.queue += ['closure']
elif self.debug_level <= 2 and shared.Settings.FINALIZE_ASM_JS and not self.use_closure_compiler:
self.cleanup_shell = True
def embed_memfile(options):
return (shared.Settings.SINGLE_FILE or
(shared.Settings.MEM_INIT_METHOD == 0 and
(not shared.Settings.MAIN_MODULE and
not shared.Settings.SIDE_MODULE and
not use_source_map(options))))
def apply_settings(changes):
"""Take a list of settings in form `NAME=VALUE` and apply them to the global
Settings object.
"""
def standardize_setting_change(key, value):
# Handle aliases in settings flags. These are settings whose name
# has changed.
settings_aliases = {
'BINARYEN': 'WASM',
'BINARYEN_MEM_MAX': 'WASM_MEM_MAX',
# TODO: change most (all?) other BINARYEN* names to WASM*
}
key = settings_aliases.get(key, key)
# boolean NO_X settings are aliases for X
# (note that *non*-boolean setting values have special meanings,
# and we can't just flip them, so leave them as-is to be
# handled in a special way later)
if key.startswith('NO_') and value in ('0', '1'):
key = key[3:]
value = str(1 - int(value))
return key, value
for change in changes:
key, value = change.split('=', 1)
key, value = standardize_setting_change(key, value)
# In those settings fields that represent amount of memory, translate suffixes to multiples of 1024.
if key in ('TOTAL_STACK', 'TOTAL_MEMORY', 'MEMORY_GROWTH_STEP', 'GL_MAX_TEMP_BUFFER_SIZE',
'WASM_MEM_MAX', 'DEFAULT_PTHREAD_STACK_SIZE'):
value = str(shared.expand_byte_size_suffixes(value))
if value[0] == '@':
if key not in DEFERRED_RESPONSE_FILES:
value = open(value[1:]).read()
else:
value = value.replace('\\', '\\\\')
try:
setattr(shared.Settings, key, parse_value(value))
except Exception as e:
exit_with_error('a problem occured in evaluating the content after a "-s", specifically "%s": %s', change, str(e))
if shared.Settings.WASM_BACKEND and key == 'BINARYEN_TRAP_MODE':
exit_with_error('BINARYEN_TRAP_MODE is not supported by the LLVM wasm backend')
if key == 'EXPORTED_FUNCTIONS':
# used for warnings in emscripten.py
shared.Settings.ORIGINAL_EXPORTED_FUNCTIONS = shared.Settings.EXPORTED_FUNCTIONS[:]
def find_output_arg(args):
"""Find and remove any -o arguments. The final one takes precedence.
Return the final -o target along with the remaining (non-o) arguments.
"""
outargs = []
specified_target = None
use_next = False
for arg in args:
if use_next:
specified_target = arg
use_next = False
continue
if arg == '-o':
use_next = True
elif arg.startswith('-o'):
specified_target = arg[2:]
else:
outargs.append(arg)
return specified_target, outargs
def do_emscripten(infile, memfile, js_libraries):
# Run Emscripten
outfile = infile + '.o.js'
with ToolchainProfiler.profile_block('emscripten.py'):
emscripten.run(infile, outfile, memfile, js_libraries)
# Detect compilation crashes and errors
assert os.path.exists(outfile), 'Emscripten failed to generate .js'
return outfile
#
# Main run() function
#
def run(args):
global final
target = None
# Additional compiler flags that we treat as if they were passed to us on the
# commandline
EMCC_CFLAGS = os.environ.get('EMCC_CFLAGS')
if DEBUG:
cmd = ' '.join(args)
if EMCC_CFLAGS:
cmd += ' + ' + EMCC_CFLAGS
logger.warning('invocation: ' + cmd + ' (in ' + os.getcwd() + ')')
if EMCC_CFLAGS:
args.extend(shlex.split(EMCC_CFLAGS))
# Strip args[0] (program name)
args = args[1:]
if DEBUG and LEAVE_INPUTS_RAW:
logger.warning('leaving inputs raw')
if '--emscripten-cxx' in args:
run_via_emxx = True
args = [x for x in args if x != '--emscripten-cxx']
else:
run_via_emxx = False
misc_temp_files = shared.configuration.get_temp_files()
# Handle some global flags
# read response files very early on
try:
args = substitute_response_files(args)
except IOError as e:
exit_with_error(e)
if '--help' in args:
# Documentation for emcc and its options must be updated in:
# site/source/docs/tools_reference/emcc.rst
# A prebuilt local version of the documentation is available at:
# site/build/text/docs/tools_reference/emcc.txt
# (it is read from there and printed out when --help is invoked)
# You can also build docs locally as HTML or other formats in site/
# An online HTML version (which may be of a different version of Emscripten)
# is up at http://kripken.github.io/emscripten-site/docs/tools_reference/emcc.html
print('''%s
------------------------------------------------------------------
emcc: supported targets: llvm bitcode, javascript, NOT elf
(autoconf likes to see elf above to enable shared object support)
''' % (open(shared.path_from_root('site', 'build', 'text', 'docs', 'tools_reference', 'emcc.txt')).read()))
return 0
if '--version' in args:
try:
revision = run_process(['git', 'show'], stdout=PIPE, stderr=PIPE, cwd=shared.path_from_root()).stdout.splitlines()[0]
except Exception:
revision = '(unknown revision)'
print('''emcc (Emscripten gcc/clang-like replacement) %s (%s)
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
''' % (shared.EMSCRIPTEN_VERSION, revision))
return 0
if len(args) == 1 and args[0] == '-v': # -v with no inputs
# autoconf likes to see 'GNU' in the output to enable shared object support
print('emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) %s' % shared.EMSCRIPTEN_VERSION, file=sys.stderr)
code = run_process([shared.CLANG_CC, '-v'], check=False).returncode
shared.check_sanity(force=True)
return code
shared.check_sanity(force=DEBUG)
# This check comes after check_sanity because test_sanity expects this.
if not args:
logger.warning('no input files')
return 1
if '-dumpmachine' in args:
print(shared.get_llvm_target())
return 0
if '-dumpversion' in args: # gcc's doc states "Print the compiler version [...] and don't do anything else."
print(shared.EMSCRIPTEN_VERSION)
return 0
if '--cflags' in args:
# fake running the command, to see the full args we pass to clang
debug_env = os.environ.copy()
args = [x for x in args if x != '--cflags']
with misc_temp_files.get_file(suffix='.o') as temp_target:
input_file = 'hello_world.c'
cmd = [shared.PYTHON, sys.argv[0], shared.path_from_root('tests', input_file), '-v', '-c', '-o', temp_target] + args
proc = run_process(cmd, stderr=PIPE, env=debug_env, check=False)
if proc.returncode != 0:
print(proc.stderr)
exit_with_error('error getting cflags')
lines = [x for x in proc.stderr.splitlines() if shared.CLANG_CC in x and input_file in x]
parts = shlex.split(lines[0].replace('\\', '\\\\'))
parts = [x for x in parts if x not in ['-c', '-o', '-v', '-emit-llvm'] and input_file not in x and temp_target not in x]
print(' '.join(shared.Building.doublequote_spaces(parts[1:])))
return 0
# Default to using C++ even when run as `emcc`.
# This means that emcc will act as a C++ linker when no source files are
# specified. However, when a C source is specified we do default to C.
# This differs to clang and gcc where the default is always C unless run as
# clang++/g++.
use_cxx = True
def get_language_mode(args):
return_next = False
for item in args:
if return_next:
return item
if item == '-x':
return_next = True
continue
if item.startswith('-x'):
return item[2:]
return None
def has_c_source(args):
for a in args:
if a[0] != '-' and a.endswith(C_ENDINGS + OBJC_ENDINGS):
return True
return False
language_mode = get_language_mode(args)
has_fixed_language_mode = language_mode is not None
if language_mode == 'c':
use_cxx = False
if not has_fixed_language_mode:
if not run_via_emxx and has_c_source(args):
use_cxx = False
def is_minus_s_for_emcc(args, i):
# -s OPT=VALUE or -s OPT are interpreted as emscripten flags.
# -s by itself is a linker option (alias for --strip-all)
assert args[i] == '-s'
if len(args) > i + 1:
arg = args[i + 1]
if arg.split('=')[0].isupper():
return True
logger.debug('treating -s as linker option and not as -s OPT=VALUE for js compilation')
return False
# If this is a configure-type thing, do not compile to JavaScript, instead use clang
# to compile to a native binary (using our headers, so things make sense later)
CONFIGURE_CONFIG = (os.environ.get('EMMAKEN_JUST_CONFIGURE') or 'conftest.c' in args) and not os.environ.get('EMMAKEN_JUST_CONFIGURE_RECURSE')
CMAKE_CONFIG = 'CMakeFiles/cmTryCompileExec.dir' in ' '.join(args)# or 'CMakeCCompilerId' in ' '.join(args)
if CONFIGURE_CONFIG or CMAKE_CONFIG:
# XXX use this to debug configure stuff. ./configure's generally hide our
# normal output including stderr so we write to a file
debug_configure = 0
# Whether we fake configure tests using clang - the local, native compiler -
# or not. if not we generate JS and use node with a shebang
# Neither approach is perfect, you can try both, but may need to edit
# configure scripts in some cases
# By default we configure in js, which can break on local filesystem access,
# etc., but is otherwise accurate so we
# disable this if we think we have to. A value of '2' here will force JS
# checks in all cases. In summary:
# 0 - use native compilation for configure checks
# 1 - use js when we think it will work
# 2 - always use js for configure checks
use_js = int(os.environ.get('EMCONFIGURE_JS', '2'))
if debug_configure:
tempout = '/tmp/emscripten_temp/out'
if not os.path.exists(tempout):
open(tempout, 'w').write('//\n')
src = None
for arg in args:
if arg.endswith(SOURCE_ENDINGS):
try:
src = open(arg).read()
if debug_configure:
open(tempout, 'a').write('============= ' + arg + '\n' + src + '\n=============\n\n')
except IOError:
pass
elif arg.endswith('.s'):
if debug_configure:
open(tempout, 'a').write('(compiling .s assembly, must use clang\n')
if use_js == 1:
use_js = 0
elif arg == '-E' or arg == '-M' or arg == '-MM':
if use_js == 1:
use_js = 0
if src:
if 'fopen' in src and '"w"' in src:
if use_js == 1:
use_js = 0 # we cannot write to files from js!
if debug_configure:
open(tempout, 'a').write('Forcing clang since uses fopen to write\n')
# if CONFIGURE_CC is defined, use that. let's you use local gcc etc. if you need that
compiler = os.environ.get('CONFIGURE_CC')
if not compiler:
compiler = shared.EMXX if use_js else shared.CLANG_CPP
if 'CXXCompiler' not in ' '.join(args) and not use_cxx:
compiler = shared.to_cc(compiler)
def filter_emscripten_options(argv):
skip_next = False
for idx, arg in enumerate(argv):
if skip_next:
skip_next = False
continue
if not use_js and arg == '-s' and is_minus_s_for_emcc(argv, idx):
# skip -s X=Y if not using js for configure
skip_next = True
continue
if use_js or arg != '--tracing':
yield arg
if compiler in (shared.EMCC, shared.EMXX):
compiler = [shared.PYTHON, compiler]
else:
compiler = [compiler]
cmd = compiler + list(filter_emscripten_options(args))
if not use_js:
cmd += shared.emsdk_cflags() + ['-D__EMSCRIPTEN__']
# The preprocessor define EMSCRIPTEN is deprecated. Don't pass it to code
# in strict mode. Code should use the define __EMSCRIPTEN__ instead.
if not shared.Settings.STRICT:
cmd += ['-DEMSCRIPTEN']
if use_js:
# configure tests want a more shell-like style, where we emit return codes on exit()
cmd += ['-s', 'NO_EXIT_RUNTIME=0']
# use node.js raw filesystem access, to behave just like a native executable
cmd += ['-s', 'NODERAWFS=1']
logger.debug('just configuring: ' + ' '.join(cmd))
if debug_configure:
open(tempout, 'a').write('emcc, just configuring: ' + ' '.join(cmd) + '\n\n')
if not use_js:
return run_process(cmd, check=False).returncode
only_object = '-c' in cmd
for i in reversed(range(len(cmd) - 1)): # Last -o directive should take precedence, if multiple are specified
if cmd[i] == '-o':
if not only_object:
cmd[i + 1] += '.js'
target = cmd[i + 1]
break
if not target:
target = 'a.out.js'
os.environ['EMMAKEN_JUST_CONFIGURE_RECURSE'] = '1'
ret = run_process(cmd, check=False).returncode
os.environ['EMMAKEN_JUST_CONFIGURE_RECURSE'] = ''
if not os.path.exists(target):
# note that emcc -c will cause target to have the wrong value here;
# but then, we don't care about bitcode outputs anyhow, below, so
# skipping returning early is fine
return ret
if target.endswith('.js'):
shutil.copyfile(target, unsuffixed(target))
target = unsuffixed(target)
if not target.endswith(OBJECT_FILE_ENDINGS):
src = open(target).read()
full_node = ' '.join(shared.NODE_JS)
if os.path.sep not in full_node:
full_node = '/usr/bin/' + full_node # TODO: use whereis etc. And how about non-*NIX?
open(target, 'w').write('#!' + full_node + '\n' + src) # add shebang
try:
os.chmod(target, stat.S_IMODE(os.stat(target).st_mode) | stat.S_IXUSR) # make executable
except OSError:
pass # can fail if e.g. writing the executable to /dev/null
return ret
CXX = os.environ.get('EMMAKEN_COMPILER', shared.CLANG_CPP)
CC = shared.to_cc(CXX)
EMMAKEN_CFLAGS = os.environ.get('EMMAKEN_CFLAGS')
if EMMAKEN_CFLAGS:
args += shlex.split(EMMAKEN_CFLAGS)
# ---------------- Utilities ---------------
def suffix(name):
"""Return the file extension"""
return os.path.splitext(name)[1]
seen_names = {}
def uniquename(name):
if name not in seen_names:
seen_names[name] = str(len(seen_names))
return unsuffixed(name) + '_' + seen_names[name] + suffix(name)
# ---------------- End configs -------------
# Check if a target is specified on the command line
specified_target, args = find_output_arg(args)
# specified_target is the user-specified one, target is what we will generate
if specified_target:
target = specified_target
# check for the existence of the output directory now, to avoid having
# to do so repeatedly when each of the various output files (.mem, .wasm,
# etc) are written. This gives a more useful error message than the
# IOError and python backtrace that users would otherwise see.
dirname = os.path.dirname(target)
if dirname and not os.path.isdir(dirname):
exit_with_error("specified output file (%s) is in a directory that does not exist" % target)
else:
target = 'a.out.js'
shared.Settings.TARGET_BASENAME = target_basename = unsuffixed_basename(target)
final_suffix = suffix(target)
temp_dir = shared.get_emscripten_temp_dir()
def in_temp(name):
return os.path.join(temp_dir, os.path.basename(name))
def get_file_suffix(filename):
"""Parses the essential suffix of a filename, discarding Unix-style version
numbers in the name. For example for 'libz.so.1.2.8' returns '.so'"""
if filename in SPECIAL_ENDINGLESS_FILENAMES:
return filename
while filename:
filename, suffix = os.path.splitext(filename)
if not suffix[1:].isdigit():
return suffix
return ''
def optimizing(opts):
return '-O0' not in opts
with ToolchainProfiler.profile_block('parse arguments and setup'):
## Parse args
newargs = list(args)
# Scan and strip emscripten specific cmdline warning flags.
# This needs to run before other cmdline flags have been parsed, so that
# warnings are properly printed during arg parse.
newargs = shared.WarningManager.capture_warnings(newargs)
for i in range(len(newargs)):
if newargs[i] in ('-l', '-L', '-I'):
# Scan for individual -l/-L/-I arguments and concatenate the next arg on
# if there is no suffix
newargs[i] += newargs[i + 1]
newargs[i + 1] = ''
options, settings_changes, newargs = parse_args(newargs)
if use_cxx:
clang_compiler = CXX
# If user did not specify a default -std for C++ code, specify the emscripten default.
if options.default_cxx_std:
newargs += [options.default_cxx_std]
else:
# Compiling C code with .c files, don't enforce a default C++ std.
clang_compiler = CC
if '-print-search-dirs' in newargs:
return run_process([clang_compiler, '-print-search-dirs'], check=False).returncode
if options.emrun:
options.pre_js += open(shared.path_from_root('src', 'emrun_prejs.js')).read() + '\n'
options.post_js += open(shared.path_from_root('src', 'emrun_postjs.js')).read() + '\n'
# emrun mode waits on program exit
shared.Settings.EXIT_RUNTIME = 1
if options.cpu_profiler:
options.post_js += open(shared.path_from_root('src', 'cpuprofiler.js')).read() + '\n'
if options.memory_profiler:
shared.Settings.MEMORYPROFILER = 1
if options.thread_profiler:
options.post_js += open(shared.path_from_root('src', 'threadprofiler.js')).read() + '\n'
if options.js_opts is None:
options.js_opts = options.opt_level >= 2
if options.llvm_opts is None:
options.llvm_opts = LLVM_OPT_LEVEL[options.opt_level]
elif type(options.llvm_opts) == int:
options.llvm_opts = ['-O%d' % options.llvm_opts]
if options.memory_init_file is None:
options.memory_init_file = options.opt_level >= 2
# TODO: support source maps with js_transform
if options.js_transform and use_source_map(options):
logger.warning('disabling source maps because a js transform is being done')
options.debug_level = 3
if DEBUG:
start_time = time.time() # done after parsing arguments, which might affect debug state
for i in range(len(newargs)):
if newargs[i] == '-s':
if is_minus_s_for_emcc(newargs, i):
key = newargs[i + 1]
# If not = is specified default to 1
if '=' not in key:
key += '=1'
settings_changes.append(key)
newargs[i] = newargs[i + 1] = ''
if key == 'WASM_BACKEND=1':
exit_with_error('do not set -s WASM_BACKEND, instead set EMCC_WASM_BACKEND=1 in the environment')
newargs = [arg for arg in newargs if arg]
settings_key_changes = set()
for s in settings_changes:
key, value = s.split('=', 1)
settings_key_changes.add(key)
# Find input files
# These three arrays are used to store arguments of different types for
# type-specific processing. In order to shuffle the arguments back together
# after processing, all of these arrays hold tuples (original_index, value).
# Note that the index part of the tuple can have a fractional part for input
# arguments that expand into multiple processed arguments, as in -Wl,-f1,-f2.
input_files = []
libs = []
link_flags = []
# All of the above arg lists entries contain indexes into the full argument
# list. In order to add extra implicit args (embind.cc, etc) below, we keep a
# counter for the next index that should be used.
next_arg_index = len(newargs)
has_source_inputs = False
has_header_inputs = False
lib_dirs = []
has_dash_c = '-c' in newargs
has_dash_S = '-S' in newargs
executable_endings = JS_CONTAINING_ENDINGS + ('.wasm',)
compile_only = has_dash_c or has_dash_S
link_to_object = final_suffix not in executable_endings
def add_link_flag(i, f):
# Filter out libraries that musl includes in libc itself, or which we
# otherwise provide implicitly.
if f in ('-lm', '-lrt', '-ldl', '-lpthread'):
return
if f.startswith('-l'):
libs.append((i, f[2:]))
if f.startswith('-L'):
lib_dirs.append(f[2:])
link_flags.append((i, f))
# find input files this a simple heuristic. we should really analyze
# based on a full understanding of gcc params, right now we just assume that
# what is left contains no more |-x OPT| things
for i in range(len(newargs)):
arg = newargs[i]
if i > 0:
prev = newargs[i - 1]
if prev in ('-MT', '-MF', '-MQ', '-D', '-U', '-o', '-x',
'-Xpreprocessor', '-include', '-imacros', '-idirafter',
'-iprefix', '-iwithprefix', '-iwithprefixbefore',
'-isysroot', '-imultilib', '-A', '-isystem', '-iquote',
'-install_name', '-compatibility_version',
'-current_version', '-I', '-L', '-include-pch'):
continue # ignore this gcc-style argument
if options.expand_symlinks and os.path.islink(arg) and get_file_suffix(os.path.realpath(arg)) in SOURCE_ENDINGS + OBJECT_FILE_ENDINGS + DYNAMICLIB_ENDINGS + ASSEMBLY_ENDINGS + HEADER_ENDINGS:
arg = os.path.realpath(arg)
if not arg.startswith('-'):
if not os.path.exists(arg):
exit_with_error('%s: No such file or directory ("%s" was expected to be an input file, based on the commandline arguments provided)', arg, arg)
file_suffix = get_file_suffix(arg)
if file_suffix in SOURCE_ENDINGS + OBJECT_FILE_ENDINGS + DYNAMICLIB_ENDINGS + ASSEMBLY_ENDINGS + HEADER_ENDINGS or shared.Building.is_ar(arg): # we already removed -o <target>, so all these should be inputs
newargs[i] = ''
if file_suffix.endswith(SOURCE_ENDINGS):
input_files.append((i, arg))
has_source_inputs = True
elif file_suffix.endswith(HEADER_ENDINGS):
input_files.append((i, arg))
has_header_inputs = True
elif file_suffix.endswith(ASSEMBLY_ENDINGS) or shared.Building.is_bitcode(arg) or shared.Building.is_ar(arg):
input_files.append((i, arg))
elif shared.Building.is_wasm(arg):
if not shared.Settings.WASM_BACKEND:
exit_with_error('fastcomp is not compatible with wasm object files:' + arg)
input_files.append((i, arg))
elif file_suffix.endswith(STATICLIB_ENDINGS + DYNAMICLIB_ENDINGS):
# if it's not, and it's a library, just add it to libs to find later
libname = unsuffixed_basename(arg)
for prefix in LIB_PREFIXES:
if not prefix:
continue
if libname.startswith(prefix):
libname = libname[len(prefix):]
break
libs.append((i, libname))
newargs[i] = ''
else:
logger.warning(arg + ' is not a valid input file')
elif file_suffix.endswith(STATICLIB_ENDINGS):
if not shared.Building.is_ar(arg):
if shared.Building.is_bitcode(arg):
message = arg + ': File has a suffix of a static library ' + str(STATICLIB_ENDINGS) + ', but instead is an LLVM bitcode file! When linking LLVM bitcode files, use one of the suffixes ' + str(OBJECT_FILE_ENDINGS)
else:
message = arg + ': Unknown format, not a static library!'
exit_with_error(message)
else:
if has_fixed_language_mode:
newargs[i] = ''
input_files.append((i, arg))
has_source_inputs = True
else:
exit_with_error(arg + ": Input file has an unknown suffix, don't know what to do with it!")
elif arg.startswith('-L'):
add_link_flag(i, arg)
newargs[i] = ''
elif arg.startswith('-l'):
add_link_flag(i, arg)
newargs[i] = ''
elif arg.startswith('-Wl,'):
# Multiple comma separated link flags can be specified. Create fake
# fractional indices for these: -Wl,a,b,c,d at index 4 becomes:
# (4, a), (4.25, b), (4.5, c), (4.75, d)
link_flags_to_add = arg.split(',')[1:]
for flag_index, flag in enumerate(link_flags_to_add):
add_link_flag(i + float(flag_index) / len(link_flags_to_add), flag)
newargs[i] = ''
elif arg == '-s':
# -s and some other compiler flags are normally passed onto the linker
# TODO(sbc): Pass this and other flags through when using lld
# link_flags.append((i, arg))
newargs[i] = ''
newargs = [a for a in newargs if a]
if '-fno-rtti' in newargs:
shared.Settings.USE_RTTI = 0
if has_dash_c or has_dash_S:
assert has_source_inputs or has_header_inputs, 'Must have source code or header inputs to use -c or -S'
if has_dash_c:
if '-emit-llvm' in newargs:
final_suffix = '.bc'
else:
final_suffix = options.default_object_extension
elif has_dash_S:
if '-emit-llvm' in newargs:
final_suffix = '.ll'
else:
final_suffix = '.s'
target = target_basename + final_suffix
if len(input_files) > 1 and specified_target:
exit_with_error('cannot specify -o with -c/-S and multiple source files')
if '-E' in newargs:
final_suffix = '.eout' # not bitcode, not js; but just result from preprocessing stage of the input file
if '-M' in newargs or '-MM' in newargs:
final_suffix = '.mout' # not bitcode, not js; but just dependency rule of the input file
# target is now finalized, can finalize other _target s
if final_suffix == '.mjs':
shared.Settings.EXPORT_ES6 = 1
shared.Settings.MODULARIZE = 1
js_target = target
else:
js_target = unsuffixed(target) + '.js'
asm_target = unsuffixed(js_target) + '.asm.js' # might not be used, but if it is, this is the name
wasm_text_target = asm_target.replace('.asm.js', '.wast') # ditto, might not be used
wasm_binary_target = asm_target.replace('.asm.js', '.wasm') # ditto, might not be used
wasm_source_map_target = wasm_binary_target + '.map'
if final_suffix == '.html' and not options.separate_asm and 'PRECISE_F32=2' in settings_changes:
options.separate_asm = True
logger.warning('forcing separate asm output (--separate-asm), because -s PRECISE_F32=2 was passed.')
if options.separate_asm:
shared.Settings.SEPARATE_ASM = shared.JS.get_subresource_location(asm_target)
# Libraries are searched before settings_changes are applied, so apply the
# value for STRICT from command line already now.
def get_last_setting_change(setting):
return ([None] + [x for x in settings_changes if x.startswith(setting + '=')])[-1]
strict_cmdline = get_last_setting_change('STRICT')
if strict_cmdline:
shared.Settings.STRICT = int(strict_cmdline.split('=', 1)[1])
if options.separate_asm and final_suffix != '.html':
shared.WarningManager.warn('SEPARATE_ASM')
# Apply optimization level settings
shared.Settings.apply_opt_level(opt_level=options.opt_level, shrink_level=options.shrink_level, noisy=True)
# For users that opt out of WARN_ON_UNDEFINED_SYMBOLS we assume they also
# want to opt out of ERROR_ON_UNDEFINED_SYMBOLS.
if 'WARN_ON_UNDEFINED_SYMBOLS=0' in settings_changes:
shared.Settings.ERROR_ON_UNDEFINED_SYMBOLS = 0
# Set ASM_JS default here so that we can override it from the command line.
shared.Settings.ASM_JS = 1 if options.opt_level > 0 else 2
# Apply -s settings in newargs here (after optimization levels, so they can override them)
apply_settings(settings_changes)
shared.verify_settings()
using_lld = shared.Settings.WASM_BACKEND and not (link_to_object and not shared.Settings.WASM_OBJECT_FILES)
def filter_out_dynamic_libs(inputs):
# If not compiling to JS, then we are compiling to an intermediate bitcode
# objects or library, so ignore dynamic linking, since multiple dynamic
# linkings can interfere with each other
if get_file_suffix(target) not in JS_CONTAINING_ENDINGS or options.ignore_dynamic_linking:
def check(input_file):
if get_file_suffix(input_file) in DYNAMICLIB_ENDINGS:
if not options.ignore_dynamic_linking:
logger.warning('ignoring dynamic library %s because not compiling to JS or HTML, remember to link it when compiling to JS or HTML at the end', os.path.basename(input_file))
return False
else:
return True
return [f for f in inputs if check(f[1])]
return inputs
input_files = filter_out_dynamic_libs(input_files)
if len(input_files) == 0:
exit_with_error('no input files\nnote that input files without a known suffix are ignored, make sure your input files end with one of: ' + str(SOURCE_ENDINGS + OBJECT_FILE_ENDINGS + DYNAMICLIB_ENDINGS + STATICLIB_ENDINGS + ASSEMBLY_ENDINGS + HEADER_ENDINGS))
# Note the exports the user requested
shared.Building.user_requested_exports = shared.Settings.EXPORTED_FUNCTIONS[:]
# -s ASSERTIONS=1 implies the heaviest stack overflow check mode. Set the implication here explicitly to avoid having to
# do preprocessor "#if defined(ASSERTIONS) || defined(STACK_OVERFLOW_CHECK)" in .js files, which is not supported.
if shared.Settings.ASSERTIONS:
shared.Settings.STACK_OVERFLOW_CHECK = 2
if shared.Settings.WASM_OBJECT_FILES and not shared.Settings.WASM_BACKEND:
if 'WASM_OBJECT_FILES=1' in settings_changes:
exit_with_error('WASM_OBJECT_FILES can only be used with wasm backend')
shared.Settings.WASM_OBJECT_FILES = 0
if shared.Settings.STRICT:
shared.Settings.DISABLE_DEPRECATED_FIND_EVENT_TARGET_BEHAVIOR = 1
shared.Settings.STRICT_JS = 1
shared.Settings.AUTO_JS_LIBRARIES = 0
if AUTODEBUG:
shared.Settings.AUTODEBUG = 1
# Use settings
if options.debug_level > 1 and options.use_closure_compiler:
logger.warning('disabling closure because debug info was requested')
options.use_closure_compiler = False
if shared.Settings.EMTERPRETIFY_FILE and shared.Settings.SINGLE_FILE:
exit_with_error('cannot have both EMTERPRETIFY_FILE and SINGLE_FILE enabled at the same time')
if options.use_closure_compiler and not shared.Settings.DYNAMIC_EXECUTION:
exit_with_error('cannot have both NO_DYNAMIC_EXECUTION and closure compiler enabled at the same time')
if options.emrun:
if shared.Settings.MINIMAL_RUNTIME:
exit_with_error('--emrun is not compatible with -s MINIMAL_RUNTIME=1')
shared.Settings.EXPORTED_RUNTIME_METHODS.append('addOnExit')
if options.use_closure_compiler:
shared.Settings.USE_CLOSURE_COMPILER = options.use_closure_compiler
if not shared.check_closure_compiler():
exit_with_error('fatal: closure compiler is not configured correctly')
if options.use_closure_compiler == 2 and shared.Settings.ASM_JS == 1:
shared.WarningManager.warn('ALMOST_ASM', 'not all asm.js optimizations are possible with --closure 2, disabling those - your code will be run more slowly')
shared.Settings.ASM_JS = 2
if shared.Settings.MAIN_MODULE:
assert not shared.Settings.SIDE_MODULE
if shared.Settings.MAIN_MODULE != 2:
shared.Settings.INCLUDE_FULL_LIBRARY = 1
elif shared.Settings.SIDE_MODULE:
assert not shared.Settings.MAIN_MODULE
options.memory_init_file = False # memory init file is not supported with asm.js side modules, must be executable synchronously (for dlopen)
if shared.Settings.MAIN_MODULE or shared.Settings.SIDE_MODULE:
assert shared.Settings.ASM_JS, 'module linking requires asm.js output (-s ASM_JS=1)'
if shared.Settings.MAIN_MODULE != 2 and shared.Settings.SIDE_MODULE != 2:
shared.Settings.LINKABLE = 1
shared.Settings.RELOCATABLE = 1
assert not options.use_closure_compiler, 'cannot use closure compiler on shared modules'
# shared modules need memory utilities to allocate their memory
shared.Settings.EXPORTED_RUNTIME_METHODS += [
'allocate',
'getMemory',
]
if shared.Settings.RELOCATABLE:
shared.Settings.ALLOW_TABLE_GROWTH = 1
# Reconfigure the cache now that settings have been applied. Some settings
# such as WASM_OBJECT_FILES and SIDE_MODULE/MAIN_MODULE effect which cache
# directory we use.
shared.reconfigure_cache()
if not compile_only:
ldflags = shared.emsdk_ldflags(newargs)
for f in ldflags:
newargs.append(f)
add_link_flag(len(newargs), f)
if not shared.Settings.STRICT:
# The preprocessor define EMSCRIPTEN is deprecated. Don't pass it to code
# in strict mode. Code should use the define __EMSCRIPTEN__ instead.
newargs += ['-DEMSCRIPTEN']
newargs = shared.COMPILER_OPTS + shared.get_cflags(newargs) + newargs
def is_supported_link_flag(f):
if f in SUPPORTED_LINKER_FLAGS:
return True
if using_lld:
# Add flags here to allow -Wl, options to be passed all the way through
# to the linker.
valid_prefixs = ('-l', '-L', '--trace-symbol', '--trace')
if any(f.startswith(prefix) for prefix in valid_prefixs):
return True
else:
# Silently ignore -l/-L flags when not using lld. If using lld allow
# them to pass through the linker
if f.startswith('-l') or f.startswith('-L'):
return False
logger.warning('ignoring unsupported linker flag: `%s`', f)
return False
link_flags = [f for f in link_flags if is_supported_link_flag(f[1])]
if shared.Settings.USE_PTHREADS:
# These runtime methods are called from worker.js
shared.Settings.EXPORTED_RUNTIME_METHODS += ['establishStackSpace', 'dynCall_ii']
if shared.Settings.MODULARIZE_INSTANCE:
shared.Settings.MODULARIZE = 1
if shared.Settings.MODULARIZE:
assert not options.proxy_to_worker, '-s MODULARIZE=1 and -s MODULARIZE_INSTANCE=1 are not compatible with --proxy-to-worker (if you want to run in a worker with -s MODULARIZE=1, you likely want to do the worker side setup manually)'
# MODULARIZE's .then() method uses onRuntimeInitialized currently, so make sure
# it is expected to be used.
shared.Settings.INCOMING_MODULE_JS_API += ['onRuntimeInitialized']
if shared.Settings.EMULATE_FUNCTION_POINTER_CASTS:
shared.Settings.ALIASING_FUNCTION_POINTERS = 0
if shared.Settings.LEGACY_VM_SUPPORT:
# legacy vms don't have wasm
assert not shared.Settings.WASM or shared.Settings.WASM2JS, 'LEGACY_VM_SUPPORT is only supported for asm.js, and not wasm. Build with -s WASM=0'
shared.Settings.POLYFILL_OLD_MATH_FUNCTIONS = 1
shared.Settings.WORKAROUND_IOS_9_RIGHT_SHIFT_BUG = 1
shared.Settings.WORKAROUND_OLD_WEBGL_UNIFORM_UPLOAD_IGNORED_OFFSET_BUG = 1
# Silently drop any individual backwards compatibility emulation flags that are known never to occur on browsers that support WebAssembly.
if shared.Settings.WASM and not shared.Settings.WASM2JS:
shared.Settings.POLYFILL_OLD_MATH_FUNCTIONS = 0
shared.Settings.WORKAROUND_IOS_9_RIGHT_SHIFT_BUG = 0
shared.Settings.WORKAROUND_OLD_WEBGL_UNIFORM_UPLOAD_IGNORED_OFFSET_BUG = 0
if shared.Settings.STB_IMAGE and final_suffix in JS_CONTAINING_ENDINGS:
input_files.append((next_arg_index, shared.path_from_root('third_party', 'stb_image.c')))
next_arg_index += 1
shared.Settings.EXPORTED_FUNCTIONS += ['_stbi_load', '_stbi_load_from_memory', '_stbi_image_free']
# stb_image 2.x need to have STB_IMAGE_IMPLEMENTATION defined to include the implementation when compiling
newargs.append('-DSTB_IMAGE_IMPLEMENTATION')
forced_stdlibs = []
if shared.Settings.ASMFS and final_suffix in JS_CONTAINING_ENDINGS:
forced_stdlibs.append('libasmfs')
newargs.append('-D__EMSCRIPTEN_ASMFS__=1')
next_arg_index += 1
shared.Settings.FILESYSTEM = 0
shared.Settings.SYSCALLS_REQUIRE_FILESYSTEM = 0
shared.Settings.FETCH = 1
options.js_libraries.append(shared.path_from_root('src', 'library_asmfs.js'))
if shared.Settings.FETCH and final_suffix in JS_CONTAINING_ENDINGS:
forced_stdlibs.append('libfetch')
next_arg_index += 1
options.js_libraries.append(shared.path_from_root('src', 'library_fetch.js'))
if shared.Settings.USE_PTHREADS:
shared.Settings.FETCH_WORKER_FILE = unsuffixed(os.path.basename(target)) + '.fetch.js'
if not shared.Settings.USE_PTHREADS or not shared.Settings.FETCH:
shared.Settings.USE_FETCH_WORKER = 0
# In asm.js+pthreads we can use a fetch worker, which is made from the main
# asm.js code. That lets us do sync operations by blocking on the worker etc.
# In the wasm backend we don't have a fetch worker implemented yet, however,
# we can still do basic synchronous fetches in the same places: if we can
# block on another thread then we aren't the main thread, and if we aren't
# the main thread then synchronous xhrs are legitimate.
if shared.Settings.FETCH and shared.Settings.WASM_BACKEND:
shared.Settings.USE_FETCH_WORKER = 0
if shared.Settings.DEMANGLE_SUPPORT:
shared.Settings.EXPORTED_FUNCTIONS += ['___cxa_demangle']
forced_stdlibs.append('libc++abi')
if shared.Settings.EMBIND:
forced_stdlibs.append('libembind')
if not shared.Settings.MINIMAL_RUNTIME:
# Always need malloc and free to be kept alive and exported, for internal use and other modules
shared.Settings.EXPORTED_FUNCTIONS += ['_malloc', '_free']
if shared.Settings.WASM_BACKEND:
# setjmp/longjmp and exception handling JS code depends on this so we
# include it by default. Should be eliminated by meta-DCE if unused.
shared.Settings.EXPORTED_FUNCTIONS += ['_setThrew']
if shared.Settings.RELOCATABLE and not shared.Settings.DYNAMIC_EXECUTION:
exit_with_error('cannot have both DYNAMIC_EXECUTION=0 and RELOCATABLE enabled at the same time, since RELOCATABLE needs to eval()')
if shared.Settings.SIDE_MODULE and shared.Settings.GLOBAL_BASE != -1:
exit_with_error('Cannot set GLOBAL_BASE when building SIDE_MODULE')
if shared.Settings.RELOCATABLE:
if 'EMULATED_FUNCTION_POINTERS' not in settings_key_changes and not shared.Settings.WASM_BACKEND:
shared.Settings.EMULATED_FUNCTION_POINTERS = 2 # by default, use optimized function pointer emulation
shared.Settings.ERROR_ON_UNDEFINED_SYMBOLS = 0
shared.Settings.WARN_ON_UNDEFINED_SYMBOLS = 0
if shared.Settings.ASYNCIFY:
if not shared.Settings.WASM_BACKEND:
exit_with_error('ASYNCIFY has been removed from fastcomp. There is a new implementation which can be used in the upstream wasm backend.')
if shared.Settings.EMTERPRETIFY:
shared.Settings.FINALIZE_ASM_JS = 0
shared.Settings.SIMPLIFY_IFS = 0 # this is just harmful for emterpreting
shared.Settings.EXPORTED_FUNCTIONS += ['emterpret']
if not options.js_opts:
logger.debug('enabling js opts for EMTERPRETIFY')
options.js_opts = True
options.force_js_opts = True
if options.use_closure_compiler == 2:
exit_with_error('EMTERPRETIFY requires valid asm.js, and is incompatible with closure 2 which disables that')
assert not use_source_map(options), 'EMTERPRETIFY is not compatible with source maps (maps are not useful in emterpreted code, and splitting out non-emterpreted source maps is not yet implemented)'
if shared.Settings.DISABLE_EXCEPTION_THROWING and not shared.Settings.DISABLE_EXCEPTION_CATCHING:
exit_with_error("DISABLE_EXCEPTION_THROWING was set (probably from -fno-exceptions) but is not compatible with enabling exception catching (DISABLE_EXCEPTION_CATCHING=0). If you don't want exceptions, set DISABLE_EXCEPTION_CATCHING to 1; if you do want exceptions, don't link with -fno-exceptions")
if shared.Settings.DEAD_FUNCTIONS:
if not options.js_opts:
logger.debug('enabling js opts for DEAD_FUNCTIONS')
options.js_opts = True
options.force_js_opts = True
if options.proxy_to_worker:
shared.Settings.PROXY_TO_WORKER = 1
if options.use_preload_plugins or len(options.preload_files) or len(options.embed_files):
if shared.Settings.NODERAWFS:
exit_with_error('--preload-file and --embed-file cannot be used with NODERAWFS which disables virtual filesystem')
# if we include any files, or intend to use preload plugins, then we definitely need filesystem support
shared.Settings.FORCE_FILESYSTEM = 1
if options.proxy_to_worker or options.use_preload_plugins:
shared.Settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$Browser']
if not shared.Settings.MINIMAL_RUNTIME:
# In non-MINIMAL_RUNTIME, the core runtime depends on these functions to be present. (In MINIMAL_RUNTIME, they are
# no longer always bundled in)
shared.Settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$demangle', '$demangleAll', '$jsStackTrace', '$stackTrace']
if shared.Settings.FILESYSTEM:
if shared.Settings.SUPPORT_ERRNO:
shared.Settings.EXPORTED_FUNCTIONS += ['___errno_location'] # so FS can report errno back to C
# to flush streams on FS exit, we need to be able to call fflush
# we only include it if the runtime is exitable, or when ASSERTIONS
# (ASSERTIONS will check that streams do not need to be flushed,
# helping people see when they should have disabled NO_EXIT_RUNTIME)
if shared.Settings.EXIT_RUNTIME or shared.Settings.ASSERTIONS:
shared.Settings.EXPORTED_FUNCTIONS += ['_fflush']
if shared.Settings.GLOBAL_BASE < 0:
# default if nothing else sets it
if shared.Settings.WASM:
# a higher global base is useful for optimizing load/store offsets, as it
# enables the --post-emscripten pass
shared.Settings.GLOBAL_BASE = 1024
else:
shared.Settings.GLOBAL_BASE = 8
if shared.Settings.USE_PTHREADS:
if shared.Settings.USE_PTHREADS == 2:
exit_with_error('USE_PTHREADS=2 is not longer supported')
if shared.Settings.ALLOW_MEMORY_GROWTH:
if not shared.Settings.WASM:
exit_with_error('Memory growth is not supported with pthreads without wasm')
else:
logging.warning('USE_PTHREADS + ALLOW_MEMORY_GROWTH may run non-wasm code slowly, see https://github.com/WebAssembly/design/issues/1271')
# UTF8Decoder.decode doesn't work with a view of a SharedArrayBuffer
shared.Settings.TEXTDECODER = 0
options.js_libraries.append(shared.path_from_root('src', 'library_pthread.js'))
newargs.append('-D__EMSCRIPTEN_PTHREADS__=1')
if shared.Settings.WASM_BACKEND:
newargs += ['-pthread']
# some pthreads code is in asm.js library functions, which are auto-exported; for the wasm backend, we must
# manually export them
shared.Settings.EXPORTED_FUNCTIONS += ['_emscripten_get_global_libc', '___pthread_tsd_run_dtors', '__register_pthread_ptr', '_pthread_self', '___emscripten_pthread_data_constructor']
# set location of worker.js
shared.Settings.PTHREAD_WORKER_FILE = unsuffixed(os.path.basename(target)) + '.worker.js'
else:
options.js_libraries.append(shared.path_from_root('src', 'library_pthread_stub.js'))
if shared.Settings.FORCE_FILESYSTEM and not shared.Settings.MINIMAL_RUNTIME:
# when the filesystem is forced, we export by default methods that filesystem usage
# may need, including filesystem usage from standalone file packager output (i.e.
# file packages not built together with emcc, but that are loaded at runtime
# separately, and they need emcc's output to contain the support they need)
if not shared.Settings.ASMFS:
shared.Settings.EXPORTED_RUNTIME_METHODS += [
'FS_createFolder',
'FS_createPath',
'FS_createDataFile',
'FS_createPreloadedFile',
'FS_createLazyFile',
'FS_createLink',
'FS_createDevice',
'FS_unlink'
]
shared.Settings.EXPORTED_RUNTIME_METHODS += [
'getMemory',
'addRunDependency',
'removeRunDependency',
'calledRun',
]
if shared.Settings.USE_PTHREADS:
# To ensure allocated thread stacks are aligned:
shared.Settings.EXPORTED_FUNCTIONS += ['_memalign']
if shared.Settings.MODULARIZE:
# MODULARIZE+USE_PTHREADS mode requires extra exports out to Module so that worker.js
# can access them:
# general threading variables:
shared.Settings.EXPORTED_RUNTIME_METHODS += ['PThread', 'ExitStatus']
# pthread stack setup:
shared.Settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$establishStackSpaceInJsModule']
shared.Settings.EXPORTED_FUNCTIONS += ['establishStackSpaceInJsModule']
# stack check:
if shared.Settings.STACK_OVERFLOW_CHECK:
shared.Settings.EXPORTED_RUNTIME_METHODS += ['writeStackCookie', 'checkStackCookie']
if shared.Settings.LINKABLE:
exit_with_error('-s LINKABLE=1 is not supported with -s USE_PTHREADS>0!')
if shared.Settings.SIDE_MODULE:
exit_with_error('-s SIDE_MODULE=1 is not supported with -s USE_PTHREADS>0!')
if shared.Settings.MAIN_MODULE:
exit_with_error('-s MAIN_MODULE=1 is not supported with -s USE_PTHREADS>0!')
if shared.Settings.EMTERPRETIFY:
exit_with_error('-s EMTERPRETIFY=1 is not supported with -s USE_PTHREADS>0!')
if shared.Settings.PROXY_TO_WORKER:
exit_with_error('--proxy-to-worker is not supported with -s USE_PTHREADS>0! Use the option -s PROXY_TO_PTHREAD=1 if you want to run the main thread of a multithreaded application in a web worker.')
else:
if shared.Settings.PROXY_TO_PTHREAD:
exit_with_error('-s PROXY_TO_PTHREAD=1 requires -s USE_PTHREADS to work!')
# Enable minification of asm.js imports on -O1 and higher if -g1 or lower is used.
if options.opt_level >= 1 and options.debug_level < 2 and not shared.Settings.WASM:
shared.Settings.MINIFY_ASMJS_IMPORT_NAMES = 1
if shared.Settings.WASM:
if not shared.Building.need_asm_js_file():
asm_target = asm_target.replace('.asm.js', '.temp.asm.js')
misc_temp_files.note(asm_target)
if shared.Settings.WASM:
if shared.Settings.TOTAL_MEMORY % 65536 != 0:
exit_with_error('For wasm, TOTAL_MEMORY must be a multiple of 64KB, was ' + str(shared.Settings.TOTAL_MEMORY))
else:
if shared.Settings.TOTAL_MEMORY < 16 * 1024 * 1024:
exit_with_error('TOTAL_MEMORY must be at least 16MB, was ' + str(shared.Settings.TOTAL_MEMORY))
if shared.Settings.TOTAL_MEMORY % (16 * 1024 * 1024) != 0:
exit_with_error('For asm.js, TOTAL_MEMORY must be a multiple of 16MB, was ' + str(shared.Settings.TOTAL_MEMORY))
if shared.Settings.TOTAL_MEMORY < shared.Settings.TOTAL_STACK:
exit_with_error('TOTAL_MEMORY must be larger than TOTAL_STACK, was ' + str(shared.Settings.TOTAL_MEMORY) + ' (TOTAL_STACK=' + str(shared.Settings.TOTAL_STACK) + ')')
if shared.Settings.WASM_MEM_MAX != -1 and shared.Settings.WASM_MEM_MAX % 65536 != 0:
exit_with_error('WASM_MEM_MAX must be a multiple of 64KB, was ' + str(shared.Settings.WASM_MEM_MAX))
if shared.Settings.MEMORY_GROWTH_STEP != -1 and shared.Settings.MEMORY_GROWTH_STEP % 65536 != 0:
exit_with_error('MEMORY_GROWTH_STEP must be a multiple of 64KB, was ' + str(shared.Settings.MEMORY_GROWTH_STEP))
if shared.Settings.USE_PTHREADS and shared.Settings.WASM and shared.Settings.ALLOW_MEMORY_GROWTH and shared.Settings.WASM_MEM_MAX == -1:
exit_with_error('If pthreads and memory growth are enabled, WASM_MEM_MAX must be set')
if shared.Settings.EXPORT_ES6 and not shared.Settings.MODULARIZE:
exit_with_error('EXPORT_ES6 requires MODULARIZE to be set')
# When MODULARIZE option is used, currently declare all module exports
# individually - TODO: this could be optimized
if shared.Settings.MODULARIZE and not shared.Settings.DECLARE_ASM_MODULE_EXPORTS:
shared.Settings.DECLARE_ASM_MODULE_EXPORTS = 1
logger.warning('Enabling -s DECLARE_ASM_MODULE_EXPORTS=1, since MODULARIZE currently requires declaring asm.js/wasm module exports in full')
# In MINIMAL_RUNTIME when modularizing, by default output asm.js module under the same name as the JS module. This allows code to share same loading function for both JS and asm.js modules,
# to save code size. The intent is that loader code captures the function variable from global scope to XHR loader local scope when it finishes loading, to avoid polluting global JS scope with
# variables. This provides safety via encapsulation. See src/shell_minimal_runtime.html for an example.
if shared.Settings.MINIMAL_RUNTIME and not shared.Settings.SEPARATE_ASM_MODULE_NAME and not shared.Settings.WASM and shared.Settings.MODULARIZE:
shared.Settings.SEPARATE_ASM_MODULE_NAME = 'var ' + shared.Settings.EXPORT_NAME
if shared.Settings.MODULARIZE and shared.Settings.SEPARATE_ASM and not shared.Settings.WASM and not shared.Settings.SEPARATE_ASM_MODULE_NAME:
exit_with_error('Targeting asm.js with --separate-asm and -s MODULARIZE=1 requires specifying the target variable name to which the asm.js module is loaded into. See https://github.com/emscripten-core/emscripten/pull/7949 for details')
# Apply default option if no custom name is provided
if not shared.Settings.SEPARATE_ASM_MODULE_NAME:
shared.Settings.SEPARATE_ASM_MODULE_NAME = 'Module["asm"]'
elif shared.Settings.WASM:
exit_with_error('-s SEPARATE_ASM_MODULE_NAME option only applies to when targeting asm.js, not with WebAssembly!')
if shared.Settings.MINIMAL_RUNTIME:
# Minimal runtime uses a different default shell file
if options.shell_path == shared.path_from_root('src', 'shell.html'):
options.shell_path = shared.path_from_root('src', 'shell_minimal_runtime.html')
# Remove the default exported functions 'memcpy', 'memset', 'malloc', 'free', etc. - those should only be linked in if used
shared.Settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE = []
if shared.Settings.ASSERTIONS and shared.Settings.MINIMAL_RUNTIME:
# In ASSERTIONS-builds, functions UTF8ArrayToString() and stringToUTF8Array() (which are not JS library functions), both
# use warnOnce(), which in MINIMAL_RUNTIME is a JS library function, so explicitly have to mark dependency to warnOnce()
# in that case. If string functions are turned to library functions in the future, then JS dependency tracking can be
# used and this special directive can be dropped.
shared.Settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$warnOnce']
# Always use the new HTML5 API event target lookup rules
shared.Settings.DISABLE_DEPRECATED_FIND_EVENT_TARGET_BEHAVIOR = 1
# Require explicit -lfoo.js flags to link with JS libraries.
shared.Settings.AUTO_JS_LIBRARIES = 0
# In asm.js always use memory init file to get the best code size, other modes are not currently supported.
if not shared.Settings.WASM:
options.memory_init_file = True
if shared.Settings.MODULARIZE and not shared.Settings.MODULARIZE_INSTANCE and shared.Settings.EXPORT_NAME == 'Module' and final_suffix == '.html' and \
(options.shell_path == shared.path_from_root('src', 'shell.html') or options.shell_path == shared.path_from_root('src', 'shell_minimal.html')):
exit_with_error('Due to collision in variable name "Module", the shell file "' + options.shell_path + '" is not compatible with build options "-s MODULARIZE=1 -s EXPORT_NAME=Module". Either provide your own shell file, change the name of the export to something else to avoid the name collision. (see https://github.com/emscripten-core/emscripten/issues/7950 for details)')
if shared.Settings.WASM:
if shared.Settings.SINGLE_FILE:
# placeholder strings for JS glue, to be replaced with subresource locations in do_binaryen
shared.Settings.WASM_TEXT_FILE = shared.FilenameReplacementStrings.WASM_TEXT_FILE
shared.Settings.WASM_BINARY_FILE = shared.FilenameReplacementStrings.WASM_BINARY_FILE
shared.Settings.ASMJS_CODE_FILE = shared.FilenameReplacementStrings.ASMJS_CODE_FILE
else:
# set file locations, so that JS glue can find what it needs
shared.Settings.WASM_TEXT_FILE = shared.JS.escape_for_js_string(os.path.basename(wasm_text_target))
shared.Settings.WASM_BINARY_FILE = shared.JS.escape_for_js_string(os.path.basename(wasm_binary_target))
shared.Settings.ASMJS_CODE_FILE = shared.JS.escape_for_js_string(os.path.basename(asm_target))
shared.Settings.ASM_JS = 2 # when targeting wasm, we use a wasm Memory, but that is not compatible with asm.js opts
if shared.Settings.ELIMINATE_DUPLICATE_FUNCTIONS:
logger.warning('for wasm there is no need to set ELIMINATE_DUPLICATE_FUNCTIONS, the binaryen optimizer does it automatically')
shared.Settings.ELIMINATE_DUPLICATE_FUNCTIONS = 0
# default precise-f32 to on, since it works well in wasm
shared.Settings.PRECISE_F32 = 1
if options.js_opts and not options.force_js_opts:
options.js_opts = None
logger.debug('asm.js opts not forced by user or an option that depends them, and we do not intend to run the asm.js, so disabling and leaving opts to the binaryen optimizer')
if options.use_closure_compiler == 2 and not shared.Settings.WASM2JS:
exit_with_error('closure compiler mode 2 assumes the code is asm.js, so not meaningful for wasm')
if any(s.startswith('MEM_INIT_METHOD=') for s in settings_changes):
exit_with_error('MEM_INIT_METHOD is not supported in wasm. Memory will be embedded in the wasm binary if threads are not used, and included in a separate file if threads are used.')
if shared.Settings.WASM2JS:
shared.Settings.MAYBE_WASM2JS = 1
# wasm2js does not support passive segments or atomics
if shared.Settings.USE_PTHREADS:
exit_with_error('WASM2JS does not yet support pthreads')
# in wasm2js, keep the mem init in the wasm itself if we can and if the
# options wouldn't tell a js build to use a separate mem init file
shared.Settings.MEM_INIT_IN_WASM = not options.memory_init_file or shared.Settings.SINGLE_FILE
else:
# wasm includes the mem init in the wasm binary. The exception is
# wasm2js, which behaves more like js.
options.memory_init_file = True
shared.Settings.MEM_INIT_IN_WASM = True if shared.Settings.WASM_BACKEND else not shared.Settings.USE_PTHREADS
# WASM_ASYNC_COMPILATION and SWAPPABLE_ASM_MODULE do not have a meaning in MINIMAL_RUNTIME (always async)
if not shared.Settings.MINIMAL_RUNTIME:
if shared.Settings.WASM_ASYNC_COMPILATION == 1:
# async compilation requires a swappable module - we swap it in when it's ready
shared.Settings.SWAPPABLE_ASM_MODULE = 1
else:
# if not wasm-only, we can't do async compilation as the build can run in other
# modes than wasm (like asm.js) which may not support an async step
shared.Settings.WASM_ASYNC_COMPILATION = 0
warning = 'This will reduce performance and compatibility (some browsers limit synchronous compilation), see http://kripken.github.io/emscripten-site/docs/compiling/WebAssembly.html#codegen-effects'
if 'WASM_ASYNC_COMPILATION=1' in settings_changes:
logger.warning('WASM_ASYNC_COMPILATION requested, but disabled because of user options. ' + warning)
elif 'WASM_ASYNC_COMPILATION=0' not in settings_changes:
logger.warning('WASM_ASYNC_COMPILATION disabled due to user options. ' + warning)
if not shared.Settings.DECLARE_ASM_MODULE_EXPORTS:
# Swappable wasm module/asynchronous wasm compilation requires an indirect stub
# function generated to each function export from wasm module, so cannot use the
# concise form of grabbing exports that does not need to refer to each export individually.
if shared.Settings.SWAPPABLE_ASM_MODULE == 1:
shared.Settings.DECLARE_ASM_MODULE_EXPORTS = 1
logger.warning('Enabling -s DECLARE_ASM_MODULE_EXPORTS=1 since -s SWAPPABLE_ASM_MODULE=1 is used')
# wasm side modules have suffix .wasm
if shared.Settings.SIDE_MODULE and target.endswith('.js'):
logger.warning('output suffix .js requested, but wasm side modules are just wasm files; emitting only a .wasm, no .js')
if options.separate_asm:
exit_with_error('cannot --separate-asm when emitting wasm, since not emitting asm.js')
sanitize = set()
for arg in newargs:
if arg.startswith('-fsanitize='):
sanitize.update(arg.split('=', 1)[1].split(','))
elif arg.startswith('-fno-sanitize='):
sanitize.difference_update(arg.split('=', 1)[1].split(','))
if sanitize:
shared.Settings.USE_OFFSET_CONVERTER = 1
if not shared.Settings.WASM_BACKEND:
exit_with_error('Sanitizers are not compatible with the fastcomp backend. Please upgrade to the upstream wasm backend by following these instructions: https://v8.dev/blog/emscripten-llvm-wasm#testing')
if sanitize & UBSAN_SANITIZERS:
if '-fsanitize-minimal-runtime' in newargs:
shared.Settings.UBSAN_RUNTIME = 1
else:
shared.Settings.UBSAN_RUNTIME = 2
if 'leak' in sanitize:
shared.Settings.USE_LSAN = 1
shared.Settings.EXIT_RUNTIME = 1
if shared.Settings.LINKABLE:
exit_with_error('LSan does not support dynamic linking')
if 'address' in sanitize:
shared.Settings.USE_ASAN = 1
shared.Settings.GLOBAL_BASE = shared.Settings.ASAN_SHADOW_SIZE
shared.Settings.TOTAL_MEMORY += shared.Settings.ASAN_SHADOW_SIZE
assert shared.Settings.TOTAL_MEMORY < 2**32
if shared.Settings.SAFE_HEAP:
# SAFE_HEAP instruments ASan's shadow memory accesses.
# Since the shadow memory starts at 0, the act of accessing the shadow memory is detected
# by SAFE_HEAP as a null pointer dereference.
exit_with_error('ASan does not work with SAFE_HEAP')
if shared.Settings.LINKABLE:
exit_with_error('ASan does not support dynamic linking')
if sanitize and '-g4' in args:
shared.Settings.LOAD_SOURCE_MAP = 1
if shared.Settings.WASM_BACKEND:
options.js_opts = None
# wasm backend output can benefit from the binaryen optimizer (in asm2wasm,
# we run the optimizer during asm2wasm itself). use it, if not overridden.
# BINARYEN_PASSES and BINARYEN_EXTRA_PASSES are comma-separated, and we support both '-'-prefixed and unprefixed pass names
def parse_passes(string):
passes = string.split(',')
passes = [('--' + p) if p[0] != '-' else p for p in passes if p]
return passes
passes = []
if 'BINARYEN_PASSES' in settings_key_changes:
if shared.Settings.BINARYEN_PASSES:
passes += parse_passes(shared.Settings.BINARYEN_PASSES)
else:
# safe heap must run before post-emscripten, so post-emscripten can apply the sbrk ptr
if shared.Settings.SAFE_HEAP:
passes += ['--safe-heap']
passes += ['--post-emscripten']
if not shared.Settings.EXIT_RUNTIME:
passes += ['--no-exit-runtime']
if options.opt_level > 0 or options.shrink_level > 0:
passes += [shared.Building.opt_level_to_str(options.opt_level, options.shrink_level)]
elif shared.Settings.STANDALONE_WASM:
# even if not optimizing, make an effort to remove all unused imports and
# exports, to make the wasm as standalone as possible
passes += ['--remove-unused-module-elements']
if shared.Settings.GLOBAL_BASE >= 1024: # hardcoded value in the binaryen pass
passes += ['--low-memory-unused']
if options.debug_level < 3:
passes += ['--strip-debug']
if not shared.Settings.EMIT_PRODUCERS_SECTION:
passes += ['--strip-producers']
if shared.Settings.AUTODEBUG and shared.Settings.WASM_OBJECT_FILES:
# adding '--flatten' here may make these even more effective
passes += ['--instrument-locals']
passes += ['--log-execution']
passes += ['--instrument-memory']
passes += ['--legalize-js-interface']
if shared.Settings.EMULATE_FUNCTION_POINTER_CASTS:
# note that this pass must run before asyncify, as if it runs afterwards we only
# generate the byn$fpcast_emu functions after asyncify runs, and so we wouldn't
# be able to whitelist them etc.
passes += ['--fpcast-emu']
if shared.Settings.ASYNCIFY:
# TODO: allow whitelist as in asyncify
passes += ['--asyncify']
if shared.Settings.ASYNCIFY_IGNORE_INDIRECT:
passes += ['--pass-arg=asyncify-ignore-indirect']
else:
# if we are not ignoring indirect calls, then we must treat invoke_* as if
# they are indirect calls, since that is what they do - we can't see their
# targets statically.
shared.Settings.ASYNCIFY_IMPORTS += ['invoke_*']
# with pthreads we may call main through the __call_main mechanism, which can
# therefore reach anything in the program, so mark it as possibly causing a
# sleep (the asyncify analysis doesn't look through JS, just wasm, so it can't
# see what it itself calls)
if shared.Settings.USE_PTHREADS:
shared.Settings.ASYNCIFY_IMPORTS += ['__call_main']
if shared.Settings.ASYNCIFY_IMPORTS:
passes += ['--pass-arg=asyncify-imports@%s' % ','.join(['env.' + i for i in shared.Settings.ASYNCIFY_IMPORTS])]
# shell escaping can be confusing; try to emit useful warnings
def check_human_readable_list(items):
for item in items:
if item.count('(') != item.count(')'):
logger.warning('''emcc: ASYNCIFY list contains an item without balanced parentheses ("(", ")"):''')
logger.warning(''' ''' + item)
logger.warning('''This may indicate improper escaping that led to splitting inside your names.''')
logger.warning('''Try to quote the entire argument, like this: -s 'ASYNCIFY_WHITELIST=["foo(int, char)", "bar"]' ''')
break
if shared.Settings.ASYNCIFY_BLACKLIST:
check_human_readable_list(shared.Settings.ASYNCIFY_BLACKLIST)
passes += ['--pass-arg=asyncify-blacklist@%s' % ','.join(shared.Settings.ASYNCIFY_BLACKLIST)]
if shared.Settings.ASYNCIFY_WHITELIST:
check_human_readable_list(shared.Settings.ASYNCIFY_WHITELIST)
passes += ['--pass-arg=asyncify-whitelist@%s' % ','.join(shared.Settings.ASYNCIFY_WHITELIST)]
if shared.Settings.BINARYEN_IGNORE_IMPLICIT_TRAPS:
passes += ['--ignore-implicit-traps']
if shared.Settings.BINARYEN_EXTRA_PASSES:
passes += parse_passes(shared.Settings.BINARYEN_EXTRA_PASSES)
options.binaryen_passes = passes
# to bootstrap struct_info, we need binaryen
os.environ['EMCC_WASM_BACKEND_BINARYEN'] = '1'
# run safe-heap as a binaryen pass in fastcomp wasm, while in the wasm backend we
# run it in binaryen_passes so that it can be synchronized with the sbrk ptr
if shared.Settings.SAFE_HEAP and shared.Building.is_wasm_only() and not shared.Settings.WASM_BACKEND:
options.binaryen_passes += ['--safe-heap']
if shared.Settings.EMULATE_FUNCTION_POINTER_CASTS and not shared.Settings.WASM_BACKEND:
# emulated function pointer casts is emulated in fastcomp wasm using a binaryen pass
options.binaryen_passes += ['--fpcast-emu']
# we also need emulated function pointers for that, as we need a single flat
# table, as is standard in wasm, and not asm.js split ones.
shared.Settings.EMULATED_FUNCTION_POINTERS = 1
if shared.Settings.WASM2JS:
if not shared.Settings.WASM_BACKEND:
exit_with_error('wasm2js is only available in the upstream wasm backend path')
if use_source_map(options):
exit_with_error('wasm2js does not support source maps yet (debug in wasm for now)')
if target.endswith(WASM_ENDINGS):
# if the output is just a wasm file, it will normally be a standalone one,
# as there is no JS. an exception are side modules, as we can't tell at
# compile time whether JS will be involved or not - the main module may
# have JS, and the side module is expected to link against that.
# we also do not support standalone mode in fastcomp.
if shared.Settings.WASM_BACKEND and not shared.Settings.SIDE_MODULE:
shared.Settings.STANDALONE_WASM = 1
js_target = misc_temp_files.get(suffix='.js').name
if shared.Settings.EVAL_CTORS:
if not shared.Settings.WASM:
# for asm.js: this option is not a js optimizer pass, but does run the js optimizer internally, so
# we need to generate proper code for that (for wasm, we run a binaryen tool for this)
shared.Settings.RUNNING_JS_OPTS = 1
# memory growth does not work in dynamic linking, except for wasm
if not shared.Settings.WASM and (shared.Settings.MAIN_MODULE or shared.Settings.SIDE_MODULE):
assert not shared.Settings.ALLOW_MEMORY_GROWTH, 'memory growth is not supported with shared asm.js modules'
if shared.Settings.MINIMAL_RUNTIME:
if shared.Settings.ALLOW_MEMORY_GROWTH:
logging.warning('-s ALLOW_MEMORY_GROWTH=1 is not yet supported with -s MINIMAL_RUNTIME=1')
if shared.Settings.EMTERPRETIFY:
exit_with_error('-s EMTERPRETIFY=1 is not supported with -s MINIMAL_RUNTIME=1')
if shared.Settings.USE_PTHREADS:
exit_with_error('-s USE_PTHREADS=1 is not yet supported with -s MINIMAL_RUNTIME=1')
if shared.Settings.PRECISE_F32 == 2:
exit_with_error('-s PRECISE_F32=2 is not supported with -s MINIMAL_RUNTIME=1')
if shared.Settings.SINGLE_FILE:
exit_with_error('-s SINGLE_FILE=1 is not supported with -s MINIMAL_RUNTIME=1')
if shared.Settings.ALLOW_MEMORY_GROWTH and shared.Settings.ASM_JS == 1:
# this is an issue in asm.js, but not wasm
if not shared.Settings.WASM:
shared.WarningManager.warn('ALMOST_ASM')
shared.Settings.ASM_JS = 2 # memory growth does not validate as asm.js http://discourse.wicg.io/t/request-for-comments-switching-resizing-heaps-in-asm-js/641/23
# safe heap in asm.js uses the js optimizer (in wasm-only mode we can use binaryen)
if shared.Settings.SAFE_HEAP and not shared.Building.is_wasm_only():
if not options.js_opts:
logger.debug('enabling js opts for SAFE_HEAP')
options.js_opts = True
options.force_js_opts = True
if options.js_opts:
shared.Settings.RUNNING_JS_OPTS = 1
if shared.Settings.CYBERDWARF:
newargs.append('-g')
options.debug_level = max(options.debug_level, 2)
shared.Settings.BUNDLED_CD_DEBUG_FILE = target + ".cd"
options.js_libraries.append(shared.path_from_root('src', 'library_cyberdwarf.js'))
options.js_libraries.append(shared.path_from_root('src', 'library_debugger_toolkit.js'))
if options.tracing:
if shared.Settings.ALLOW_MEMORY_GROWTH:
shared.Settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['emscripten_trace_report_memory_layout']
# MINIMAL_RUNTIME always use separate .asm.js file for best performance and memory usage
if shared.Settings.MINIMAL_RUNTIME and not shared.Settings.WASM:
options.separate_asm = True
if shared.Settings.STANDALONE_WASM:
if not shared.Settings.WASM_BACKEND:
exit_with_error('STANDALONE_WASM is only available in the upstream wasm backend path')
if shared.Settings.USE_PTHREADS:
exit_with_error('STANDALONE_WASM does not support pthreads yet')
if shared.Settings.SIMD:
exit_with_error('STANDALONE_WASM does not support simd yet')
if shared.Settings.ALLOW_MEMORY_GROWTH:
exit_with_error('STANDALONE_WASM does not support memory growth yet')
# the wasm must be runnable without the JS, so there cannot be anything that
# requires JS legalization
shared.Settings.LEGALIZE_JS_FFI = 0
if shared.Settings.WASM_BACKEND:
if shared.Settings.SIMD:
newargs.append('-msimd128')
if shared.Settings.USE_PTHREADS:
newargs.append('-pthread')
else:
# We leave the -O option in place so that the clang front-end runs in that
# optimization mode, but we disable the actual optimization passes, as we'll
# run them separately.
if options.opt_level > 0:
newargs.append('-mllvm')
newargs.append('-disable-llvm-optzns')
if not shared.Settings.LEGALIZE_JS_FFI:
assert shared.Building.is_wasm_only(), 'LEGALIZE_JS_FFI incompatible with RUNNING_JS_OPTS.'
shared.Settings.EMSCRIPTEN_VERSION = shared.EMSCRIPTEN_VERSION
shared.Settings.OPT_LEVEL = options.opt_level
shared.Settings.DEBUG_LEVEL = options.debug_level
shared.Settings.PROFILING_FUNCS = options.profiling_funcs
shared.Settings.SOURCE_MAP_BASE = options.source_map_base or ''
## Compile source code to bitcode
logger.debug('compiling to bitcode')
temp_files = []
# exit block 'parse arguments and setup'
log_time('parse arguments and setup')
if DEBUG:
# we are about to start using temp dirs. serialize access to the temp dir
# when using EMCC_DEBUG, since we don't want multiple processes would to
# use it at once, they might collide if they happen to use the same
# tempfile names
shared.Cache.acquire_cache_lock()
try:
with ToolchainProfiler.profile_block('compile inputs'):
# Precompiled headers support
if has_header_inputs:
headers = [header for _, header in input_files]
for header in headers:
assert header.endswith(HEADER_ENDINGS), 'if you have one header input, we assume you want to precompile headers, and cannot have source files or other inputs as well: ' + str(headers) + ' : ' + header
args = newargs + headers
if specified_target:
args += ['-o', specified_target]
args = system_libs.process_args(args, shared.Settings)
logger.debug("running (for precompiled headers): " + clang_compiler + ' ' + ' '.join(args))
return run_process([clang_compiler] + args, check=False).returncode
# Request LLVM debug info if explicitly specified, or building bitcode with -g, or if building a source all the way to JS with -g
if use_source_map(options) or ((final_suffix not in JS_CONTAINING_ENDINGS or (has_source_inputs and final_suffix in JS_CONTAINING_ENDINGS)) and options.requested_debug == '-g'):
# do not save llvm debug info if js optimizer will wipe it out anyhow (but if source maps are used, keep it)
if use_source_map(options) or not (final_suffix in JS_CONTAINING_ENDINGS and options.js_opts):
newargs.append('-g') # preserve LLVM debug info
options.debug_level = 4
shared.Settings.DEBUG_LEVEL = 4
# For asm.js, the generated JavaScript could preserve LLVM value names, which can be useful for debugging.
if options.debug_level >= 3 and not shared.Settings.WASM:
newargs.append('-fno-discard-value-names')
def is_link_flag(flag):
return any(flag.startswith(x) for x in ('-l', '-L', '-Wl,'))
compile_args = [a for a in newargs if a and not is_link_flag(a)]
# Bitcode args generation code
def get_clang_command(input_files):
args = [clang_compiler] + compile_args + input_files
if not shared.Building.can_inline():
args.append('-fno-inline-functions')
# For fastcomp backend, no LLVM IR functions should ever be annotated
# 'optnone', because that would skip running the SimplifyCFG pass on
# them, which is required to always run to clean up LandingPadInst
# instructions that are not needed.
if not shared.Settings.WASM_BACKEND:
args += ['-Xclang', '-disable-O0-optnone']
args = system_libs.process_args(args, shared.Settings)
return args
# -E preprocessor-only support
if '-E' in newargs or '-M' in newargs or '-MM' in newargs or '-fsyntax-only' in newargs:
input_files = [x[1] for x in input_files]
cmd = get_clang_command(input_files)
if specified_target:
cmd += ['-o', specified_target]
# Do not compile, but just output the result from preprocessing stage or
# output the dependency rule. Warning: clang and gcc behave differently
# with -MF! (clang seems to not recognize it)
logger.debug(('just preprocessor ' if '-E' in newargs else 'just dependencies: ') + ' '.join(cmd))
return run_process(cmd, check=False).returncode
def get_object_filename(input_file):
if compile_only and len(input_files) == 1:
# no need for a temp file, just emit to the right place
if specified_target:
return specified_target
else:
return unsuffixed_basename(input_files[0][1]) + options.default_object_extension
else:
return in_temp(unsuffixed(uniquename(input_file)) + options.default_object_extension)
def compile_source_file(i, input_file):
logger.debug('compiling source file: ' + input_file)
output_file = get_object_filename(input_file)
temp_files.append((i, output_file))
cmd = get_clang_command([input_file]) + ['-c', '-o', output_file]
if shared.Settings.WASM_BACKEND and shared.Settings.RELOCATABLE:
cmd.append('-fPIC')
cmd.append('-fvisibility=default')
if shared.Settings.WASM_OBJECT_FILES:
for a in shared.Building.llvm_backend_args():
cmd += ['-mllvm', a]
else:
cmd.append('-emit-llvm')
shared.print_compiler_stage(cmd)
shared.check_call(cmd)
if output_file != '-':
assert(os.path.exists(output_file))
# First, generate LLVM bitcode. For each input file, we get base.o with bitcode
for i, input_file in input_files:
file_ending = get_file_suffix(input_file)
if file_ending.endswith(SOURCE_ENDINGS):
compile_source_file(i, input_file)
else:
if file_ending.endswith(OBJECT_FILE_ENDINGS):
logger.debug('using object file: ' + input_file)
temp_files.append((i, input_file))
elif file_ending.endswith(DYNAMICLIB_ENDINGS) or shared.Building.is_ar(input_file):
logger.debug('using library file: ' + input_file)
temp_files.append((i, input_file))
elif file_ending.endswith(ASSEMBLY_ENDINGS):
if not LEAVE_INPUTS_RAW:
logger.debug('assembling assembly file: ' + input_file)
temp_file = in_temp(unsuffixed(uniquename(input_file)) + '.o')
shared.Building.llvm_as(input_file, temp_file)
temp_files.append((i, temp_file))
else:
if has_fixed_language_mode:
compile_source_file(i, input_file)
else:
exit_with_error(input_file + ': Unknown file suffix when compiling to LLVM bitcode!')
# exit block 'compile inputs'
log_time('compile inputs')
with ToolchainProfiler.profile_block('process inputs'):
if not LEAVE_INPUTS_RAW and not shared.Settings.WASM_BACKEND:
assert len(temp_files) == len(input_files)
# Optimize source files
if optimizing(options.llvm_opts):
for pos, (_, input_file) in enumerate(input_files):
file_ending = get_file_suffix(input_file)
if file_ending.endswith(SOURCE_ENDINGS):
temp_file = temp_files[pos][1]
logger.debug('optimizing %s', input_file)
# if DEBUG:
# shutil.copyfile(temp_file, os.path.join(shared.configuration.CANONICAL_TEMP_DIR, 'to_opt.bc')) # useful when LLVM opt aborts
new_temp_file = in_temp(unsuffixed(uniquename(temp_file)) + '.o')
# after optimizing, lower intrinsics to libc calls so that our linking code
# will find them (otherwise, llvm.cos.f32() will not link in cosf(), and
# we end up calling out to JS for Math.cos).
opts = options.llvm_opts + ['-lower-non-em-intrinsics']
shared.Building.llvm_opt(temp_file, opts, new_temp_file)
temp_files[pos] = (temp_files[pos][0], new_temp_file)
# If we were just compiling stop here
if compile_only:
if not specified_target:
assert len(temp_files) == len(input_files)
for tempf, inputf in zip(temp_files, input_files):
safe_move(tempf[1], unsuffixed_basename(inputf[1]) + final_suffix)
else:
# Specifying -o with multiple input source files is not allowed.
# We error out much earlier in this case.
assert len(input_files) == 1
input_file = input_files[0][1]
temp_file = temp_files[0][1]
bitcode_target = specified_target if specified_target else unsuffixed_basename(input_file) + final_suffix
if temp_file != input_file:
safe_move(temp_file, bitcode_target)
else:
shutil.copyfile(temp_file, bitcode_target)
temp_output_base = unsuffixed(temp_file)
if os.path.exists(temp_output_base + '.d'):
# There was a .d file generated, from -MD or -MMD and friends, save a copy of it to where the output resides,
# adjusting the target name away from the temporary file name to the specified target.
# It will be deleted with the rest of the temporary directory.
deps = open(temp_output_base + '.d').read()
deps = deps.replace(temp_output_base + options.default_object_extension, specified_target)
with open(os.path.join(os.path.dirname(specified_target), os.path.basename(unsuffixed(input_file) + '.d')), "w") as out_dep:
out_dep.write(deps)
# exit block 'process inputs'
log_time('process inputs')
if compile_only:
logger.debug('stopping after compile phase')
return 0
# Decide what we will link
consumed = process_libraries(libs, lib_dirs, temp_files)
# Filter out libraries that are actually JS libs
link_flags = [l for l in link_flags if l[0] not in consumed]
temp_files = filter_out_dynamic_libs(temp_files)
linker_inputs = [val for _, val in sorted(temp_files + link_flags)]
if link_to_object:
with ToolchainProfiler.profile_block('linking to object file'):
# We have a specified target (-o <target>), which is not JavaScript or HTML, and
# we have multiple files: Link them
if shared.Settings.SIDE_MODULE:
exit_with_error('SIDE_MODULE must only be used when compiling to an executable shared library, and not when emitting an object file. That is, you should be emitting a .wasm file (for wasm) or a .js file (for asm.js). Note that when compiling to a typical native suffix for a shared library (.so, .dylib, .dll; which many build systems do) then Emscripten emits an object file, which you should then compile to .wasm or .js with SIDE_MODULE.')
if final_suffix.lower() in ('.so', '.dylib', '.dll'):
logger.warning('When Emscripten compiles to a typical native suffix for shared libraries (.so, .dylib, .dll) then it emits an object file. You should then compile that to an emscripten SIDE_MODULE (using that flag) with suffix .wasm (for wasm) or .js (for asm.js). (You may also want to adapt your build system to emit the more standard suffix for a an object file, \'.bc\' or \'.o\', which would avoid this warning.)')
logger.debug('link_to_object: ' + str(linker_inputs) + ' -> ' + specified_target)
shared.Building.link_to_object(linker_inputs, specified_target)
logger.debug('stopping after linking to object file')
return 0
## Continue on to create JavaScript
with ToolchainProfiler.profile_block('calculate system libraries'):
# link in ports and system libraries, if necessary
if not LEAVE_INPUTS_RAW and \
not shared.Settings.BOOTSTRAPPING_STRUCT_INFO and \
not shared.Settings.SIDE_MODULE: # shared libraries/side modules link no C libraries, need them in parent
extra_files_to_link = system_libs.get_ports(shared.Settings)
extra_files_to_link += system_libs.calculate([f for _, f in sorted(temp_files)] + extra_files_to_link, in_temp, stdout_=None, stderr_=None, forced=forced_stdlibs)
linker_inputs += extra_files_to_link
# exit block 'calculate system libraries'
log_time('calculate system libraries')
def dedup_list(lst):
rtn = []
for item in lst:
if item not in rtn:
rtn.append(item)
return rtn
# Make a final pass over shared.Settings.EXPORTED_FUNCTIONS to remove any
# duplication between functions added by the driver/libraries and function
# specified by the user
shared.Settings.EXPORTED_FUNCTIONS = dedup_list(shared.Settings.EXPORTED_FUNCTIONS)
with ToolchainProfiler.profile_block('link'):
# final will be an array if linking is deferred, otherwise a normal string.
if shared.Settings.WASM_BACKEND:
DEFAULT_FINAL = in_temp(target_basename + '.wasm')
else:
DEFAULT_FINAL = in_temp(target_basename + '.bc')
def get_final():
global final
if isinstance(final, list):
final = DEFAULT_FINAL
return final
# First, combine the bitcode files if there are several. We must also link if we have a singleton .a
perform_link = len(linker_inputs) > 1 or shared.Settings.WASM_BACKEND
if not perform_link and not LEAVE_INPUTS_RAW:
is_bc = suffix(temp_files[0][1]) in OBJECT_FILE_ENDINGS
is_dylib = suffix(temp_files[0][1]) in DYNAMICLIB_ENDINGS
is_ar = shared.Building.is_ar(temp_files[0][1])
perform_link = not (is_bc or is_dylib) and is_ar
if perform_link:
logger.debug('linking: ' + str(linker_inputs))
# force archive contents to all be included, if just archives, or if linking shared modules
force_archive_contents = all(t.endswith(STATICLIB_ENDINGS) for _, t in temp_files) or shared.Settings.LINKABLE
# if EMCC_DEBUG=2 then we must link now, so the temp files are complete.
# if using the wasm backend, we might be using vanilla LLVM, which does not allow our fastcomp deferred linking opts.
# TODO: we could check if this is a fastcomp build, and still speed things up here
just_calculate = DEBUG != 2 and not shared.Settings.WASM_BACKEND
if shared.Settings.WASM_BACKEND:
# If LTO is enabled then use the -O opt level as the LTO level
if options.llvm_lto:
lto_level = options.opt_level
else:
lto_level = 0
final = shared.Building.link_lld(linker_inputs, DEFAULT_FINAL, lto_level=lto_level)
else:
final = shared.Building.link(linker_inputs, DEFAULT_FINAL, force_archive_contents=force_archive_contents, just_calculate=just_calculate)
else:
logger.debug('skipping linking: ' + str(linker_inputs))
if not LEAVE_INPUTS_RAW:
_, temp_file = temp_files[0]
_, input_file = input_files[0]
final = in_temp(target_basename + '.bc')
if temp_file != input_file:
shutil.move(temp_file, final)
else:
shutil.copyfile(temp_file, final)
else:
_, input_file = input_files[0]
final = in_temp(input_file)
shutil.copyfile(input_file, final)
# exit block 'link'
log_time('link')
if not shared.Settings.WASM_BACKEND:
with ToolchainProfiler.profile_block('post-link'):
if DEBUG:
logger.debug('saving intermediate processing steps to %s', shared.get_emscripten_temp_dir())
if not LEAVE_INPUTS_RAW:
save_intermediate('basebc', 'bc')
# Optimize, if asked to
if not LEAVE_INPUTS_RAW:
# remove LLVM debug if we are not asked for it
link_opts = [] if use_source_map(options) or shared.Settings.CYBERDWARF else ['-strip-debug']
if not shared.Settings.ASSERTIONS:
link_opts += ['-disable-verify']
else:
# when verifying, LLVM debug info has some tricky linking aspects, and llvm-link will
# disable the type map in that case. we added linking to opt, so we need to do
# something similar, which we can do with a param to opt
link_opts += ['-disable-debug-info-type-map']
if options.llvm_lto is not None and options.llvm_lto >= 2 and optimizing(options.llvm_opts):
logger.debug('running LLVM opts as pre-LTO')
final = shared.Building.llvm_opt(final, options.llvm_opts, DEFAULT_FINAL)
save_intermediate('opt', 'bc')
# If we can LTO, do it before dce, since it opens up dce opportunities
if (not shared.Settings.LINKABLE) and options.llvm_lto and options.llvm_lto != 2:
if not shared.Building.can_inline():
link_opts.append('-disable-inlining')
# add a manual internalize with the proper things we need to be kept alive during lto
link_opts += shared.Building.get_safe_internalize() + ['-std-link-opts']
# execute it now, so it is done entirely before we get to the stage of legalization etc.
final = shared.Building.llvm_opt(final, link_opts, DEFAULT_FINAL)
save_intermediate('lto', 'bc')
link_opts = []
else:
# At minimum remove dead functions etc., this potentially saves a
# lot in the size of the generated code (and the time to compile it)
link_opts += shared.Building.get_safe_internalize() + ['-globaldce']
if options.cfi:
if use_cxx:
link_opts.append("-wholeprogramdevirt")
link_opts.append("-lowertypetests")
if AUTODEBUG:
# let llvm opt directly emit ll, to skip writing and reading all the bitcode
link_opts += ['-S']
final = shared.Building.llvm_opt(final, link_opts, get_final() + '.link.ll')
save_intermediate('linktime', 'll')
else:
if len(link_opts) > 0:
final = shared.Building.llvm_opt(final, link_opts, DEFAULT_FINAL)
save_intermediate('linktime', 'bc')
if options.save_bc:
shutil.copyfile(final, options.save_bc)
# Prepare .ll for Emscripten
if LEAVE_INPUTS_RAW:
assert len(input_files) == 1
if options.save_bc:
save_intermediate('ll', 'll')
if AUTODEBUG:
logger.debug('autodebug')
next = get_final() + '.ad.ll'
run_process([shared.PYTHON, shared.AUTODEBUGGER, final, next])
final = next
save_intermediate('autodebug', 'll')
assert not isinstance(final, list), 'we must have linked the final files, if linking was deferred, by this point'
# exit block 'post-link'
log_time('post-link')
with ToolchainProfiler.profile_block('emscript'):
# Emscripten
logger.debug('LLVM => JS')
js_libraries = None
if options.js_libraries:
js_libraries = [os.path.abspath(lib) for lib in options.js_libraries]
if options.memory_init_file:
shared.Settings.MEM_INIT_METHOD = 1
else:
assert shared.Settings.MEM_INIT_METHOD != 1
if embed_memfile(options):
shared.Settings.SUPPORT_BASE64_EMBEDDING = 1
final = do_emscripten(final, target + '.mem', js_libraries)
save_intermediate('original')
if shared.Settings.WASM_BACKEND:
# we also received wast and wasm at this stage
temp_basename = unsuffixed(final)
wasm_temp = temp_basename + '.wasm'
shutil.move(wasm_temp, wasm_binary_target)
if use_source_map(options):
shutil.move(wasm_temp + '.map', wasm_source_map_target)
if shared.Settings.CYBERDWARF:
cd_target = final + '.cd'
shutil.move(cd_target, target + '.cd')
# exit block 'emscript'
log_time('emscript (llvm => executable code)')
with ToolchainProfiler.profile_block('source transforms'):
# Embed and preload files
if len(options.preload_files) or len(options.embed_files):
# Also, MEMFS is not aware of heap resizing feature in wasm, so if MEMFS and memory growth are used together, force
# no_heap_copy to be enabled.
if shared.Settings.ALLOW_MEMORY_GROWTH and not options.no_heap_copy:
logger.info('Enabling --no-heap-copy because -s ALLOW_MEMORY_GROWTH=1 is being used with file_packager.py (pass --no-heap-copy to suppress this notification)')
options.no_heap_copy = True
logger.debug('setting up files')
file_args = ['--from-emcc', '--export-name=' + shared.Settings.EXPORT_NAME]
if len(options.preload_files):
file_args.append('--preload')
file_args += options.preload_files
if len(options.embed_files):
file_args.append('--embed')
file_args += options.embed_files
if len(options.exclude_files):
file_args.append('--exclude')
file_args += options.exclude_files
if options.use_preload_cache:
file_args.append('--use-preload-cache')
if options.no_heap_copy:
file_args.append('--no-heap-copy')
if shared.Settings.LZ4:
file_args.append('--lz4')
if options.use_preload_plugins:
file_args.append('--use-preload-plugins')
file_code = run_process([shared.PYTHON, shared.FILE_PACKAGER, unsuffixed(target) + '.data'] + file_args, stdout=PIPE).stdout
options.pre_js = file_code + options.pre_js
# Apply pre and postjs files
if options.pre_js or options.post_js:
logger.debug('applying pre/postjses')
src = open(final).read()
final += '.pp.js'
if WINDOWS: # Avoid duplicating \r\n to \r\r\n when writing out.
if options.pre_js:
options.pre_js = options.pre_js.replace('\r\n', '\n')
if options.post_js:
options.post_js = options.post_js.replace('\r\n', '\n')
with open(final, 'w') as f:
# pre-js code goes right after the Module integration code (so it
# can use Module), we have a marker for it
f.write(src.replace('// {{PRE_JSES}}', options.pre_js))
f.write(options.post_js)
options.pre_js = src = options.post_js = None
save_intermediate('pre-post')
# Apply a source code transformation, if requested
if options.js_transform:
shutil.copyfile(final, final + '.tr.js')
final += '.tr.js'
posix = not shared.WINDOWS
logger.debug('applying transform: %s', options.js_transform)
shared.check_call(shared.Building.remove_quotes(shlex.split(options.js_transform, posix=posix) + [os.path.abspath(final)]))
save_intermediate('transformed')
js_transform_tempfiles = [final]
# exit block 'source transforms'
log_time('source transforms')
with ToolchainProfiler.profile_block('memory initializer'):
memfile = None
if (not shared.Settings.WASM_BACKEND and (shared.Settings.MEM_INIT_METHOD > 0 or embed_memfile(options))) or \
(shared.Settings.WASM_BACKEND and not shared.Settings.MEM_INIT_IN_WASM):
if shared.Settings.MINIMAL_RUNTIME:
# Independent of whether user is doing -o a.html or -o a.js, generate the mem init file as a.mem (and not as a.html.mem or a.js.mem)
memfile = target.replace('.html', '.mem').replace('.js', '.mem')
else:
memfile = target + '.mem'
if memfile:
if shared.Settings.WASM_BACKEND:
# For the wasm backend, we don't have any memory info in JS. All we need to do
# is set the memory initializer url.
src = open(final).read()
src = src.replace('var memoryInitializer = null;', 'var memoryInitializer = "%s";' % os.path.basename(memfile))
open(final + '.mem.js', 'w').write(src)
final += '.mem.js'
else:
# Non-wasm backend path: Strip the memory initializer out of the asmjs file
shared.try_delete(memfile)
def repl(m):
# handle chunking of the memory initializer
s = m.group(1)
if len(s) == 0:
return '' # don't emit 0-size ones
membytes = [int(x or '0') for x in s.split(',')]
while membytes and membytes[-1] == 0:
membytes.pop()
if not membytes:
return ''
if shared.Settings.MEM_INIT_METHOD == 2:
# memory initializer in a string literal
return "memoryInitializer = '%s';" % shared.JS.generate_string_initializer(membytes)
open(memfile, 'wb').write(bytearray(membytes))
if DEBUG:
# Copy into temp dir as well, so can be run there too
shared.safe_copy(memfile, os.path.join(shared.get_emscripten_temp_dir(), os.path.basename(memfile)))
if not shared.Settings.WASM or not shared.Settings.MEM_INIT_IN_WASM:
return 'memoryInitializer = "%s";' % shared.JS.get_subresource_location(memfile, embed_memfile(options))
else:
return ''
src = re.sub(shared.JS.memory_initializer_pattern, repl, open(final).read(), count=1)
open(final + '.mem.js', 'w').write(src)
final += '.mem.js'
src = None
js_transform_tempfiles[-1] = final # simple text substitution preserves comment line number mappings
if os.path.exists(memfile):
save_intermediate('meminit')
logger.debug('wrote memory initialization to %s', memfile)
else:
logger.debug('did not see memory initialization')
if shared.Settings.USE_PTHREADS:
target_dir = os.path.dirname(os.path.abspath(target))
worker_output = os.path.join(target_dir, shared.Settings.PTHREAD_WORKER_FILE)
with open(worker_output, 'w') as f:
f.write(shared.read_and_preprocess(shared.path_from_root('src', 'worker.js'), expand_macros=True))
# Generate the fetch.js worker script for multithreaded emscripten_fetch() support if targeting pthreads.
if shared.Settings.USE_FETCH_WORKER:
shared.make_fetch_worker(final, shared.Settings.FETCH_WORKER_FILE)
# exit block 'memory initializer'
log_time('memory initializer')
optimizer = JSOptimizer(
target=target,
options=options,
js_transform_tempfiles=js_transform_tempfiles,
in_temp=in_temp,
)
with ToolchainProfiler.profile_block('js opts'):
# It is useful to run several js optimizer passes together, to save on unneeded unparsing/reparsing
if shared.Settings.DEAD_FUNCTIONS:
optimizer.queue += ['eliminateDeadFuncs']
optimizer.extra_info['dead_functions'] = shared.Settings.DEAD_FUNCTIONS
if options.opt_level >= 1 and options.js_opts:
logger.debug('running js post-opts')
if DEBUG == 2:
# Clean up the syntax a bit
optimizer.queue += ['noop']
def get_eliminate():
if shared.Settings.ALLOW_MEMORY_GROWTH:
return 'eliminateMemSafe'
else:
return 'eliminate'
if options.opt_level >= 2:
optimizer.queue += [get_eliminate()]
if shared.Settings.AGGRESSIVE_VARIABLE_ELIMINATION:
# note that this happens before registerize/minification, which can obfuscate the name of 'label', which is tricky
optimizer.queue += ['aggressiveVariableElimination']
optimizer.queue += ['simplifyExpressions']
if shared.Settings.EMTERPRETIFY:
# emterpreter code will not run through a JS optimizing JIT, do more work ourselves
optimizer.queue += ['localCSE']
if shared.Settings.EMTERPRETIFY:
# add explicit label setting, as we will run aggressiveVariableElimination late, *after* 'label' is no longer notable by name
optimizer.queue += ['safeLabelSetting']
if options.opt_level >= 1 and options.js_opts:
if options.opt_level >= 2:
# simplify ifs if it is ok to make the code somewhat unreadable,
# with commaified code breaks late aggressive variable elimination)
# do not do this with binaryen, as commaifying confuses binaryen call type detection (FIXME, in theory, but unimportant)
debugging = options.debug_level == 0 or options.profiling
if shared.Settings.SIMPLIFY_IFS and debugging and not shared.Settings.WASM:
optimizer.queue += ['simplifyIfs']
if shared.Settings.PRECISE_F32:
optimizer.queue += ['optimizeFrounds']
if options.js_opts:
if shared.Settings.SAFE_HEAP and not shared.Building.is_wasm_only():
optimizer.queue += ['safeHeap']
if options.opt_level >= 2 and options.debug_level < 3:
if options.opt_level >= 3 or options.shrink_level > 0:
optimizer.queue += ['registerizeHarder']
else:
optimizer.queue += ['registerize']
# NOTE: Important that this comes after registerize/registerizeHarder
if shared.Settings.ELIMINATE_DUPLICATE_FUNCTIONS and options.opt_level >= 2:
optimizer.flush()
shared.Building.eliminate_duplicate_funcs(final)
save_intermediate('dfe')
if shared.Settings.EVAL_CTORS and options.memory_init_file and not use_source_map(options) and not shared.Settings.WASM:
optimizer.flush()
shared.Building.eval_ctors(final, memfile)
save_intermediate('eval-ctors')
if options.js_opts:
# some compilation modes require us to minify later or not at all
if not shared.Settings.EMTERPRETIFY and not shared.Settings.WASM:
optimizer.do_minify()
if options.opt_level >= 2:
optimizer.queue += ['asmLastOpts']
if shared.Settings.FINALIZE_ASM_JS:
optimizer.queue += ['last']
optimizer.flush()
if options.use_closure_compiler == 2 and not shared.Settings.WASM_BACKEND:
optimizer.flush()
logger.debug('running closure')
# no need to add this to js_transform_tempfiles, because closure and
# debug_level > 0 are never simultaneously true
final = shared.Building.closure_compiler(final, pretty=options.debug_level >= 1,
extra_closure_args=options.closure_args)
save_intermediate('closure')
log_time('js opts')
with ToolchainProfiler.profile_block('final emitting'):
if shared.Settings.EMTERPRETIFY:
emterpretify(js_target, optimizer, options)
# Remove some trivial whitespace
# TODO: do not run when compress has already been done on all parts of the code
# src = open(final).read()
# src = re.sub(r'\n+[ \n]*\n+', '\n', src)
# open(final, 'w').write(src)
# Bundle symbol data in with the cyberdwarf file
if shared.Settings.CYBERDWARF:
run_process([shared.PYTHON, shared.path_from_root('tools', 'emdebug_cd_merger.py'), target + '.cd', target + '.symbols'])
if use_source_map(options) and not shared.Settings.WASM:
emit_js_source_maps(target, optimizer.js_transform_tempfiles)
# track files that will need native eols
generated_text_files_with_native_eols = []
if (options.separate_asm or shared.Settings.WASM) and not shared.Settings.WASM_BACKEND:
separate_asm_js(final, asm_target)
generated_text_files_with_native_eols += [asm_target]
if shared.Settings.WASM:
do_binaryen(target, asm_target, options, memfile, wasm_binary_target,
wasm_text_target, wasm_source_map_target, misc_temp_files,
optimizer)
if shared.Settings.MODULARIZE:
modularize()
module_export_name_substitution()
# Run a final regex pass to clean up items that were not possible to optimize by Closure, or unoptimalities that were left behind
# by processing steps that occurred after Closure.
if shared.Settings.MINIMAL_RUNTIME == 2 and shared.Settings.USE_CLOSURE_COMPILER and options.debug_level == 0:
# Process .js runtime file
shared.run_process([shared.PYTHON, shared.path_from_root('tools', 'hacky_postprocess_around_closure_limitations.py'), final])
# Process .asm.js file
if not shared.Settings.WASM:
shared.run_process([shared.PYTHON, shared.path_from_root('tools', 'hacky_postprocess_around_closure_limitations.py'), asm_target])
# The JS is now final. Move it to its final location
shutil.move(final, js_target)
generated_text_files_with_native_eols += [js_target]
# If we were asked to also generate HTML, do that
if final_suffix == '.html':
generate_html(target, options, js_target, target_basename,
asm_target, wasm_binary_target,
memfile, optimizer)
else:
if options.proxy_to_worker:
generate_worker_js(target, js_target, target_basename)
if embed_memfile(options) and memfile:
shared.try_delete(memfile)
for f in generated_text_files_with_native_eols:
tools.line_endings.convert_line_endings_in_file(f, os.linesep, options.output_eol)
log_time('final emitting')
# exit block 'final emitting'
finally:
if DEBUG:
shared.Cache.release_cache_lock()
if DEBUG:
logger.debug('total time: %.2f seconds', (time.time() - start_time))
return 0
def parse_args(newargs):
options = EmccOptions()
settings_changes = []
should_exit = False
def check_bad_eq(arg):
if '=' in arg:
exit_with_error('Invalid parameter (do not use "=" with "--" options)')
for i in range(len(newargs)):
# On Windows Vista (and possibly others), excessive spaces in the command line
# leak into the items in this array, so trim e.g. 'foo.cpp ' -> 'foo.cpp'
newargs[i] = newargs[i].strip()
if newargs[i].startswith('-O'):
# Let -O default to -O2, which is what gcc does.
options.requested_level = newargs[i][2:] or '2'
if options.requested_level == 's':
options.llvm_opts = ['-Os']
options.requested_level = 2
options.shrink_level = 1
settings_changes.append('INLINING_LIMIT=50')
elif options.requested_level == 'z':
options.llvm_opts = ['-Oz']
options.requested_level = 2
options.shrink_level = 2
settings_changes.append('INLINING_LIMIT=25')
options.opt_level = validate_arg_level(options.requested_level, 3, 'Invalid optimization level: ' + newargs[i], clamp=True)
elif newargs[i].startswith('--js-opts'):
check_bad_eq(newargs[i])
options.js_opts = int(newargs[i + 1])
if options.js_opts:
options.force_js_opts = True
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--llvm-opts'):
check_bad_eq(newargs[i])
options.llvm_opts = parse_value(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--llvm-lto'):
check_bad_eq(newargs[i])
options.llvm_lto = int(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--closure-args'):
check_bad_eq(newargs[i])
args = newargs[i + 1]
options.closure_args += shlex.split(args)
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--closure'):
check_bad_eq(newargs[i])
options.use_closure_compiler = int(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--js-transform'):
check_bad_eq(newargs[i])
options.js_transform = newargs[i + 1]
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--pre-js'):
check_bad_eq(newargs[i])
options.pre_js += open(newargs[i + 1]).read() + '\n'
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--post-js'):
check_bad_eq(newargs[i])
options.post_js += open(newargs[i + 1]).read() + '\n'
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--minify'):
check_bad_eq(newargs[i])
assert newargs[i + 1] == '0', '0 is the only supported option for --minify; 1 has been deprecated'
options.debug_level = max(1, options.debug_level)
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('-g'):
requested_level = newargs[i][2:] or '3'
options.debug_level = validate_arg_level(requested_level, 4, 'Invalid debug level: ' + newargs[i])
options.requested_debug = newargs[i]
newargs[i] = ''
elif newargs[i] == '-profiling' or newargs[i] == '--profiling':
options.debug_level = max(options.debug_level, 2)
options.profiling = True
newargs[i] = ''
elif newargs[i] == '-profiling-funcs' or newargs[i] == '--profiling-funcs':
options.profiling_funcs = True
newargs[i] = ''
elif newargs[i] == '--tracing' or newargs[i] == '--memoryprofiler':
if newargs[i] == '--memoryprofiler':
options.memory_profiler = True
options.tracing = True
newargs[i] = ''
newargs.append('-D__EMSCRIPTEN_TRACING__=1')
settings_changes.append("EMSCRIPTEN_TRACING=1")
options.js_libraries.append(shared.path_from_root('src', 'library_trace.js'))
elif newargs[i] == '--emit-symbol-map':
options.emit_symbol_map = True
shared.Settings.EMIT_SYMBOL_MAP = 1
newargs[i] = ''
elif newargs[i] == '--bind':
shared.Settings.EMBIND = 1
newargs[i] = ''
options.js_libraries.append(shared.path_from_root('src', 'embind', 'emval.js'))
options.js_libraries.append(shared.path_from_root('src', 'embind', 'embind.js'))
if options.default_cxx_std:
# Force C++11 for embind code, but only if user has not explicitly overridden a standard.
options.default_cxx_std = '-std=c++11'
elif newargs[i].startswith('-std=') or newargs[i].startswith('--std='):
# User specified a standard to use, clear Emscripten from specifying it.
options.default_cxx_std = None
elif newargs[i].startswith('--embed-file'):
check_bad_eq(newargs[i])
options.embed_files.append(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--preload-file'):
check_bad_eq(newargs[i])
options.preload_files.append(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--exclude-file'):
check_bad_eq(newargs[i])
options.exclude_files.append(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--use-preload-cache'):
options.use_preload_cache = True
newargs[i] = ''
elif newargs[i].startswith('--no-heap-copy'):
options.no_heap_copy = True
newargs[i] = ''
elif newargs[i].startswith('--use-preload-plugins'):
options.use_preload_plugins = True
newargs[i] = ''
elif newargs[i] == '--ignore-dynamic-linking':
options.ignore_dynamic_linking = True
newargs[i] = ''
elif newargs[i] == '-v':
shared.PRINT_STAGES = True
shared.check_sanity(force=True)
elif newargs[i].startswith('--shell-file'):
check_bad_eq(newargs[i])
options.shell_path = newargs[i + 1]
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--source-map-base'):
check_bad_eq(newargs[i])
options.source_map_base = newargs[i + 1]
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i].startswith('--js-library'):
check_bad_eq(newargs[i])
options.js_libraries.append(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i] == '--remove-duplicates':
logger.warning('--remove-duplicates is deprecated as it is no longer needed. If you cannot link without it, file a bug with a testcase')
newargs[i] = ''
elif newargs[i] == '--jcache':
logger.error('jcache is no longer supported')
newargs[i] = ''
elif newargs[i] == '--cache':
check_bad_eq(newargs[i])
os.environ['EM_CACHE'] = os.path.normpath(newargs[i + 1])
shared.reconfigure_cache()
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i] == '--clear-cache':
logger.info('clearing cache as requested by --clear-cache')
shared.Cache.erase()
shared.check_sanity(force=True) # this is a good time for a sanity check
should_exit = True
elif newargs[i] == '--clear-ports':
logger.info('clearing ports and cache as requested by --clear-ports')
system_libs.Ports.erase()
shared.Cache.erase()
shared.check_sanity(force=True) # this is a good time for a sanity check
should_exit = True
elif newargs[i] == '--show-ports':
system_libs.show_ports()
should_exit = True
elif newargs[i] == '--save-bc':
check_bad_eq(newargs[i])
options.save_bc = newargs[i + 1]
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i] == '--memory-init-file':
check_bad_eq(newargs[i])
options.memory_init_file = int(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i] == '--proxy-to-worker':
options.proxy_to_worker = True
newargs[i] = ''
elif newargs[i] == '--valid-abspath':
options.valid_abspaths.append(newargs[i + 1])
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i] == '--separate-asm':
options.separate_asm = True
newargs[i] = ''
elif newargs[i].startswith(('-I', '-L')):
options.path_name = newargs[i][2:]
if os.path.isabs(options.path_name) and not is_valid_abspath(options, options.path_name):
# Of course an absolute path to a non-system-specific library or header
# is fine, and you can ignore this warning. The danger are system headers
# that are e.g. x86 specific and nonportable. The emscripten bundled
# headers are modified to be portable, local system ones are generally not.
shared.WarningManager.warn(
'ABSOLUTE_PATHS', '-I or -L of an absolute path "' + newargs[i] +
'" encountered. If this is to a local system header/library, it may '
'cause problems (local system files make sense for compiling natively '
'on your system, but not necessarily to JavaScript).')
elif newargs[i] == '--emrun':
options.emrun = True
newargs[i] = ''
elif newargs[i] == '--cpuprofiler':
options.cpu_profiler = True
newargs[i] = ''
elif newargs[i] == '--threadprofiler':
options.thread_profiler = True
settings_changes.append('PTHREADS_PROFILING=1')
newargs[i] = ''
elif newargs[i] == '-fno-exceptions':
settings_changes.append('DISABLE_EXCEPTION_THROWING=1')
elif newargs[i] == '-fexceptions':
settings_changes.append('DISABLE_EXCEPTION_THROWING=0')
elif newargs[i] == '--default-obj-ext':
newargs[i] = ''
options.default_object_extension = newargs[i + 1]
if not options.default_object_extension.startswith('.'):
options.default_object_extension = '.' + options.default_object_extension
newargs[i + 1] = ''
elif newargs[i].startswith("-fsanitize=cfi"):
options.cfi = True
elif newargs[i] == "--output_eol":
if newargs[i + 1].lower() == 'windows':
options.output_eol = '\r\n'
elif newargs[i + 1].lower() == 'linux':
options.output_eol = '\n'
else:
exit_with_error('Invalid value "' + newargs[i + 1] + '" to --output_eol!')
newargs[i] = ''
newargs[i + 1] = ''
elif newargs[i] == '--generate-config':
optarg = newargs[i + 1]
path = os.path.expanduser(optarg)
if os.path.exists(path):
exit_with_error('File ' + optarg + ' passed to --generate-config already exists!')
else:
shared.generate_config(optarg)
should_exit = True
# Record SIMD setting because it controls whether the autovectorizer runs
elif newargs[i] == '-msimd128':
settings_changes.append('SIMD=1')
elif newargs[i] == '-mno-simd128':
settings_changes.append('SIMD=0')
# Record USE_PTHREADS setting because it controls whether --shared-memory is passed to lld
elif newargs[i] == '-pthread':
settings_changes.append('USE_PTHREADS=1')
elif newargs[i] in ('-fno-diagnostics-color', '-fdiagnostics-color=never'):
colored_logger.disable()
elif newargs[i] == '-no-canonical-prefixes':
options.expand_symlinks = False
if should_exit:
sys.exit(0)
newargs = [arg for arg in newargs if arg]
return options, settings_changes, newargs
def emterpretify(js_target, optimizer, options):
global final
optimizer.flush('pre-emterpretify')
logger.debug('emterpretifying')
blacklist = shared.Settings.EMTERPRETIFY_BLACKLIST
whitelist = shared.Settings.EMTERPRETIFY_WHITELIST
synclist = shared.Settings.EMTERPRETIFY_SYNCLIST
if type(blacklist) == list:
blacklist = json.dumps(blacklist)
if type(whitelist) == list:
whitelist = json.dumps(whitelist)
if type(synclist) == list:
synclist = json.dumps(synclist)
args = [shared.PYTHON,
shared.path_from_root('tools', 'emterpretify.py'),
js_target,
final + '.em.js',
blacklist,
whitelist,
synclist,
str(shared.Settings.SWAPPABLE_ASM_MODULE)]
if shared.Settings.EMTERPRETIFY_ASYNC:
args += ['ASYNC=1']
if shared.Settings.EMTERPRETIFY_ADVISE:
args += ['ADVISE=1']
if options.profiling or options.profiling_funcs:
args += ['PROFILING=1']
if shared.Settings.ASSERTIONS:
args += ['ASSERTIONS=1']
if shared.Settings.PRECISE_F32:
args += ['FROUND=1']
if shared.Settings.ALLOW_MEMORY_GROWTH:
args += ['MEMORY_SAFE=1']
if shared.Settings.EMTERPRETIFY_FILE:
args += ['FILE="' + shared.Settings.EMTERPRETIFY_FILE + '"']
try:
# move temp js to final position, alongside its mem init file
shutil.move(final, js_target)
shared.check_call(args)
finally:
shared.try_delete(js_target)
final = final + '.em.js'
if shared.Settings.EMTERPRETIFY_ADVISE:
logger.warning('halting compilation due to EMTERPRETIFY_ADVISE')
sys.exit(0)
# minify (if requested) after emterpreter processing, and finalize output
logger.debug('finalizing emterpreted code')
shared.Settings.FINALIZE_ASM_JS = 1
if not shared.Settings.WASM:
optimizer.do_minify()
optimizer.queue += ['last']
optimizer.flush('finalizing-emterpreted-code')
# finalize the original as well, if we will be swapping it in (TODO: add specific option for this)
if shared.Settings.SWAPPABLE_ASM_MODULE:
real = final
original = js_target + '.orig.js' # the emterpretify tool saves the original here
final = original
logger.debug('finalizing original (non-emterpreted) code at ' + final)
if not shared.Settings.WASM:
optimizer.do_minify()
optimizer.queue += ['last']
optimizer.flush('finalizing-original-code')
safe_copy(final, original)
final = real
def emit_js_source_maps(target, js_transform_tempfiles):
logger.debug('generating source maps')
jsrun.run_js_tool(shared.path_from_root('tools', 'source-maps', 'sourcemapper.js'),
shared.NODE_JS, js_transform_tempfiles +
['--sourceRoot', os.getcwd(),
'--mapFileBaseName', target,
'--offset', '0'])
def separate_asm_js(final, asm_target):
"""Separate out the asm.js code, if asked. Or, if necessary for another option"""
logger.debug('separating asm')
shared.check_call([shared.PYTHON, shared.path_from_root('tools', 'separate_asm.py'), final, asm_target, final, shared.Settings.SEPARATE_ASM_MODULE_NAME])
def do_binaryen(target, asm_target, options, memfile, wasm_binary_target,
wasm_text_target, wasm_source_map_target, misc_temp_files,
optimizer):
global final
logger.debug('using binaryen')
binaryen_bin = shared.Building.get_binaryen_bin()
# whether we need to emit -g (function name debug info) in the final wasm
debug_info = options.debug_level >= 2 or options.profiling_funcs
# whether we need to emit -g in the intermediate binaryen invocations (but not necessarily at the very end).
# this is necessary for emitting a symbol map at the end.
intermediate_debug_info = bool(debug_info or options.emit_symbol_map or shared.Settings.ASYNCIFY_WHITELIST or shared.Settings.ASYNCIFY_BLACKLIST)
emit_symbol_map = options.emit_symbol_map or shared.Settings.CYBERDWARF
# finish compiling to WebAssembly, using asm2wasm, if we didn't already emit WebAssembly directly using the wasm backend.
if not shared.Settings.WASM_BACKEND:
if DEBUG:
# save the asm.js input
shared.safe_copy(asm_target, os.path.join(shared.get_emscripten_temp_dir(), os.path.basename(asm_target)))
cmd = [os.path.join(binaryen_bin, 'asm2wasm'), asm_target, '--total-memory=' + str(shared.Settings.TOTAL_MEMORY)]
if shared.Settings.BINARYEN_TRAP_MODE not in ('js', 'clamp', 'allow'):
exit_with_error('invalid BINARYEN_TRAP_MODE value: ' + shared.Settings.BINARYEN_TRAP_MODE + ' (should be js/clamp/allow)')
cmd += ['--trap-mode=' + shared.Settings.BINARYEN_TRAP_MODE]
if shared.Settings.BINARYEN_IGNORE_IMPLICIT_TRAPS:
cmd += ['--ignore-implicit-traps']
# pass optimization level to asm2wasm (if not optimizing, or which passes we should run was overridden, do not optimize)
if options.opt_level > 0:
cmd.append(shared.Building.opt_level_to_str(options.opt_level, options.shrink_level))
# import mem init file if it exists, and if we will not be using asm.js as a binaryen method (as it needs the mem init file, of course)
mem_file_exists = options.memory_init_file and os.path.exists(memfile)
import_mem_init = mem_file_exists and shared.Settings.MEM_INIT_IN_WASM
if import_mem_init:
cmd += ['--mem-init=' + memfile]
if not shared.Settings.RELOCATABLE:
cmd += ['--mem-base=' + str(shared.Settings.GLOBAL_BASE)]
# various options imply that the imported table may not be the exact size as
# the wasm module's own table segments
if shared.Settings.RELOCATABLE or shared.Settings.RESERVED_FUNCTION_POINTERS > 0 or shared.Settings.EMULATED_FUNCTION_POINTERS:
cmd += ['--table-max=-1']
if shared.Settings.SIDE_MODULE:
cmd += ['--mem-max=-1']
elif shared.Settings.WASM_MEM_MAX >= 0:
cmd += ['--mem-max=' + str(shared.Settings.WASM_MEM_MAX)]
if shared.Settings.LEGALIZE_JS_FFI != 1:
cmd += ['--no-legalize-javascript-ffi']
if shared.Building.is_wasm_only():
cmd += ['--wasm-only'] # this asm.js is code not intended to run as asm.js, it is only ever going to be wasm, an can contain special fastcomp-wasm support
if shared.Settings.USE_PTHREADS:
cmd += ['--enable-threads']
if intermediate_debug_info:
cmd += ['-g']
if emit_symbol_map:
cmd += ['--symbolmap=' + target + '.symbols']
# we prefer to emit a binary, as it is more efficient. however, when we
# want full debug info support (not just function names), then we must
# emit text (at least until wasm gains support for debug info in binaries)
target_binary = options.debug_level < 3
if target_binary:
cmd += ['-o', wasm_binary_target]
else:
cmd += ['-o', wasm_text_target, '-S']
cmd += shared.Building.get_binaryen_feature_flags()
logger.debug('asm2wasm (asm.js => WebAssembly): ' + ' '.join(cmd))
TimeLogger.update()
shared.check_call(cmd)
if not target_binary:
cmd = [os.path.join(binaryen_bin, 'wasm-as'), wasm_text_target, '-o', wasm_binary_target, '--all-features', '--disable-bulk-memory']
if intermediate_debug_info:
cmd += ['-g']
if use_source_map(options):
cmd += ['--source-map=' + wasm_source_map_target]
cmd += ['--source-map-url=' + options.source_map_base + os.path.basename(wasm_binary_target) + '.map']
logger.debug('wasm-as (text => binary): ' + ' '.join(cmd))
shared.check_call(cmd)
if import_mem_init:
# remove the mem init file in later processing; it does not need to be prefetched in the html, etc.
if DEBUG:
safe_move(memfile, os.path.join(shared.get_emscripten_temp_dir(), os.path.basename(memfile)))
else:
os.unlink(memfile)
log_time('asm2wasm')
if options.binaryen_passes:
if '--post-emscripten' in options.binaryen_passes:
# the value of the sbrk pointer has been computed by the JS compiler, and we can apply it in the wasm
# (we can't add this value when we placed post-emscripten in the proper position in the list of
# passes because that was before the value was computed)
options.binaryen_passes += ['--pass-arg=emscripten-sbrk-ptr@%d' % shared.Settings.DYNAMICTOP_PTR]
if shared.Settings.STANDALONE_WASM:
options.binaryen_passes += ['--pass-arg=emscripten-sbrk-val@%d' % shared.Settings.DYNAMIC_BASE]
if DEBUG:
shared.safe_copy(wasm_binary_target, os.path.join(shared.get_emscripten_temp_dir(), os.path.basename(wasm_binary_target) + '.pre-byn'))
cmd = [os.path.join(binaryen_bin, 'wasm-opt'), wasm_binary_target, '-o', wasm_binary_target] + options.binaryen_passes
cmd += shared.Building.get_binaryen_feature_flags()
if intermediate_debug_info:
cmd += ['-g'] # preserve the debug info
if use_source_map(options):
cmd += ['--input-source-map=' + wasm_source_map_target]
cmd += ['--output-source-map=' + wasm_source_map_target]
cmd += ['--output-source-map-url=' + options.source_map_base + os.path.basename(wasm_binary_target) + '.map']
if DEBUG:
shared.safe_copy(wasm_source_map_target, os.path.join(shared.get_emscripten_temp_dir(), os.path.basename(wasm_source_map_target) + '.pre-byn'))
logger.debug('wasm-opt on binaryen passes: %s', cmd)
shared.print_compiler_stage(cmd)
shared.check_call(cmd)
if shared.Settings.BINARYEN_SCRIPTS:
binaryen_scripts = os.path.join(shared.BINARYEN_ROOT, 'scripts')
script_env = os.environ.copy()
root_dir = os.path.abspath(os.path.dirname(__file__))
if script_env.get('PYTHONPATH'):
script_env['PYTHONPATH'] += ':' + root_dir
else:
script_env['PYTHONPATH'] = root_dir
for script in shared.Settings.BINARYEN_SCRIPTS.split(','):
logger.debug('running binaryen script: ' + script)
shared.check_call([shared.PYTHON, os.path.join(binaryen_scripts, script), final, wasm_text_target], env=script_env)
if shared.Settings.EVAL_CTORS:
if DEBUG:
save_intermediate_with_wasm('pre-eval-ctors', wasm_binary_target)
shared.Building.eval_ctors(final, wasm_binary_target, binaryen_bin, debug_info=intermediate_debug_info)
# after generating the wasm, do some final operations
if shared.Settings.SIDE_MODULE and not shared.Settings.WASM_BACKEND:
wso = shared.WebAssembly.make_shared_library(final, wasm_binary_target, shared.Settings.RUNTIME_LINKED_LIBS)
# replace the wasm binary output with the dynamic library.
# TODO: use a specific suffix for such files?
shutil.move(wso, wasm_binary_target)
if not DEBUG:
os.unlink(asm_target) # we don't need the asm.js, it can just confuse
# after generating the wasm, do some final operations
if shared.Settings.EMIT_EMSCRIPTEN_METADATA:
shared.WebAssembly.add_emscripten_metadata(final, wasm_binary_target)
if shared.Settings.SIDE_MODULE:
sys.exit(0) # and we are done.
# pthreads memory growth requires some additional JS fixups
if shared.Settings.USE_PTHREADS and shared.Settings.ALLOW_MEMORY_GROWTH:
final = shared.Building.apply_wasm_memory_growth(final)
if options.opt_level >= 2 and options.debug_level <= 2:
# minify the JS
optimizer.do_minify() # calculate how to minify
save_intermediate_with_wasm('preclean', wasm_binary_target)
final = shared.Building.minify_wasm_js(js_file=final,
wasm_file=wasm_binary_target,
expensive_optimizations=will_metadce(options),
minify_whitespace=optimizer.minify_whitespace,
debug_info=intermediate_debug_info,
emitting_js=not target.endswith(WASM_ENDINGS))
save_intermediate_with_wasm('postclean', wasm_binary_target)
def run_closure_compiler(final):
final = shared.Building.closure_compiler(final, pretty=not optimizer.minify_whitespace,
extra_closure_args=options.closure_args)
save_intermediate_with_wasm('closure', wasm_binary_target)
return final
if options.use_closure_compiler:
final = run_closure_compiler(final)
symbols_file = target + '.symbols' if options.emit_symbol_map else None
if shared.Settings.WASM2JS:
final = shared.Building.wasm2js(final,
wasm_binary_target,
opt_level=options.opt_level,
minify_whitespace=optimizer.minify_whitespace,
use_closure_compiler=options.use_closure_compiler,
debug_info=intermediate_debug_info,
symbols_file=symbols_file)
save_intermediate('wasm2js')
shared.try_delete(wasm_binary_target)
# emit the final symbols, either in the binary or in a symbol map.
# this will also remove debug info if we only kept it around in the intermediate invocations.
# note that wasm2js handles the symbol map itself (as it manipulates and then
# replaces the wasm with js)
if intermediate_debug_info and not shared.Settings.WASM2JS:
shared.Building.handle_final_wasm_symbols(wasm_file=wasm_binary_target, symbols_file=symbols_file, debug_info=debug_info)
save_intermediate_with_wasm('symbolmap', wasm_binary_target)
# replace placeholder strings with correct subresource locations
if shared.Settings.SINGLE_FILE:
js = open(final).read()
for target, replacement_string, should_embed in (
(wasm_binary_target,
shared.FilenameReplacementStrings.WASM_BINARY_FILE,
True),
(asm_target,
shared.FilenameReplacementStrings.ASMJS_CODE_FILE,
False),
):
if should_embed and os.path.isfile(target):
js = js.replace(replacement_string, shared.JS.get_subresource_location(target))
else:
js = js.replace(replacement_string, '')
shared.try_delete(target)
with open(final, 'w') as f:
f.write(js)
def modularize():
global final
logger.debug('Modularizing, assigning to var ' + shared.Settings.EXPORT_NAME)
src = open(final).read()
# TODO: exports object generation for MINIMAL_RUNTIME
exports_object = '{}' if shared.Settings.MINIMAL_RUNTIME else shared.Settings.EXPORT_NAME
src = '''
function(%(EXPORT_NAME)s) {
%(EXPORT_NAME)s = %(EXPORT_NAME)s || {};
%(src)s
return %(exports_object)s
}
''' % {
'EXPORT_NAME': shared.Settings.EXPORT_NAME,
'src': src,
'exports_object': exports_object
}
if not shared.Settings.MODULARIZE_INSTANCE:
if shared.Settings.MINIMAL_RUNTIME and not shared.Settings.USE_PTHREADS:
# Single threaded MINIMAL_RUNTIME programs do not need access to
# document.currentScript, so a simple export declaration is enough.
src = 'var %s=%s' % (shared.Settings.EXPORT_NAME, src)
else:
# When MODULARIZE this JS may be executed later,
# after document.currentScript is gone, so we save it.
# (when MODULARIZE_INSTANCE, an instance is created
# immediately anyhow, like in non-modularize mode)
# In EXPORT_ES6 + USE_PTHREADS the 'thread' is actually an ES6 module webworker running in strict mode,
# so doesn't have access to 'document'. In this case use 'import.meta' instead.
if shared.Settings.EXPORT_ES6 and shared.Settings.USE_ES6_IMPORT_META:
script_url = "import.meta.url"
else:
script_url = "typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined"
src = '''
var %(EXPORT_NAME)s = (function() {
var _scriptDir = %(script_url)s;
return (%(src)s);
})();
''' % {
'EXPORT_NAME': shared.Settings.EXPORT_NAME,
'src': src,
'script_url': script_url
}
else:
# Create the MODULARIZE_INSTANCE instance
# Note that we notice the global Module object, just like in normal
# non-MODULARIZE mode (while MODULARIZE has the user create the instances,
# and the user can decide whether to use Module there or something
# else etc.).
src = '''
var %(EXPORT_NAME)s = (%(src)s)(typeof %(EXPORT_NAME)s === 'object' ? %(EXPORT_NAME)s : {});
''' % {
'EXPORT_NAME': shared.Settings.EXPORT_NAME,
'src': src
}
final = final + '.modular.js'
with open(final, 'w') as f:
f.write(src)
# Export using a UMD style export, or ES6 exports if selected
if shared.Settings.EXPORT_ES6:
f.write('''export default %s;''' % shared.Settings.EXPORT_NAME)
elif not shared.Settings.MINIMAL_RUNTIME:
f.write('''if (typeof exports === 'object' && typeof module === 'object')
module.exports = %(EXPORT_NAME)s;
else if (typeof define === 'function' && define['amd'])
define([], function() { return %(EXPORT_NAME)s; });
else if (typeof exports === 'object')
exports["%(EXPORT_NAME)s"] = %(EXPORT_NAME)s;
''' % {
'EXPORT_NAME': shared.Settings.EXPORT_NAME
})
save_intermediate('modularized')
def module_export_name_substitution():
global final
logger.debug('Private module export name substitution with ' + shared.Settings.EXPORT_NAME)
src = open(final).read()
final = final + '.module_export_name_substitution.js'
if shared.Settings.MINIMAL_RUNTIME:
# In MINIMAL_RUNTIME the Module object is always present to provide the .asm.js/.wasm content
replacement = shared.Settings.EXPORT_NAME
else:
replacement = "typeof %(EXPORT_NAME)s !== 'undefined' ? %(EXPORT_NAME)s : {}" % {"EXPORT_NAME": shared.Settings.EXPORT_NAME}
with open(final, 'w') as f:
src = src.replace(shared.JS.module_export_name_substitution_pattern, replacement)
# For Node.js and other shell environments, create an unminified Module object so that
# loading external .asm.js file that assigns to Module['asm'] works even when Closure is used.
if shared.Settings.MINIMAL_RUNTIME and (shared.Settings.target_environment_may_be('node') or
shared.Settings.target_environment_may_be('shell')):
src = 'if(typeof Module==="undefined"){var Module={};}' + src
f.write(src)
save_intermediate('module_export_name_substitution')
def generate_minimal_runtime_html(target, options, js_target, target_basename,
asm_target, wasm_binary_target,
memfile, optimizer):
logger.debug('generating HTML for minimal runtime')
shell = read_and_preprocess(options.shell_path)
if re.search(r'{{{\s*SCRIPT\s*}}}', shell):
exit_with_error('--shell-file "' + options.shell_path + '": MINIMAL_RUNTIME uses a different kind of HTML page shell file than the traditional runtime! Please see $EMSCRIPTEN/src/shell_minimal_runtime.html for a template to use as a basis.')
shell = shell.replace('{{{ TARGET_BASENAME }}}', target_basename)
shell = shell.replace('{{{ EXPORT_NAME }}}', shared.Settings.EXPORT_NAME)
shell = tools.line_endings.convert_line_endings(shell, '\n', options.output_eol)
with open(target, 'wb') as f:
f.write(asbytes(shell))
def generate_traditional_runtime_html(target, options, js_target, target_basename,
asm_target, wasm_binary_target,
memfile, optimizer):
script = ScriptSource()
shell = read_and_preprocess(options.shell_path)
assert '{{{ SCRIPT }}}' in shell, 'HTML shell must contain {{{ SCRIPT }}} , see src/shell.html for an example'
base_js_target = os.path.basename(js_target)
asm_mods = []
if options.proxy_to_worker:
proxy_worker_filename = (shared.Settings.PROXY_TO_WORKER_FILENAME or target_basename) + '.js'
worker_js = worker_js_script(proxy_worker_filename)
script.inline = ('''
var filename = '%s';
if ((',' + window.location.search.substr(1) + ',').indexOf(',noProxy,') < 0) {
console.log('running code in a web worker');
''' % shared.JS.get_subresource_location(proxy_worker_filename)) + worker_js + '''
} else {
// note: no support for code mods (PRECISE_F32==2)
console.log('running code on the main thread');
var fileBytes = tryParseAsDataURI(filename);
var script = document.createElement('script');
if (fileBytes) {
script.innerHTML = intArrayToString(fileBytes);
} else {
script.src = filename;
}
document.body.appendChild(script);
}
'''
else:
# Normal code generation path
script.src = base_js_target
asm_mods = client_mods.get_mods(shared.Settings,
minified='minifyNames' in optimizer.queue_history,
separate_asm=options.separate_asm)
if not shared.Settings.SINGLE_FILE:
if shared.Settings.EMTERPRETIFY_FILE:
# We need to load the emterpreter file before anything else, it has to be synchronously ready
script.un_src()
script.inline = '''
var emterpretURL = '%s';
var emterpretXHR = new XMLHttpRequest();
emterpretXHR.open('GET', emterpretURL, true);
emterpretXHR.responseType = 'arraybuffer';
emterpretXHR.onload = function() {
if (emterpretXHR.status === 200 || emterpretXHR.status === 0) {
Module.emterpreterFile = emterpretXHR.response;
} else {
var emterpretURLBytes = tryParseAsDataURI(emterpretURL);
if (emterpretURLBytes) {
Module.emterpreterFile = emterpretURLBytes.buffer;
}
}
%s
};
emterpretXHR.send(null);
''' % (shared.JS.get_subresource_location(shared.Settings.EMTERPRETIFY_FILE), script.inline)
if options.memory_init_file and not shared.Settings.MEM_INIT_IN_WASM:
# start to load the memory init file in the HTML, in parallel with the JS
script.un_src()
script.inline = ('''
var memoryInitializer = '%s';
memoryInitializer = Module['locateFile'] ? Module['locateFile'](memoryInitializer, '') : memoryInitializer;
Module['memoryInitializerRequestURL'] = memoryInitializer;
var meminitXHR = Module['memoryInitializerRequest'] = new XMLHttpRequest();
meminitXHR.open('GET', memoryInitializer, true);
meminitXHR.responseType = 'arraybuffer';
meminitXHR.send(null);
''' % shared.JS.get_subresource_location(memfile)) + script.inline
# Download .asm.js if --separate-asm was passed in an asm.js build, or if 'asmjs' is one
# of the wasm run methods.
if not options.separate_asm or shared.Settings.WASM:
if len(asm_mods):
exit_with_error('no --separate-asm means no client code mods are possible')
else:
script.un_src()
if len(asm_mods) == 0:
# just load the asm, then load the rest
script.inline = '''
var filename = '%s';
var fileBytes = tryParseAsDataURI(filename);
var script = document.createElement('script');
if (fileBytes) {
script.innerHTML = intArrayToString(fileBytes);
} else {
script.src = filename;
}
script.onload = function() {
setTimeout(function() {
%s
}, 1); // delaying even 1ms is enough to allow compilation memory to be reclaimed
};
document.body.appendChild(script);
''' % (shared.JS.get_subresource_location(asm_target), script.inline)
else:
# may need to modify the asm code, load it as text, modify, and load asynchronously
script.inline = '''
var codeURL = '%s';
var codeXHR = new XMLHttpRequest();
codeXHR.open('GET', codeURL, true);
codeXHR.onload = function() {
var code;
if (codeXHR.status === 200 || codeXHR.status === 0) {
code = codeXHR.responseText;
} else {
var codeURLBytes = tryParseAsDataURI(codeURL);
if (codeURLBytes) {
code = intArrayToString(codeURLBytes);
}
}
%s
var blob = new Blob([code], { type: 'text/javascript' });
codeXHR = null;
var src = URL.createObjectURL(blob);
var script = document.createElement('script');
script.src = src;
script.onload = function() {
setTimeout(function() {
%s
}, 1); // delaying even 1ms is enough to allow compilation memory to be reclaimed
URL.revokeObjectURL(script.src);
};
document.body.appendChild(script);
};
codeXHR.send(null);
''' % (shared.JS.get_subresource_location(asm_target), '\n'.join(asm_mods), script.inline)
if shared.Settings.WASM and not shared.Settings.WASM_ASYNC_COMPILATION:
# We need to load the wasm file before anything else, it has to be synchronously ready TODO: optimize
script.un_src()
script.inline = '''
var wasmURL = '%s';
var wasmXHR = new XMLHttpRequest();
wasmXHR.open('GET', wasmURL, true);
wasmXHR.responseType = 'arraybuffer';
wasmXHR.onload = function() {
if (wasmXHR.status === 200 || wasmXHR.status === 0) {
Module.wasmBinary = wasmXHR.response;
} else {
var wasmURLBytes = tryParseAsDataURI(wasmURL);
if (wasmURLBytes) {
Module.wasmBinary = wasmURLBytes.buffer;
}
}
%s
};
wasmXHR.send(null);
''' % (shared.JS.get_subresource_location(wasm_binary_target), script.inline)
# when script.inline isn't empty, add required helper functions such as tryParseAsDataURI
if script.inline:
for filename in ('arrayUtils.js', 'base64Utils.js', 'URIUtils.js'):
content = read_and_preprocess(shared.path_from_root('src', filename))
script.inline = content + script.inline
script.inline = 'var ASSERTIONS = %s;\n%s' % (shared.Settings.ASSERTIONS, script.inline)
# inline script for SINGLE_FILE output
if shared.Settings.SINGLE_FILE:
js_contents = script.inline or ''
if script.src:
js_contents += open(js_target).read()
shared.try_delete(js_target)
script.src = None
script.inline = js_contents
html_contents = shell.replace('{{{ SCRIPT }}}', script.replacement())
html_contents = tools.line_endings.convert_line_endings(html_contents, '\n', options.output_eol)
with open(target, 'wb') as f:
f.write(asbytes(html_contents))
def minify_html(filename, options):
opts = []
# -g1 and greater retain whitespace and comments in source
if options.debug_level == 0:
opts += ['--collapse-whitespace',
'--collapse-inline-tag-whitespace',
'--remove-comments',
'--remove-tag-whitespace',
'--sort-attributes',
'--sort-class-name']
# -g2 and greater do not minify HTML at all
if options.debug_level <= 1:
opts += ['--decode-entities',
'--collapse-boolean-attributes',
'--remove-attribute-quotes',
'--remove-redundant-attributes',
'--remove-script-type-attributes',
'--remove-style-link-type-attributes',
'--use-short-doctype',
'--minify-css', 'true',
'--minify-js', 'true']
# html-minifier also has the following options, but they look unsafe for use:
# '--remove-optional-tags': removes e.g. <head></head> and <body></body> tags from the page.
# (Breaks at least browser.test_sdl2glshader)
# '--remove-empty-attributes': removes all attributes with whitespace-only values.
# (Breaks at least browser.test_asmfs_hello_file)
# '--remove-empty-elements': removes all elements with empty contents.
# (Breaks at least browser.test_asm_swapping)
if options.debug_level >= 2:
return
logger.debug('minifying HTML file ' + filename)
size_before = os.path.getsize(filename)
start_time = time.time()
run_process(shared.NODE_JS + [shared.path_from_root('third_party', 'html-minifier', 'cli.js'), filename, '-o', filename] + opts)
elapsed_time = time.time() - start_time
size_after = os.path.getsize(filename)
delta = size_after - size_before
logger.debug('HTML minification took {:.2f}'.format(elapsed_time) + ' seconds, and shrunk size of ' + filename + ' from ' + str(size_before) + ' to ' + str(size_after) + ' bytes, delta=' + str(delta) + ' ({:+.2f}%)'.format(delta * 100.0 / size_before))
def generate_html(target, options, js_target, target_basename,
asm_target, wasm_binary_target,
memfile, optimizer):
logger.debug('generating HTML')
if shared.Settings.MINIMAL_RUNTIME:
generate_minimal_runtime_html(target, options, js_target, target_basename, asm_target,
wasm_binary_target, memfile, optimizer)
else:
generate_traditional_runtime_html(target, options, js_target, target_basename, asm_target,
wasm_binary_target, memfile, optimizer)
if shared.Settings.MINIFY_HTML and (options.opt_level >= 1 or options.shrink_level >= 1):
minify_html(target, options)
def generate_worker_js(target, js_target, target_basename):
# compiler output is embedded as base64
if shared.Settings.SINGLE_FILE:
proxy_worker_filename = shared.JS.get_subresource_location(js_target)
# compiler output goes in .worker.js file
else:
shutil.move(js_target, unsuffixed(js_target) + '.worker.js')
worker_target_basename = target_basename + '.worker'
proxy_worker_filename = (shared.Settings.PROXY_TO_WORKER_FILENAME or worker_target_basename) + '.js'
target_contents = worker_js_script(proxy_worker_filename)
open(target, 'w').write(target_contents)
def worker_js_script(proxy_worker_filename):
web_gl_client_src = open(shared.path_from_root('src', 'webGLClient.js')).read()
idb_store_src = open(shared.path_from_root('src', 'IDBStore.js')).read()
proxy_client_src = (
open(shared.path_from_root('src', 'proxyClient.js')).read()
.replace('{{{ filename }}}', proxy_worker_filename)
.replace('{{{ IDBStore.js }}}', idb_store_src)
)
return web_gl_client_src + '\n' + proxy_client_src
def process_libraries(libs, lib_dirs, temp_files):
libraries = []
consumed = []
# Find library files
for i, lib in libs:
logger.debug('looking for library "%s"', lib)
suffixes = STATICLIB_ENDINGS + DYNAMICLIB_ENDINGS
if shared.Settings.WASM_BACKEND:
# under the wasm .a files are found using the normal -l/-L flags to
# the linker.
suffixes = DYNAMICLIB_ENDINGS
found = False
for prefix in LIB_PREFIXES:
for suff in suffixes:
name = prefix + lib + suff
for lib_dir in lib_dirs:
path = os.path.join(lib_dir, name)
if os.path.exists(path):
logger.debug('found library "%s" at %s', lib, path)
temp_files.append((i, path))
consumed.append(i)
found = True
break
if found:
break
if found:
break
if not found:
jslibs = shared.Building.path_to_system_js_libraries(lib)
if jslibs:
libraries += jslibs
consumed.append(i)
shared.Settings.SYSTEM_JS_LIBRARIES = libraries
return consumed
class ScriptSource(object):
def __init__(self):
self.src = None # if set, we have a script to load with a src attribute
self.inline = None # if set, we have the contents of a script to write inline in a script
def un_src(self):
"""Use this if you want to modify the script and need it to be inline."""
if self.src is None:
return
self.inline = '''
var script = document.createElement('script');
script.src = "%s";
document.body.appendChild(script);
''' % self.src
self.src = None
def replacement(self):
"""Returns the script tag to replace the {{{ SCRIPT }}} tag in the target"""
assert (self.src or self.inline) and not (self.src and self.inline)
if self.src:
return '<script async type="text/javascript" src="%s"></script>' % quote(self.src)
else:
return '<script>\n%s\n</script>' % self.inline
def is_valid_abspath(options, path_name):
# Any path that is underneath the emscripten repository root must be ok.
if shared.path_from_root().replace('\\', '/') in path_name.replace('\\', '/'):
return True
def in_directory(root, child):
# make both path absolute
root = os.path.realpath(root)
child = os.path.realpath(child)
# return true, if the common prefix of both is equal to directory
# e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
return os.path.commonprefix([root, child]) == root
for valid_abspath in options.valid_abspaths:
if in_directory(valid_abspath, path_name):
return True
return False
def parse_value(text):
# Note that using response files can introduce whitespace, if the file
# has a newline at the end. For that reason, we rstrip() in relevant
# places here.
def parse_string_value(text):
first = text[0]
if first == "'" or first == '"':
text = text.rstrip()
assert text[-1] == text[0] and len(text) > 1, 'unclosed opened quoted string. expected final character to be "%s" and length to be greater than 1 in "%s"' % (text[0], text)
return text[1:-1]
return text
def parse_string_list_members(text):
sep = ','
values = text.split(sep)
result = []
index = 0
while True:
current = values[index].lstrip() # Cannot safely rstrip for cases like: "HERE-> ,"
if not len(current):
exit_with_error('string array should not contain an empty value')
first = current[0]
if not(first == "'" or first == '"'):
result.append(current.rstrip())
else:
start = index
while True: # Continue until closing quote found
if index >= len(values):
exit_with_error("unclosed quoted string. expected final character to be '%s' in '%s'" % (first, values[start]))
new = values[index].rstrip()
if new and new[-1] == first:
if start == index:
result.append(current.rstrip()[1:-1])
else:
result.append((current + sep + new)[1:-1])
break
else:
current += sep + values[index]
index += 1
index += 1
if index >= len(values):
break
return result
def parse_string_list(text):
text = text.rstrip()
if text[-1] != ']':
exit_with_error('unclosed opened string list. expected final character to be "]" in "%s"' % (text))
inner = text[1:-1]
if inner.strip() == "":
return []
return parse_string_list_members(inner)
if text[0] == '[':
# if json parsing fails, we fall back to our own parser, which can handle a few
# simpler syntaxes
try:
return json.loads(text)
except ValueError:
return parse_string_list(text)
try:
return int(text)
except ValueError:
return parse_string_value(text)
def validate_arg_level(level_string, max_level, err_msg, clamp=False):
try:
level = int(level_string)
except ValueError:
raise Exception(err_msg)
if clamp:
if level > max_level:
logger.warning("optimization level '-O" + level_string + "' is not supported; using '-O" + str(max_level) + "' instead")
level = max_level
if not 0 <= level <= max_level:
raise Exception(err_msg)
return level
if __name__ == '__main__':
try:
sys.exit(run(sys.argv))
except KeyboardInterrupt:
logger.warning("KeyboardInterrupt")
sys.exit(1)
|
'use strict';
module.exports = {
event: state => socket => {
socket.write("Welcome to the game!\r\n");
return socket.emit('login', socket);
},
};
|
const keystone = require('keystone');
const Types = keystone.Field.Types;
const User = keystone.list('User');
const ObjectId = require('mongoose').Types.ObjectId;
const logger = keystone.get('logs').mail;
let Mail = new keystone.List('Mail', {
nocreate: true,
noedit: true,
track: true
});
Mail.add({
template: {
label: 'Шаблон',
type: Types.Select,
options: [
{value: 'enquiry-default', label: 'Simple'}
],
index: true,
required: true,
initial: true
},
to: {
label: 'Получатели',
type: Types.Relationship,
ref: 'User',
many: true,
index: true,
required: true,
initial: true
},
subject: {
label: 'Тема письма',
type: Types.Text,
required: true,
initial: true
},
message: {
label: 'Сообщение',
type: Types.Html,
wysiwyg: true,
required: true,
initial: true
}
});
Mail.schema.pre('save', require('../lib/wasNew'));
Mail.schema.post('save', function() {
if (this.wasNew) this.sendNotificationEmail();
});
Mail.schema.methods.sendNotificationEmail = function() {
let enquiry = this;
let recipients = enquiry.to.map((id) => {
return id instanceof ObjectId ? String(id) : String(id._id);
});
return User.model.find().where({_id: {$in: recipients}}).exec()
.then((users) => {
return new Promise((resolve, reject) => {
let email = new keystone.Email({
transport: 'nodemailer',
templateName: enquiry.template,
nodemailerConfig: {
host: process.env.NODEMAILER_SMTP_HOST,
port: process.env.NODEMAILER_SMTP_PORT,
secure: false,
tls: {
rejectUnauthorized: false
}
}
});
email.send({
to: users,
from: process.env.NODEMAILER_SENDER_EMAIL,
subject: enquiry.subject,
enquiry: enquiry
}, (err, info) => {
if (err) return reject(err);
resolve(info);
});
});
})
.catch((err) => {
logger.error(err, 'Error in Mail.sendNotificationEmail()');
});
};
Mail.defaultSort = '-createdAt';
Mail.defaultColumns = 'subject, to, createdAt';
Mail.register();
|
#!/usr/bin/env python3
# -*- coding: utf8 -*-
# SPDX-FileCopyrightText: 2022 UdS AES <https://www.uni-saarland.de/lehrstuhl/frey.html>
# SPDX-License-Identifier: MIT
"""Software agent for hypermedia API composition and execution."""
import os
import re
from urllib.parse import urlparse
import rdflib
import requests
from invoke import task
from loguru import logger
from rdflib.namespace import OWL, RDF, NamespaceManager
from . import logger
# Global constants/magic variables
SUCCESS = 0 # implies successful completion of an algorithm
FAILURE = 1 # implies that an algorithm failed to find a solution (_not_ an error!)
# Use namespace manager to enforce consistent prefixes
# https://rdflib.readthedocs.io/en/latest/namespaces_and_bindings.html
# --""--/apidocs/rdflib.html#rdflib.namespace.NamespaceManager
HTTP = rdflib.Namespace("http://www.w3.org/2011/http#")
REASON = rdflib.Namespace("http://www.w3.org/2000/10/swap/reason#")
SHACL = rdflib.Namespace("http://www.w3.org/ns/shacl#")
NAMESPACE_MANAGER = NamespaceManager(rdflib.Graph())
# FIXME read prefixes/namespaces from files instead of hardcoding?
NAMESPACE_MANAGER.bind("rdf", RDF)
NAMESPACE_MANAGER.bind("owl", OWL)
NAMESPACE_MANAGER.bind("http", HTTP)
NAMESPACE_MANAGER.bind("r", REASON)
NAMESPACE_MANAGER.bind("sh", SHACL)
# Compare https://rdflib.readthedocs.io/en/stable/plugin_parsers.html (both incomplete!)
RDFLIB_SERIALIZATIONS = [
"application/ld+json",
"application/n-triples",
"application/n-quads",
"application/rdf+xml",
"application/trig",
"text/n3",
"text/turtle",
"text/html",
]
# Utitily functions
def correct_n3_syntax(input):
"""Fix N3 syntax variants not universally supported."""
pattern = re.compile(
r"^(?P<prefix>PREFIX) (?P<abbrv>[\w-]*:) (?P<url><[\w\d:\/\.#-?=]+>)$",
re.MULTILINE,
)
output = pattern.sub(r"@prefix \g<abbrv> \g<url>.", input)
return output
def request_from_graph(graph, shapes_and_inputs):
"""Extract parts of an HTTP request from a graph."""
http_methods = [
"GET",
"POST",
"PUT",
"DELETE",
"HEAD",
"PATCH",
] # CONNECT, OPTIONS, TRACE are not part of RESTdesc (see definition 12)
request = None # to be assigned later
# Query graph for relevant information using SPARQL
a0 = graph.query(
(
"SELECT ?method ?uri ?headers ?body "
"WHERE { "
"?s http:methodName ?method. "
"?s http:requestURI ?uri. "
"OPTIONAL { ?s http:headers ?headers. }"
"OPTIONAL { ?s http:body ?body. }"
"}"
)
)
for method_rdfterm, uri_rdfterm, headers_rdfterm, body_rdfterm in a0:
logger.trace(
f"\n{method_rdfterm=}\n{uri_rdfterm=}"
f"\n{headers_rdfterm=}\n{body_rdfterm=}"
)
# Extract method and verify it's valid
method = method_rdfterm.n3().strip('"') # XXX use .toPython() instead?
logger.trace(f"{method=}")
if not (method in http_methods):
logger.warning(f"{method=} is not a supported HTTP method!")
continue
# Check URI for completeness/distinguish from blank nodes
url = urlparse(uri_rdfterm.n3().strip('<">'))
if url.scheme == "" or url.netloc == "":
logger.debug(f"{url=} is incomplete, i.e. _not_ ground!")
continue
# Prepare dictionary of headers to send
headers = None
serialization_desired = None
if headers_rdfterm is not None:
headers = {}
a1 = graph.query(
(
"SELECT ?fieldName ?fieldValue "
"WHERE { "
f"?r http:headers {headers_rdfterm.n3()} ."
f"{headers_rdfterm.n3()} http:fieldName ?fieldName ."
f"{headers_rdfterm.n3()} http:fieldValue ?fieldValue ."
"}"
)
) # TODO change query so headers for response get disregarded!
for k, v in a1:
key = k.n3().strip("\"'").lower()
value = v.n3().strip("\"'")
headers[key] = value
# Prepare body to send
body = None
if body_rdfterm is not None:
non_parseable = False
body_url = urlparse(body_rdfterm.n3().strip("<>"))
if body_url.scheme == "file":
raw = rdflib.Graph()
filtered = rdflib.Graph()
if (None, SHACL.targetNode, body_rdfterm) in shapes_and_inputs:
demand_user_input_is_ready(shapes_and_inputs, body_rdfterm)
try:
raw.parse(body_url.path)
if body_url.fragment != "":
filtered = raw # XXX only send relevant subgraph
else:
filtered = raw
except Exception:
non_parseable = True
if len(raw) == 0:
non_parseable = True
if non_parseable == False:
media_type = (
serialization_desired
if (
serialization_desired != None
and serialization_desired in RDFLIB_SERIALIZATIONS
)
else "text/turtle"
)
body = filtered.serialize(format=media_type)
if headers == None:
headers = {}
headers["content-type"] = media_type
# Work around https://github.com/RDFLib/rdflib/issues/677
body = body.replace(f"file://{body_url.path}", "")
else:
with open(body_url.path, "rb") as fp:
body = fp.read()
if headers == None:
headers = {}
headers["content-type"] = "application/octet-stream"
else:
raise NotImplementedError
# TODO Prepare other request parts
files = None
params = None
# ↓↓↓ SPECIFIC TO SIMaaS-EXAMPLE! TO BE DELETED HERE ###########################
if method == "POST" and url.path == "/models":
params = {
"records": "irradianceTemperatureWindSpeed2Power.plantRecord"
+ ",irradianceTemperatureWindSpeed2Power.location"
}
# ↑↑↑ SPECIFIC TO SIMaaS-EXAMPLE! TO BE DELETED HERE ###########################
auth = None
cookies = None
# Instantiate https://docs.python-requests.org/en/latest/api/#requests.Request
request = requests.Request(
method=method,
url=url.geturl(),
headers=headers,
files=files,
data=body,
params=params,
auth=auth,
cookies=cookies,
)
log_message = (
f"Found ground request:\n{request.method} {request.url}\n"
f"with {request.headers=}\n"
f" {request.params=}"
)
if body_rdfterm is not None:
log_message += f"\n request.data=<file://{body_url.path}>"
logger.log("DETAIL", log_message)
return request
def concatenate_eye_input_files(H, g, R, B=None):
logger.log("DETAIL", f"{H=}")
logger.log("DETAIL", f"{g=}")
logger.log("DETAIL", f"{R=}")
logger.log("DETAIL", f"{B=}")
input_files = []
input_files += R
input_files += H
if B is not None:
input_files.append(B)
return input_files
# Core functionality
def identify_shapes_for_user_input(R, B, directory):
"""For each rule in R, identify required user input defined through shapes.
Also add assumptions stating that there will be conformant data graphs so that the
pragmatic proof algorithm can derive an initial proof.
"""
logger.info("Identifying shapes and required user input...")
shapes_and_inputs = rdflib.Graph()
shapes_and_inputs.namespace_manager = NAMESPACE_MANAGER
# For each rule, assume that its implication can be realized (be optimistic!)
for rule in R:
logger.log("DETAIL", f"Searching shapes for user input in rule '{rule}'...")
# Load the facts specified as postcondition; i.e. assume the request succeeds
graph = rdflib.Graph()
graph.namespace_manager = NAMESPACE_MANAGER
with open(os.path.join(directory, rule)) as fp:
rule_text = fp.read()
# -> Extract prefix declarations
prefixes_regex = re.compile(
r"^(?P<prefix>@prefix) (?P<abbrv>[\w-]*:) (?P<url><[\w\d:\/\.#-]+>) *\.$",
re.MULTILINE,
)
prefixes_all = ""
for p, c, l in prefixes_regex.findall(rule_text):
prefixes_all += f"{p} {c} {l} .\n"
# -> Extract http-request and postcondition as `implication`
rule_regex = re.compile(
r"(?P<precondition>{[.\n\s_:?\w\";\/\[\]]*})\n*=>\n*"
+ r"{(?P<implication>[.\n\s_:?\w\";\/\[\]-]*\n*)}\s*\."
)
implication = rule_regex.search(rule_text).group("implication")
# -> Parse postcondition; prefixes added to make document valid
graph.parse(data=f"{prefixes_all}\n{implication}", format="n3")
# Identify shapes and their target nodes via SPARQL query
a0 = graph.query(
(
"SELECT ?s ?p ?o "
"WHERE { "
"?s ?p ?o ."
"?s rdf:type sh:NodeShape ."
"?s sh:targetNode ?o ."
"}"
)
)
# Add assumptions that valid input will be supplied by user eventually
if len(a0) > 0:
node = rdflib.URIRef(f"#{rule.split('.')[0]}")
shapes_and_inputs.add(
(
node,
REASON.source,
rdflib.URIRef(f"file://{os.path.join(directory, rule)}"),
)
)
for s, p, o in a0:
# existentially qualified variables are parsed as blank nodes by rdflib;
# -> turn `s` into `rdflib.Variable` with unique but non-limited name
s = rdflib.Variable(s.toPython())
# `?s sh:targetNode ?o` implies that `?o` is a user input specified via `?s`
# => replace `?o` by URIRef to file which will eventually contain the data
target_node = f"file://{os.path.join(directory, o.toPython())}.n3"
o = rdflib.URIRef(target_node)
shapes_and_inputs.add((s, p, o))
shapes_and_inputs.add((node, RDF.predicate, s))
logger.log("DETAIL", f"Identified target node <{target_node}>!")
# Make assumptions available as part of the API composition problem
if B != None:
background_graph = rdflib.Graph()
background_graph.namespace_manager = NAMESPACE_MANAGER
background_graph.parse(os.path.join(directory, B), format="n3")
background_graph.parse(
data=shapes_and_inputs.serialize(format="n3"), format="n3"
)
# Work around https://github.com/RDFLib/rdflib/issues/677
prefix_unwanted = (
f"file://{os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))}/"
)
background_graph_text = background_graph.serialize(format="n3").replace(
prefix_unwanted, ""
)
with open(os.path.join(directory, B), "w") as fp:
fp.write(background_graph_text)
else:
raise NotImplementedError # TODO users don't always specify B -> deal with it
return shapes_and_inputs
def update_shapes_and_input(shapes_and_inputs, knowledge_gained, rule_iri, file_iri):
"""Replace variables in the shapes/inputs-graph with content provided by API."""
logger.info("Updating graph that tracks shapes, assumptions and user input...")
def choose_term_over_variable(x1, x2):
"""Return the more specific of the two rdflib-terms."""
if (isinstance(x1, rdflib.Variable) or isinstance(x1, rdflib.BNode)) and (
(isinstance(x2, rdflib.URIRef)) or isinstance(x2, rdflib.Literal)
):
return x2, x1
if (isinstance(x2, rdflib.Variable) or isinstance(x2, rdflib.BNode)) and (
(isinstance(x1, rdflib.URIRef)) or isinstance(x1, rdflib.Literal)
):
return x1, x2
if isinstance(x1, rdflib.URIRef) and isinstance(x2, rdflib.URIRef):
if x1 == x2:
return x1, x2
else:
logger.error(f"Cannot decide between {x1=} and {x2=}!")
raise NotImplementedError
logger.warning(f"Could not decide between {x1=} and {x2=}!")
return None, None
# Associate graph with SPARQL-query; provide container for values compared later
lookup_table = [
{
"graph": shapes_and_inputs,
"query": (
"SELECT ?shape ?p1 ?focusNode "
"WHERE { "
f"?x r:source {rule_iri.n3()} ."
"?x ?p0 ?shape ."
"?shape ?p1 ?focusNode ."
"}"
),
"s": None,
"p": None,
"o": None,
},
{
"graph": knowledge_gained,
"query": (
"SELECT ?shape ?p1 ?focusNode "
"WHERE { "
"?shape rdf:type sh:NodeShape ."
"?shape sh:targetNode ?focusNode ."
"?shape ?p1 ?focusNode ."
"}"
),
"s": None,
"p": None,
"o": None,
},
]
# Extract subject, predicate, object from both graphs
for gq in lookup_table:
a0 = gq["graph"].query(gq["query"])
# XXX In case of several bindings, `s`, `p`, `o` get overwritten silently!
for s, p, o in a0:
gq["s"] = s
gq["p"] = p
gq["o"] = o
add = []
remove = []
for k in ["s", "p", "o"]:
if (lookup_table[0][k] != None) and (lookup_table[1][k] != None):
winner, looser = choose_term_over_variable(
lookup_table[0][k], lookup_table[1][k]
)
add.append(winner)
remove.append(looser)
# Trying to ensure that we're only left with the triples we want --- yikes...
if (len(add) > 0) and (len(remove) > 0) and (len(add) == len(remove)):
shapes_and_inputs.remove((remove[0], remove[1], remove[2]))
shapes_and_inputs.remove((remove[0], remove[1], add[2]))
shapes_and_inputs.remove((remove[0], add[1], remove[2]))
shapes_and_inputs.remove((remove[0], add[1], add[2]))
shapes_and_inputs.remove((add[0], remove[1], remove[2]))
shapes_and_inputs.remove((add[0], remove[1], add[2]))
shapes_and_inputs.remove((add[0], add[1], remove[2]))
knowledge_gained.remove((remove[0], remove[1], remove[2]))
knowledge_gained.remove((remove[0], remove[1], add[2]))
knowledge_gained.remove((remove[0], add[1], remove[2]))
knowledge_gained.remove((remove[0], add[1], add[2]))
knowledge_gained.remove((add[0], remove[1], remove[2]))
knowledge_gained.remove((add[0], remove[1], add[2]))
knowledge_gained.remove((add[0], add[1], remove[2]))
shapes_and_inputs.add((add[0], add[1], add[2]))
shapes_and_inputs.add((add[0], REASON.source, file_iri))
knowledge_gained.add((add[0], add[1], add[2]))
for s, p, o in shapes_and_inputs.triples((None, None, remove[0])):
shapes_and_inputs.remove((s, p, o))
shapes_and_inputs.add((s, p, add[0]))
return shapes_and_inputs, knowledge_gained
def demand_user_input_is_ready(shapes_and_inputs, term):
"""Have the user verify that the required inputs are ready for use."""
logger.error(f"Is the user input in {term.n3()} ready for upload? -> YES")
# ↓↓↓ SPECIFIC TO SIMaaS-EXAMPLE! TO BE DELETED HERE ###############################
from jinja2 import Environment, FileSystemLoader
# Environment to be used when rendering templates using Jinja2
ENV = Environment(
loader=FileSystemLoader("examples/simulation"),
trim_blocks=True,
lstrip_blocks=True,
)
# Make user input available in working directory
filepath = term.toPython()[7:] # get rid of `file://`-prefix via slicing
subject = shapes_and_inputs.value(None, SHACL.targetNode, term)
stored_in = shapes_and_inputs.value(subject, REASON.source, None)
# Careful, things get quite ugly below.. adults only
logger.log(
"USER",
(
f"Shape for focus node `{term.n3()}`: `{subject.n3()}`; "
f"to be found in `{stored_in.n3()}`"
),
)
logger.log(
"USER",
"Note that we simply _assume_ that the data graph conforms to the shape!",
)
if "shapes-instantiation" in subject.toPython():
x = [
(
ENV.get_template("parameters_01.n3.jinja"),
{"filepath": filepath},
)
]
if "shapes-simulation" in subject.toPython():
x = [
(
ENV.get_template("simulation_01.n3.jinja"),
{
"settings_prefix": f"{subject.toPython().split('#')[0]}/settings#",
"var_prefix": f"{'/'.join(subject.toPython().split('/')[0:-2])}/variables#",
},
)
]
for template, data in x:
with open(filepath, "w") as fp:
fp.write(template.render(data))
logger.log("USER", f"User just updated file <{term.toPython()}>")
# ↑↑↑ SPECIFIC TO SIMaaS-EXAMPLE! TO BE DELETED HERE ###############################
# response = input(f"Is the user input in {term.n3()} ready for upload? y/n: ")
# ready = True if response.lower().startswith("y") else False
# logger.debug(f"{ready=}")
# http://docs.pyinvoke.org/en/stable/concepts/invoking-tasks.html#iterable-flag-values
@task(
iterable=["input_files"],
optional=["suffix", "workdir"],
help={
"tmp_dir": "The working directory on the host",
"input_files": "The filenames of all input files",
"agent_goal": "The name of the .n3-file specifying the agent's goal",
"suffix": "A suffix for the file name in which the proof is stored",
"workdir": "The directory inside the container at which files are mounted",
},
)
def eye_generate_proof(
ctx, tmp_dir, input_files, agent_goal, prefix=None, workdir="/mnt"
):
"""Generate proof using containerized EYE reasoner."""
logger.info("Generating proof using EYE...")
# Assemble command
image_name = os.getenv("EYE_IMAGE_NAME")
cmd_engine = (
"docker run "
"-i "
"--rm "
"--name eye "
f"-v {tmp_dir}:{workdir} "
f"-w {workdir} "
f"{image_name} "
)
options = "--quiet --tactic limited-answer 1"
filenames = " ".join(input_files)
cmd_container = f"{options} {filenames} --query {agent_goal}"
cmd = cmd_engine + cmd_container
logger.debug(cmd)
# Generate proof
timeout = int(os.getenv("EYE_TIMEOUT")) if os.getenv("EYE_TIMEOUT") else None
result = ctx.run(cmd, hide=True, timeout=timeout)
# Modify proof to ensure all parts of the stack understand the syntax
content = correct_n3_syntax(result.stdout)
logger.trace(f"Reasoning logs:\n{result.stderr}")
logger.trace(f"Proof deduced by EYE:\n{content}")
# Was the reasoner able to generate a proof?
graph = rdflib.Graph()
graph.namespace_manager = NAMESPACE_MANAGER
graph.parse(data=content, format="n3")
if result.ok and (len(graph) > 0):
status = SUCCESS
else:
logger.error("EYE was unable to generate a proof, halting with FAILURE!")
status = FAILURE
# Store the proof as a file on disk
proof = "proof.n3" if prefix is None else f"{prefix}_proof.n3"
path = os.path.join(tmp_dir, proof)
with open(path, "w") as fp:
fp.write(content)
return status, path
@task(
iterable=["R"],
help={
"proof": "The .n3-file containing the proof",
"R": "The RESTdesc descriptions as .n3-files",
"prefix": "The path of the directory in which the .n3-files are found within the container",
},
)
def find_rule_applications(ctx, proof, R, prefix):
"""Count how many times rules of R are applied in the proof."""
logger.info("Counting how many times rules of R are applied in the proof...")
# Parse graph from n3-file
graph = rdflib.Graph()
graph.namespace_manager = NAMESPACE_MANAGER
graph.parse(proof, format="n3")
# Identify applications of R in proof
n_pre = 0
for file in R:
# Identify triple resulting from loading the source file containing part of R
file_name = file.split("/")[-1]
file_uriref = rdflib.URIRef(f"file://{prefix}/{file_name}")
logger.debug(f"Finding applications of rules stated in '{file_name}'...")
# Count number of triples that match SPARQL query
a0 = graph.query(
(
"SELECT ?x ?y "
"WHERE { "
f"?x ?p0 {file_uriref.n3()}. "
"?y ?p1 ?x. "
"}"
)
)
for x, y in a0:
logger.trace(f"\n{x=}\n{y=}")
n_pre += 1
logger.trace(f"{n_pre=}")
return n_pre
@task(
iterable=["R"],
help={
"proof": "The .n3-file containing the proof",
"R": "The RESTdesc descriptions as .n3-files",
"prefix": "The path of the directory in which the .n3-files are found within the container",
},
)
def identify_http_requests(ctx, proof, R, prefix, shapes_and_inputs):
"""Extract HTTP requests in proof resulting from R."""
logger.info("Extracting ground HTTP requests in proof resulting from R...")
requests_ground = []
# Read and parse entire proof from n3-file
graph = rdflib.Graph()
graph.namespace_manager = NAMESPACE_MANAGER
graph.parse(proof, format="n3")
# Iterate over all files comprising R
for file in R:
# Construct identifier for which to search
file_name = file.split("/")[-1] # XXX use os.path instead
file_uriref = rdflib.URIRef(f"file://{prefix}/{file_name}")
logger.debug(f"Finding applications of rules stated in '{file_name}'...")
# Find HTTP requests that are part of the application of a rule ∈ R
a0 = graph.query(
(
"SELECT ?a ?b ?c ?x "
"WHERE { "
f"?a r:source {file_uriref.n3()}. "
"?b ?p ?a. "
"?c r:rule ?b. "
"?c r:gives ?x. "
"}"
)
)
# Inspect { N3 expression } and extract HTTP request info
for a, b, c, x in a0:
logger.trace(
(
"Grounded SPARQL query to find { N3 } expression:\n"
f"{a.n3()} r:source {file_uriref.n3()}\n"
f"{b.n3()} ?p {a.n3()}\n"
f"{c.n3()} r:rule {b.n3()}\n"
f"{c.n3()} r:gives {x.n3()}"
)
)
x.namespace_manager = NAMESPACE_MANAGER
logger.debug(f"{x.serialize(format='n3')}")
# Extract method and request URI
req = request_from_graph(x, shapes_and_inputs)
if req != None:
requests_ground.append((file, req))
return requests_ground
def parse_http_body(node, r):
"""Parse triples about a HTTP message body."""
triples = []
# Identify media type of the message body
try:
content_type_parts = r.headers["content-type"].split(";")
except KeyError:
logger.warning(
f"{r=} doesn't have a 'content-type'-header, "
"aborting attempt to parse body..."
)
return triples
content_type = content_type_parts[0]
content_type_type = content_type.split("/")[0]
content_type_subtype = content_type.split("/")[1]
if len(content_type_parts) == 2:
content_type_parameter = content_type_parts[1]
message_type = "response" if isinstance(r, requests.Response) else "request"
logger.log(
"DETAIL", f"The media type for the HTTP {message_type} is '{content_type}'"
)
# Determine whether or not the message body is binary file
if (content_type_type in ["audio", "image", "video"]) or (
content_type == "application/octet-stream"
):
content_is_binary = True
elif (
(content_type_type in ["text"])
or ("json" in content_type_subtype)
or ("xml" in content_type_subtype)
or (
content_type
in ["application/n-triples", "application/n-quads", "application/trig"]
)
):
content_is_binary = False
elif content_type == "multipart/form-data":
content_is_binary = True # TODO assume binary content for now
logger.warning(
f"Parsing triples about 'multipart/form-data'-{message_type}s is not yet "
"implemented!"
) # TODO
else:
content_is_binary = True
logger.warning(
f"Don't know whether or not '{content_type}' is binary -> assuming it is!"
)
if not content_is_binary:
if content_type in RDFLIB_SERIALIZATIONS:
# Parse triples from non-binary message body
if isinstance(r, requests.Response):
data = r.text
else:
data = r.body
r_body_ds = rdflib.Dataset()
r_body_ds.parse(data=data, format=content_type, publicID=r.url)
for graph in r_body_ds.graphs():
graph.namespace_manager = NAMESPACE_MANAGER
for s, p, o in graph:
triples.append((s, p, o))
triples.append((node, HTTP.body, s))
r_body_serialized = r_body_ds.serialize(format="application/trig")
logger.trace(f"Triples parsed from message body:\n{r_body_serialized}")
if isinstance(r, requests.Response):
with open(
os.path.join(
"/home/moritz/tmp/agent",
f"{r.request.method.lower()}_{r.url.split('/')[-1].split('?')[0]}.trig",
),
"w",
) as fp:
fp.write(r_body_serialized)
else:
logger.warning(
f"Found unsupported non-binary content-type '{content_type}'; "
"won't attempt to parse that!"
)
else:
# TODO Parse triples off of binary content?
logger.warning("Parsing triples off of binary content not implemented yet!")
return triples
def parse_http_response(response):
"""Extract all triples from HTTP response object."""
logger.info("Extracting new information from HTTP request/response...")
# Prepare for parsing
request = response.request
triples = []
# Create new individual which becomes the subject of all triples
request_node = rdflib.BNode() # identifier for the request
response_node = rdflib.BNode() # identifier for the response
# Parse triples about the request method
triples.append((request_node, HTTP.Method, rdflib.Literal(request.method)))
# Parse triples about the request URL
triples.append((request_node, HTTP.requestURI, rdflib.URIRef(request.url)))
# Parse triples about the request headers
for name, value in request.headers.items():
header_bnode = rdflib.BNode()
triples.append((header_bnode, RDF.type, HTTP.ResponseHeader))
triples.append((header_bnode, HTTP.fieldName, rdflib.Literal(name)))
triples.append((header_bnode, HTTP.fieldValue, rdflib.Literal(value)))
triples.append((request_node, HTTP.headers, header_bnode))
# Parse triples about the request body
triples += parse_http_body(request_node, request)
# Parse triples about the response status
triples.append(
(response_node, HTTP.statusCodeNumber, rdflib.Literal(response.status_code))
)
triples.append((response_node, HTTP.reasonPhrase, rdflib.Literal(response.reason)))
# Parse triples about the response headers
for name, value in response.headers.items():
header_bnode = rdflib.BNode()
triples.append((header_bnode, RDF.type, HTTP.ResponseHeader))
triples.append((header_bnode, HTTP.fieldName, rdflib.Literal(name)))
triples.append((header_bnode, HTTP.fieldValue, rdflib.Literal(value)))
triples.append((response_node, HTTP.headers, header_bnode))
# Parse response body according to its (hyper-)media type
triples += parse_http_body(response_node, response)
# Connect response to request
triples.append((request_node, RDF.type, HTTP.Request))
triples.append((response_node, RDF.type, HTTP.Response))
triples.append((request_node, HTTP.resp, response_node))
return triples
@task(
iterable=["H", "R"],
optional=["B", "pre_proof", "n_pre", "iteration", "si"],
help={
"directory": "The directory in which to store all files created during execution",
"H": ".n3-files containing the initial state",
"g": ".n3-file specifying the agent's goal",
"R": ".n3-file containing a RESTdesc rule (can be given multiple times)",
"B": ".n3-file containing background knowledge (can be given multiple times)",
"pre_proof": "The .n3-file containing the pre-proof",
"n_pre": "The number of API operations in `pre_proof`",
"iteration": "The current iteration depth",
"si": "rdflib.graph.Graph-instance containing shapes for inputs (don't use via CLI)",
},
)
def solve_api_composition_problem(
ctx, directory, H, g, R, B=None, pre_proof=None, n_pre=None, iteration=0, si=None
):
"""Recursively solve API composition problem."""
logger.info(
f"Attempting to solve API composition problem, iteration {iteration}..."
)
workdir = "/mnt"
input_files = concatenate_eye_input_files(H, g, R, B)
shapes_and_inputs = si
if iteration == 0:
shapes_and_inputs = identify_shapes_for_user_input(R, B, directory)
if pre_proof == None:
# (1) Generate the (initial) pre-proof
status, pre_proof = eye_generate_proof(
ctx, directory, input_files, g, f"{iteration:0>2}_pre", workdir
)
if status == FAILURE:
return FAILURE
# (1b) How many times are rules of R applied (i.e. how many API operations)?
n_pre = find_rule_applications(ctx, pre_proof, R, workdir)
logger.log("DETAIL", f"{n_pre=}")
# (2) What does `n_pre` imply?
if n_pre == 0:
logger.success(
f"🎉 The pragmatic proof algorithm terminated successfully since {n_pre=}!"
)
# Log result achieved
proof = rdflib.Graph()
proof.parse(pre_proof, format="n3") # TODO filter out lemmata?
logger.info(f"Proof that the goal was met:\n{proof.serialize(format='n3')}")
return SUCCESS
# (3) Which HTTP requests are sufficiently specified? -> select one
ground_requests = identify_http_requests(
ctx, pre_proof, R, workdir, shapes_and_inputs
)
r, request_object = ground_requests[0]
# (4) Execute HTTP request
logger.info("Sending request to API instance and parsing response...")
logger.log("REQUEST", f"{request_object.method} {request_object.url}")
request_prepared = request_object.prepare()
session = requests.Session()
response_object = session.send(request_prepared)
# (4) Parse response, add to ground formulas (initial state)
response_triples = parse_http_response(response_object)
response_graph = rdflib.Graph()
response_graph.namespace_manager = NAMESPACE_MANAGER
for s, p, o in response_triples:
response_graph.add((s, p, o))
# Write newly gained knowledge to disk
response_graph_serialized = response_graph.serialize(format="n3")
# WORKAROUND for bug in N3 serializer (no prefix 'rdf' but `[ sh:path rdf:type ]`)
response_graph_serialized = f"@prefix rdf: <{RDF}> .\n" + response_graph_serialized
logger.trace(f"New information parsed from response:\n{response_graph_serialized}")
G = f"{iteration:0>2}_sub_api_response.n3"
with open(os.path.join(directory, G), "w") as fp:
fp.write(response_graph_serialized)
# (5a) Update agent knowledge by creating union of sets H and G
# FIXME should this be a merge or the set operation G1 + G2??
H_union_G = rdflib.Graph()
H_union_G.namespace_manager = NAMESPACE_MANAGER
H_union_G.parse(os.path.join(directory, H[0]), format="n3")
H_union_G.parse(os.path.join(directory, G), format="n3")
# TODO Update map between shapes and required user input
agent_knowledge = f"{iteration:0>2}_sub_facts.n3" # name for `H_union_G` on disk
shapes_and_inputs, H_union_G = update_shapes_and_input(
shapes_and_inputs,
H_union_G,
rdflib.URIRef(f"file://{os.path.join(directory, r)}"),
rdflib.URIRef(f"file://{os.path.join(directory, agent_knowledge)}"),
)
# Write updated knowledge (API response + shapes/input-map) to disk
agent_knowledge_updated = H_union_G.serialize(format="n3")
# WORKAROUND for bug in N3 serializer (no prefix 'rdf' but `[ sh:path rdf:type ]`)
agent_knowledge_updated = f"@prefix rdf: <{RDF}> .\n" + agent_knowledge_updated
logger.trace(f"agent_knowledge_updated:\n{agent_knowledge_updated}")
with open(os.path.join(directory, agent_knowledge), "w") as fp:
fp.write(agent_knowledge_updated)
shapes_and_inputs.serialize(
os.path.join(directory, f"{iteration:0>2}_sub_shapes_inputs.n3"), format="n3"
)
# (5b) Generate post-proof
input_files = concatenate_eye_input_files([agent_knowledge], g, R, B)
status, post_proof = eye_generate_proof(
ctx, directory, input_files, g, f"{iteration:0>2}_sub", workdir
)
# (6) What is the value of `n_post`?
if status == FAILURE:
n_post = n_pre
else:
n_post = find_rule_applications(ctx, post_proof, R, workdir)
logger.log("DETAIL", f"{n_pre=}; {n_post=}")
# (7) What do the values of `n_pre` and `n_post` imply?
iteration += 1
if n_post >= n_pre:
R_difference_r = [x for x in R if not x == r]
status = solve_api_composition_problem(
ctx,
directory,
H,
g,
R_difference_r,
B,
None,
None,
iteration,
shapes_and_inputs,
)
return status
else:
n_pre = n_post
status = solve_api_composition_problem(
ctx,
directory,
[agent_knowledge],
g,
R,
B,
post_proof,
n_pre,
iteration,
shapes_and_inputs,
)
return status
|
import React from "react"
// importを追記
import { useStaticQuery, graphql, Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => {
// queryの取得処理を追加
const data = useStaticQuery(graphql`
query MyQuery {
allContentfulUser {
nodes {
id
name
age
}
}
allContentfulPost {
nodes {
id
title
}
}
allContentfulPostContentsTextNode{
nodes {
id
contents
}
}
}
`)
return (
<Layout>
<SEO title="Home" />
{data.allContentfulPost.nodes.map(({ id, title }) => (
<h1 key={id}>
{title}
</h1>
))}
{data.allContentfulUser.nodes.map(({ id, name, age }) => (
<h3 key={id}>
{name}({age}歳)
</h3>
))}
{data.allContentfulPostContentsTextNode.nodes.map(({ id, contents }) => (
<p>
{contents}
</p>
))}
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
}
export default IndexPage
|
const path = require("path")
// Generate a slug for markdown files
// module.exports.onCreateNode = ({ node, actions }) => {
// const { createNodeField } = actions
// if (node.internal.type === "MarkdownRemark") {
// const slug = path.basename(node.fileAbsolutePath, ".md")
// createNodeField({
// node,
// name: "slug",
// value: slug,
// })
// }
// }
// Create a page from markdown files with slug above
module.exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
// 1. Get path to template
const blogTemplate = path.resolve("./src/templates/blog.js")
// 2. Get markdown data
// const res = await graphql(`
// query {
// allMarkdownRemark {
// edges {
// node {
// fields {
// slug
// }
// }
// }
// }
// }
// `)
// 2. Get Contentful data
const res = await graphql(`
query {
allContentfulBlogPost {
edges {
node {
slug
}
}
}
}
`)
// 3. Create new pages
res.data.allContentfulBlogPost.edges.forEach(edge => {
createPage({
component: blogTemplate,
path: `/blog/${edge.node.slug}`,
context: {
slug: edge.node.slug,
},
})
})
}
|
"use strict";(self.webpackChunkz_paging_doc=self.webpackChunkz_paging_doc||[]).push([[301],{1606:(n,s,a)=>{a.r(s),a.d(s,{data:()=>e});const e={key:"v-d4a7df0c",path:"/api/props/global-config.html",title:"",lang:"zh-CN",frontmatter:{},excerpt:"",headers:[{level:2,title:"支持全局配置",slug:"支持全局配置",children:[{level:3,title:"",slug:"",children:[]}]}],filePathRelative:"api/props/global-config.md",git:{updatedTime:1629561936e3}}},6437:(n,s,a)=>{a.r(s),a.d(s,{default:()=>l});var e=a(6252);const p=(0,e.uE)('<h2 id="支持全局配置" tabindex="-1"><a class="header-anchor" href="#支持全局配置" aria-hidden="true">#</a> 支持全局配置</h2><div class="custom-container tip"><p class="custom-container-title">说明</p><p>支持统一配置z-paging的所有属性,非必须!!!</p></div><div class="custom-container danger"><p class="custom-container-title">注意</p><p>这里的全局配置不是全局引入组件,全局配置是指统一配置z-paging默认的属性值,z-paging遵循easycom组件规范,无需注册即可使用。</p></div><p style="color:red;font-weight:bold;"></p>',4),t={href:"https://uniapp.dcloud.io/component/README?id=easycom%E7%BB%84%E4%BB%B6%E8%A7%84%E8%8C%83",target:"_blank",rel:"noopener noreferrer"},o=(0,e.Uk)("点击查看easycom组件规范"),c=(0,e.uE)('<ul><li>(推荐)【方案1】在路径<code>@/uni_modules/z-paging</code>下创建<code>z-paging-config.js</code>(与z-paging目录下的readme.md同级),<code>z-paging-config.js</code>中的内容如下所示。</li></ul><div class="language-json ext-json line-numbers-mode"><pre class="language-json"><code>module.exports = <span class="token punctuation">{</span>\n\t<span class="token comment">//配置分页默认pageSize为15</span>\n\t'default-page-size'<span class="token operator">:</span> '<span class="token number">15</span>'<span class="token punctuation">,</span>\n\t<span class="token comment">//配置空数据图默认描述文字为:空空如也~~</span>\n\t'empty-view-text'<span class="token operator">:</span> '空空如也~~'<span class="token punctuation">,</span>\n\t<span class="token comment">//...</span>\n<span class="token punctuation">}</span>\n</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><ul><li>【方案二】在<code>main.js</code>中<code>import zConfig from '@/uni_modules/z-paging/components/z-paging/js/z-paging-config'</code>(此路径为使用uni_modules情况下使用,可依照具体情况进行修改),然后进行<code>z-paging</code>的全局配置:</li></ul><div class="custom-container danger"><p class="custom-container-title">注意</p><p>如果调用过setConfig进行配置,后期又需要取消配置,则必须设置zConfig.setConfig(null)将配置置空,因为setConfig是将配置设置在缓存中,直接删除配置代码将导致原先缓存的配置无法清空。</p></div><div class="language-javascript ext-js line-numbers-mode"><pre class="language-javascript"><code>zConfig<span class="token punctuation">.</span><span class="token function">setConfig</span><span class="token punctuation">(</span><span class="token punctuation">{</span>\n\t<span class="token comment">//配置分页默认pageSize为15</span>\n\t<span class="token string">'default-page-size'</span><span class="token operator">:</span> <span class="token string">'15'</span><span class="token punctuation">,</span>\n\t<span class="token comment">//配置空数据图默认描述文字为:空空如也~~</span>\n\t<span class="token string">'empty-view-text'</span><span class="token operator">:</span> <span class="token string">'空空如也~~'</span><span class="token punctuation">,</span>\n\t<span class="token comment">//...</span>\n<span class="token punctuation">}</span><span class="token punctuation">)</span>\n</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><hr><h3 id="" tabindex="-1"><a class="header-anchor" href="#" aria-hidden="true">#</a></h3>',7),l={render:function(n,s){const a=(0,e.up)("OutboundLink");return(0,e.wg)(),(0,e.iD)(e.HY,null,[p,(0,e._)("p",null,[(0,e._)("a",t,[o,(0,e.Wm)(a)])]),c],64)}}}}]);
|
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { useIsAuthenticated } from "../utils/auth";
const PrivateRoute = ({ component: Component, children, redirectTo = "/", ...props }) => {
const isAuth = useIsAuthenticated();
const render = ({ location }) => (
isAuth
? (Component ? <Component /> : children)
: <Redirect to={{ pathname: redirectTo, state: { from: location } }} />
);
return (
<Route
{...props}
render={render}
/>
);
}
export default PrivateRoute;
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/insipiredai'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
/**
* @author @tatocaster <kutaliatato@gmail.com>
* Translated default messages for the jQuery validation plugin.
* Locale: GE (Georgian; ქართული)
*/
$.extend($.validator.messages, {
required: "ეს ველი სავალდებულოა",
remote: "გთხოვთ შეასწოროთ.",
email: "გთხოვთ შეიყვანოთ სწორი ფორმატით.",
url: "გთხოვთ შეიყვანოთ სწორი ფორმატით.",
date: "გთხოვთ შეიყვანოთ სწორი თარიღი.",
dateISO: "გთხოვთ შეიყვანოთ სწორი ფორმატით ( ISO ).",
number: "გთხოვთ შეიყვანოთ რიცხვი.",
digits: "დაშვებულია მხოლოდ ციფრები.",
creditcard: "გთხოვთ შეიყვანოთ სწორი ფორმატის ბარათის კოდი.",
equalTo: "გთხოვთ შეიყვანოთ იგივე მნიშვნელობა.",
maxlength: $.validator.format( "გთხოვთ შეიყვანოთ არა უმეტეს {0} სიმბოლოსი." ),
minlength: $.validator.format( "შეიყვანეთ მინიმუმ {0} სიმბოლო." ),
rangelength: $.validator.format( "გთხოვთ შეიყვანოთ {0} -დან {1} -მდე რაოდენობის სიმბოლოები." ),
range: $.validator.format( "შეიყვანეთ {0} -სა {1} -ს შორის." ),
max: $.validator.format( "გთხოვთ შეიყვანოთ მნიშვნელობა ნაკლები ან ტოლი {0} -ს." ),
min: $.validator.format( "გთხოვთ შეიყვანოთ მნიშვნელობა მეტი ან ტოლი {0} -ს." )
});
|
import React from 'react';
import { withStyles, makeStyles } from '@material-ui/core/styles';
import MuiAccordion from '@material-ui/core/Accordion';
import MuiAccordionSummary from '@material-ui/core/AccordionSummary';
import MuiAccordionDetails from '@material-ui/core/AccordionDetails';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
const Accordion = withStyles({
root: {
color: '#fff',
boxShadow: 'none',
'&:not(:last-child)': {
borderBottom: 0
},
'&:before': {
display: 'none'
},
'&$expanded': {
margin: 'auto'
}
},
expanded: {}
})(MuiAccordion);
const AccordionSummary = withStyles({
root: {
color: '#333',
backgroundColor: '#fff',
cursor: 'pointer',
transition: 'background-color 150ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
minHeight: 25,
'&$expanded': {
minHeight: 25
},
'& .MuiAccordionSummary-content': {
alignItems: 'center',
justifyContent: 'flex-start'
},
'&:hover': {
textDecoration: 'none',
backgroundColor: '#fff'
}
},
content: {
'&$expanded': {}
},
expanded: {}
})(MuiAccordionSummary);
const AccordionDetails = withStyles(() => ({
root: {
flexDirection: 'column',
padding: 0,
color: '#263238'
}
}))(MuiAccordionDetails);
const useStyles = makeStyles({
text: {
fontSize: '0.9rem'
}
});
/* eslint-disable */
export default function AccordionItem({ title, children }) {
const classes = useStyles();
const [expanded, setExpanded] = React.useState(false);
const toggleExpand = () => {
setExpanded(!expanded);
};
const handleChange = (panel) => (event, isExpanded) => {
setExpanded(isExpanded ? panel : false);
};
return (
<div>
<Accordion square expanded={expanded} onChange={toggleExpand}>
<AccordionSummary
aria-controls="panel-content"
id="panel-header"
expandIcon={<ExpandMoreIcon />}
>
<Typography className={classes.text}>{title}</Typography>
</AccordionSummary>
<AccordionDetails>{children}</AccordionDetails>
</Accordion>
</div>
);
}
|
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import operator
from functools import reduce
import numpy as np
from jina.logging.base import get_logger
class MilvusDBException(Exception):
"""Any time Milvus client returns Status not OK"""
class MilvusDBHandler:
"""Milvus DB handler
This class is intended to abstract the access and communication with external MilvusDB from Executors
For more information about Milvus:
- https://github.com/milvus-io/milvus/
"""
@staticmethod
def get_index_type(index_type):
from milvus import IndexType
return {
'Flat': IndexType.FLAT,
'IVF,Flat': IndexType.IVFLAT,
'IVF,SQ8': IndexType.IVF_SQ8,
'RNSG': IndexType.RNSG,
'IVF,SQ8H': IndexType.IVF_SQ8H,
'IVF,PQ': IndexType.IVF_PQ,
'HNSW': IndexType.IVF_PQ,
'Annoy': IndexType.ANNOY
}.get(index_type, IndexType.FLAT)
class MilvusDBInserter:
"""Milvus DB Inserter
This class is an inner class and provides a context manager to insert vectors into Milvus while ensuring
data is flushed.
For more information about Milvus:
- https://github.com/milvus-io/milvus/
"""
def __init__(self, client, collection_name: str):
self.logger = get_logger(self.__class__.__name__)
self.client = client
self.collection_name = collection_name
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.logger.info(f'Sending flush command to Milvus Server for collection: {self.collection_name}')
self.client.flush([self.collection_name])
def insert(self, keys: list, vectors: 'np.ndarray'):
status, _ = self.client.insert(collection_name=self.collection_name, records=vectors, ids=keys)
if not status.OK():
self.logger.error('Insert failed: {}'.format(status))
raise MilvusDBException(status.message)
def __init__(self, host: str, port: int, collection_name: str):
"""
Initialize an MilvusDBHandler
:param host: Host of the Milvus Server
:param port: Port to connect to the Milvus Server
:param collection_name: Name of the collection where the Handler will insert and query vectors.
"""
self.logger = get_logger(self.__class__.__name__)
self.host = host
self.port = str(port)
self.collection_name = collection_name
self.milvus_client = None
def __enter__(self):
return self.connect()
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def connect(self):
from milvus import Milvus
if self.milvus_client is None or not self.milvus_client.server_status()[0].OK():
self.logger.info(f'Setting connection to Milvus Server at {self.host}:{self.port}')
self.milvus_client = Milvus(self.host, self.port)
return self
def close(self):
self.logger.info(f'Closing connection to Milvus Server at {self.host}:{self.port}')
self.milvus_client.close()
def insert(self, keys: 'np.ndarray', vectors: 'np.ndarray'):
with MilvusDBHandler.MilvusDBInserter(self.milvus_client, self.collection_name) as db:
db.insert(reduce(operator.concat, keys.tolist()), vectors)
def build_index(self, index_type: str, index_params: dict):
type = self.get_index_type(index_type)
self.logger.info(f'Creating index of type: {index_type} at'
f' Milvus Server. collection: {self.collection_name} with index params: {index_params}')
status = self.milvus_client.create_index(self.collection_name, type, index_params)
if not status.OK():
self.logger.error('Creating index failed: {}'.format(status))
raise MilvusDBException(status.message)
def search(self, query_vectors: 'np.ndarray', top_k: int, search_params: dict = None):
self.logger.info(f'Querying collection: {self.collection_name} with search params: {search_params}')
status, results = self.milvus_client.search(collection_name=self.collection_name,
query_records=query_vectors, top_k=top_k, params=search_params)
if not status.OK():
self.logger.error('Querying index failed: {}'.format(status))
raise MilvusDBException(status.message)
else:
return results.distance_array, results.id_array
|
import json
from collections import OrderedDict
from django import forms
from django.core.files.uploadedfile import UploadedFile
from django.db.models import Prefetch
from django.utils.functional import cached_property
from pretix.base.forms.questions import (
BaseInvoiceAddressForm, BaseQuestionsForm,
)
from pretix.base.models import (
CartPosition, InvoiceAddress, OrderPosition, Question, QuestionAnswer,
QuestionOption,
)
class BaseQuestionsViewMixin:
form_class = BaseQuestionsForm
@staticmethod
def _keyfunc(pos):
# Sort addons after the item they are an addon to
if isinstance(pos, OrderPosition):
i = pos.addon_to.positionid if pos.addon_to else pos.positionid
else:
i = pos.addon_to.pk if pos.addon_to else pos.pk
addon_penalty = 1 if pos.addon_to else 0
return i, addon_penalty, pos.pk
@cached_property
def _positions_for_questions(self):
raise NotImplementedError()
@cached_property
def forms(self):
"""
A list of forms with one form for each cart position that has questions
the user can answer. All forms have a custom prefix, so that they can all be
submitted at once.
"""
formlist = []
for cr in self._positions_for_questions:
cartpos = cr if isinstance(cr, CartPosition) else None
orderpos = cr if isinstance(cr, OrderPosition) else None
form = self.form_class(event=self.request.event,
prefix=cr.id,
cartpos=cartpos,
orderpos=orderpos,
data=(self.request.POST if self.request.method == 'POST' else None),
files=(self.request.FILES if self.request.method == 'POST' else None))
form.pos = cartpos or orderpos
if len(form.fields) > 0:
formlist.append(form)
return formlist
@cached_property
def formdict(self):
storage = OrderedDict()
for f in self.forms:
pos = f.cartpos or f.orderpos
if pos.addon_to_id:
if pos.addon_to not in storage:
storage[pos.addon_to] = []
storage[pos.addon_to].append(f)
else:
if pos not in storage:
storage[pos] = []
storage[pos].append(f)
return storage
def save(self):
failed = False
for form in self.forms:
meta_info = form.pos.meta_info_data
# Every form represents a CartPosition or OrderPosition with questions attached
if not form.is_valid():
failed = True
else:
# This form was correctly filled, so we store the data as
# answers to the questions / in the CartPosition object
for k, v in form.cleaned_data.items():
if k == 'attendee_name':
form.pos.attendee_name = v if v != '' else None
form.pos.save()
elif k == 'attendee_email':
form.pos.attendee_email = v if v != '' else None
form.pos.save()
elif k.startswith('question_') and v is not None:
field = form.fields[k]
if hasattr(field, 'answer'):
# We already have a cached answer object, so we don't
# have to create a new one
if v == '' or v is None or (isinstance(field, forms.FileField) and v is False):
if field.answer.file:
field.answer.file.delete()
field.answer.delete()
else:
self._save_to_answer(field, field.answer, v)
field.answer.save()
elif v != '':
answer = QuestionAnswer(
cartposition=(form.pos if isinstance(form.pos, CartPosition) else None),
orderposition=(form.pos if isinstance(form.pos, OrderPosition) else None),
question=field.question,
)
self._save_to_answer(field, answer, v)
answer.save()
else:
meta_info.setdefault('question_form_data', {})
if v is None:
if k in meta_info['question_form_data']:
del meta_info['question_form_data'][k]
else:
meta_info['question_form_data'][k] = v
form.pos.meta_info = json.dumps(meta_info)
form.pos.save(update_fields=['meta_info'])
return not failed
def _save_to_answer(self, field, answer, value):
if isinstance(field, forms.ModelMultipleChoiceField):
answstr = ", ".join([str(o) for o in value])
if not answer.pk:
answer.save()
else:
answer.options.clear()
answer.answer = answstr
answer.options.add(*value)
elif isinstance(field, forms.ModelChoiceField):
if not answer.pk:
answer.save()
else:
answer.options.clear()
answer.options.add(value)
answer.answer = value.answer
elif isinstance(field, forms.FileField):
if isinstance(value, UploadedFile):
answer.file.save(value.name, value)
answer.answer = 'file://' + value.name
else:
answer.answer = value
class OrderQuestionsViewMixin(BaseQuestionsViewMixin):
invoice_form_class = BaseInvoiceAddressForm
only_user_visible = True
@cached_property
def _positions_for_questions(self):
return self.positions
@cached_property
def positions(self):
qqs = Question.objects.all()
if self.only_user_visible:
qqs = qqs.filter(ask_during_checkin=False)
return list(self.order.positions.select_related(
'item', 'variation'
).prefetch_related(
Prefetch('answers',
QuestionAnswer.objects.prefetch_related('options'),
to_attr='answerlist'),
Prefetch('item__questions',
qqs.prefetch_related(
Prefetch('options', QuestionOption.objects.prefetch_related(Prefetch(
# This prefetch statement is utter bullshit, but it actually prevents Django from doing
# a lot of queries since ModelChoiceIterator stops trying to be clever once we have
# a prefetch lookup on this query...
'question',
Question.objects.none(),
to_attr='dummy'
)))
),
to_attr='questions_to_ask')
))
@cached_property
def invoice_address(self):
try:
return self.order.invoice_address
except InvoiceAddress.DoesNotExist:
return InvoiceAddress(order=self.order)
@cached_property
def invoice_form(self):
return self.invoice_form_class(
data=self.request.POST if self.request.method == "POST" else None,
event=self.request.event,
instance=self.invoice_address, validate_vat_id=False
)
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['order'] = self.order
ctx['formgroups'] = self.formdict.items()
ctx['invoice_form'] = self.invoice_form
return ctx
|
var str;
console.log(str); // undefined
str = 'My name';
console.log(typeof str); // string
str = 12;
console.log(typeof str); // number
str = true;
console.log(typeof str); // string
str = Symbol.iterator;
console.log(typeof str); // symbol
str = {};
console.log(typeof str); // object
str = null;
console.log(typeof str); // object
str = function() {};
console.log(typeof str); // function
|
module.exports = function(grunt) {
grunt.initConfig({
uglify: {
options: {
mangle: true,
banner: '/**\n * Shower HTML presentation engine: github.com/shower/shower\n * @copyright 2010–<%= grunt.template.today("yyyy") %> Vadim Makeev, pepelsbey.net\n * @license MIT license: github.com/shower/shower/wiki/MIT-License\n */\n'
},
build: {
src: 'shower.js',
dest: 'shower.min.js'
}
},
dalek: {
test: {
src: 'tests/keys.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-dalek');
grunt.registerTask('default', ['uglify', 'dalek']);
};
|
/*!
* FormValidation (http://formvalidation.io)
* The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks
*
* @version v0.6.3-dev, built on 2015-04-05 6:17:56 PM
* @author https://twitter.com/formvalidation
* @copyright (c) 2013 - 2015 Nguyen Huu Phuoc
* @license http://formvalidation.io/license/
*/
if(window.FormValidation={AddOn:{},Framework:{},I18n:{},Validator:{}},"undefined"==typeof jQuery)throw new Error("FormValidation requires jQuery");!function(a){var b=a.fn.jquery.split(" ")[0].split(".");if(+b[0]<2&&+b[1]<9||1===+b[0]&&9===+b[1]&&+b[2]<1)throw new Error("FormValidation requires jQuery version 1.9.1 or higher")}(jQuery),function(a){FormValidation.Base=function(b,c,d){this.$form=a(b),this.options=a.extend({},a.fn.formValidation.DEFAULT_OPTIONS,c),this._namespace=d||"fv",this.$invalidFields=a([]),this.$submitButton=null,this.$hiddenButton=null,this.STATUS_NOT_VALIDATED="NOT_VALIDATED",this.STATUS_VALIDATING="VALIDATING",this.STATUS_INVALID="INVALID",this.STATUS_VALID="VALID",this.STATUS_IGNORED="IGNORED";var e=function(){for(var a=3,b=document.createElement("div"),c=b.all||[];b.innerHTML="<!--[if gt IE "+ ++a+"]><br><![endif]-->",c[0];);return a>4?a:!a}(),f=document.createElement("div");this._changeEvent=9!==e&&"oninput"in f?"input":"keyup",this._submitIfValid=null,this._cacheFields={},this._init()},FormValidation.Base.prototype={constructor:FormValidation.Base,_exceedThreshold:function(b){var c=this._namespace,d=b.attr("data-"+c+"-field"),e=this.options.fields[d].threshold||this.options.threshold;if(!e)return!0;var f=-1!==a.inArray(b.attr("type"),["button","checkbox","file","hidden","image","radio","reset","submit"]);return f||b.val().length>=e},_init:function(){var b=this,c=this._namespace,d={addOns:{},autoFocus:this.$form.attr("data-"+c+"-autofocus"),button:{selector:this.$form.attr("data-"+c+"-button-selector")||this.$form.attr("data-"+c+"-submitbuttons"),disabled:this.$form.attr("data-"+c+"-button-disabled")},control:{valid:this.$form.attr("data-"+c+"-control-valid"),invalid:this.$form.attr("data-"+c+"-control-invalid")},err:{clazz:this.$form.attr("data-"+c+"-err-clazz"),container:this.$form.attr("data-"+c+"-err-container")||this.$form.attr("data-"+c+"-container"),parent:this.$form.attr("data-"+c+"-err-parent")},events:{formInit:this.$form.attr("data-"+c+"-events-form-init"),formError:this.$form.attr("data-"+c+"-events-form-error"),formSuccess:this.$form.attr("data-"+c+"-events-form-success"),fieldAdded:this.$form.attr("data-"+c+"-events-field-added"),fieldRemoved:this.$form.attr("data-"+c+"-events-field-removed"),fieldInit:this.$form.attr("data-"+c+"-events-field-init"),fieldError:this.$form.attr("data-"+c+"-events-field-error"),fieldSuccess:this.$form.attr("data-"+c+"-events-field-success"),fieldStatus:this.$form.attr("data-"+c+"-events-field-status"),localeChanged:this.$form.attr("data-"+c+"-events-locale-changed"),validatorError:this.$form.attr("data-"+c+"-events-validator-error"),validatorSuccess:this.$form.attr("data-"+c+"-events-validator-success"),validatorIgnored:this.$form.attr("data-"+c+"-events-validator-ignored")},excluded:this.$form.attr("data-"+c+"-excluded"),icon:{valid:this.$form.attr("data-"+c+"-icon-valid")||this.$form.attr("data-"+c+"-feedbackicons-valid"),invalid:this.$form.attr("data-"+c+"-icon-invalid")||this.$form.attr("data-"+c+"-feedbackicons-invalid"),validating:this.$form.attr("data-"+c+"-icon-validating")||this.$form.attr("data-"+c+"-feedbackicons-validating"),feedback:this.$form.attr("data-"+c+"-icon-feedback")},live:this.$form.attr("data-"+c+"-live"),locale:this.$form.attr("data-"+c+"-locale"),message:this.$form.attr("data-"+c+"-message"),onError:this.$form.attr("data-"+c+"-onerror"),onSuccess:this.$form.attr("data-"+c+"-onsuccess"),row:{selector:this.$form.attr("data-"+c+"-row-selector")||this.$form.attr("data-"+c+"-group"),valid:this.$form.attr("data-"+c+"-row-valid"),invalid:this.$form.attr("data-"+c+"-row-invalid"),feedback:this.$form.attr("data-"+c+"-row-feedback")},threshold:this.$form.attr("data-"+c+"-threshold"),trigger:this.$form.attr("data-"+c+"-trigger"),verbose:this.$form.attr("data-"+c+"-verbose"),fields:{}};this.$form.attr("novalidate","novalidate").addClass(this.options.elementClass).on("submit."+c,function(a){a.preventDefault(),b.validate()}).on("click."+c,this.options.button.selector,function(){b.$submitButton=a(this),b._submitIfValid=!0}),(this.options.declarative===!0||"true"===this.options.declarative)&&this.$form.find("[name], [data-"+c+"-field]").each(function(){var e=a(this),f=e.attr("name")||e.attr("data-"+c+"-field"),g=b._parseOptions(e);g&&(e.attr("data-"+c+"-field",f),d.fields[f]=a.extend({},g,d.fields[f]))}),this.options=a.extend(!0,this.options,d),"string"==typeof this.options.err.parent&&(this.options.err.parent=new RegExp(this.options.err.parent)),this.options.container&&(this.options.err.container=this.options.container,delete this.options.container),this.options.feedbackIcons&&(this.options.icon=a.extend(!0,this.options.icon,this.options.feedbackIcons),delete this.options.feedbackIcons),this.options.group&&(this.options.row.selector=this.options.group,delete this.options.group),this.options.submitButtons&&(this.options.button.selector=this.options.submitButtons,delete this.options.submitButtons),FormValidation.I18n[this.options.locale]||(this.options.locale=a.fn.formValidation.DEFAULT_OPTIONS.locale),(this.options.declarative===!0||"true"===this.options.declarative)&&(this.options=a.extend(!0,this.options,{addOns:this._parseAddOnOptions()})),this.$hiddenButton=a("<button/>").attr("type","submit").prependTo(this.$form).addClass("fv-hidden-submit").css({display:"none",width:0,height:0}),this.$form.on("click."+this._namespace,'[type="submit"]',function(c){if(!c.isDefaultPrevented()){var d=a(c.target),e=d.is('[type="submit"]')?d.eq(0):d.parent('[type="submit"]').eq(0);!b.options.button.selector||e.is(b.options.button.selector)||e.is(b.$hiddenButton)||b.$form.off("submit."+b._namespace).submit()}});for(var e in this.options.fields)this._initField(e);for(var f in this.options.addOns)"function"==typeof FormValidation.AddOn[f].init&&FormValidation.AddOn[f].init(this,this.options.addOns[f]);this.$form.trigger(a.Event(this.options.events.formInit),{bv:this,fv:this,options:this.options}),this.options.onSuccess&&this.$form.on(this.options.events.formSuccess,function(a){FormValidation.Helper.call(b.options.onSuccess,[a])}),this.options.onError&&this.$form.on(this.options.events.formError,function(a){FormValidation.Helper.call(b.options.onError,[a])})},_initField:function(b){var c=this._namespace,d=a([]);switch(typeof b){case"object":d=b,b=b.attr("data-"+c+"-field");break;case"string":d=this.getFieldElements(b),d.attr("data-"+c+"-field",b)}if(0!==d.length&&null!==this.options.fields[b]&&null!==this.options.fields[b].validators){var e;for(e in this.options.fields[b].validators)FormValidation.Validator[e]||delete this.options.fields[b].validators[e];null===this.options.fields[b].enabled&&(this.options.fields[b].enabled=!0);for(var f=this,g=d.length,h=d.attr("type"),i=1===g||"radio"===h||"checkbox"===h,j=this._getFieldTrigger(d.eq(0)),k=a.map(j,function(a){return a+".update."+c}).join(" "),l=0;g>l;l++){var m=d.eq(l),n=this.options.fields[b].row||this.options.row.selector,o=m.closest(n),p="function"==typeof(this.options.fields[b].container||this.options.fields[b].err||this.options.err.container)?(this.options.fields[b].container||this.options.fields[b].err||this.options.err.container).call(this,m,this):this.options.fields[b].container||this.options.fields[b].err||this.options.err.container,q=p&&"tooltip"!==p&&"popover"!==p?a(p):this._getMessageContainer(m,n);p&&"tooltip"!==p&&"popover"!==p&&q.addClass(this.options.err.clazz),q.find("."+this.options.err.clazz.split(" ").join(".")+"[data-"+c+"-validator][data-"+c+'-for="'+b+'"]').remove(),o.find("i[data-"+c+'-icon-for="'+b+'"]').remove(),m.off(k).on(k,function(){f.updateStatus(a(this),f.STATUS_NOT_VALIDATED)}),m.data(c+".messages",q);for(e in this.options.fields[b].validators)m.data(c+".result."+e,this.STATUS_NOT_VALIDATED),i&&l!==g-1||a("<small/>").css("display","none").addClass(this.options.err.clazz).attr("data-"+c+"-validator",e).attr("data-"+c+"-for",b).attr("data-"+c+"-result",this.STATUS_NOT_VALIDATED).html(this._getMessage(b,e)).appendTo(q),"function"==typeof FormValidation.Validator[e].init&&FormValidation.Validator[e].init(this,m,this.options.fields[b].validators[e]);if(this.options.fields[b].icon!==!1&&"false"!==this.options.fields[b].icon&&this.options.icon&&this.options.icon.valid&&this.options.icon.invalid&&this.options.icon.validating&&(!i||l===g-1)){o.addClass(this.options.row.feedback);var r=a("<i/>").css("display","none").addClass(this.options.icon.feedback).attr("data-"+c+"-icon-for",b).insertAfter(m);(i?d:m).data(c+".icon",r),("tooltip"===p||"popover"===p)&&((i?d:m).on(this.options.events.fieldError,function(){o.addClass("fv-has-tooltip")}).on(this.options.events.fieldSuccess,function(){o.removeClass("fv-has-tooltip")}),m.off("focus.container."+c).on("focus.container."+c,function(){f._showTooltip(m,p)}).off("blur.container."+c).on("blur.container."+c,function(){f._hideTooltip(m,p)})),"string"==typeof this.options.fields[b].icon&&"true"!==this.options.fields[b].icon?r.appendTo(a(this.options.fields[b].icon)):this._fixIcon(m,r)}}d.on(this.options.events.fieldSuccess,function(a,b){var c=f.getOptions(b.field,null,"onSuccess");c&&FormValidation.Helper.call(c,[a,b])}).on(this.options.events.fieldError,function(a,b){var c=f.getOptions(b.field,null,"onError");c&&FormValidation.Helper.call(c,[a,b])}).on(this.options.events.fieldStatus,function(a,b){var c=f.getOptions(b.field,null,"onStatus");c&&FormValidation.Helper.call(c,[a,b])}).on(this.options.events.validatorError,function(a,b){var c=f.getOptions(b.field,b.validator,"onError");c&&FormValidation.Helper.call(c,[a,b])}).on(this.options.events.validatorIgnored,function(a,b){var c=f.getOptions(b.field,b.validator,"onIgnored");c&&FormValidation.Helper.call(c,[a,b])}).on(this.options.events.validatorSuccess,function(a,b){var c=f.getOptions(b.field,b.validator,"onSuccess");c&&FormValidation.Helper.call(c,[a,b])}),this.onLiveChange(d,"live",function(){f._exceedThreshold(a(this))&&f.validateField(a(this))}),d.trigger(a.Event(this.options.events.fieldInit),{bv:this,fv:this,field:b,element:d})}},_isExcluded:function(b){var c=this._namespace,d=b.attr("data-"+c+"-excluded"),e=b.attr("data-"+c+"-field")||b.attr("name");switch(!0){case!!e&&this.options.fields&&this.options.fields[e]&&("true"===this.options.fields[e].excluded||this.options.fields[e].excluded===!0):case"true"===d:case""===d:return!0;case!!e&&this.options.fields&&this.options.fields[e]&&("false"===this.options.fields[e].excluded||this.options.fields[e].excluded===!1):case"false"===d:return!1;case!!e&&this.options.fields&&this.options.fields[e]&&"function"==typeof this.options.fields[e].excluded:return this.options.fields[e].excluded.call(this,b,this);case!!e&&this.options.fields&&this.options.fields[e]&&"string"==typeof this.options.fields[e].excluded:case d:return FormValidation.Helper.call(this.options.fields[e].excluded,[b,this]);default:if(this.options.excluded){"string"==typeof this.options.excluded&&(this.options.excluded=a.map(this.options.excluded.split(","),function(b){return a.trim(b)}));for(var f=this.options.excluded.length,g=0;f>g;g++)if("string"==typeof this.options.excluded[g]&&b.is(this.options.excluded[g])||"function"==typeof this.options.excluded[g]&&this.options.excluded[g].call(this,b,this)===!0)return!0}return!1}},_getFieldTrigger:function(a){var b=this._namespace,c=a.data(b+".trigger");if(c)return c;var d=a.attr("type"),e=a.attr("data-"+b+"-field"),f="radio"===d||"checkbox"===d||"file"===d||"SELECT"===a.get(0).tagName?"change":this._changeEvent;return c=((this.options.fields[e]?this.options.fields[e].trigger:null)||this.options.trigger||f).split(" "),a.data(b+".trigger",c),c},_getMessage:function(a,b){if(!(this.options.fields[a]&&FormValidation.Validator[b]&&this.options.fields[a].validators&&this.options.fields[a].validators[b]))return"";switch(!0){case!!this.options.fields[a].validators[b].message:return this.options.fields[a].validators[b].message;case!!this.options.fields[a].message:return this.options.fields[a].message;case!!FormValidation.I18n[this.options.locale]&&!!FormValidation.I18n[this.options.locale][b]&&!!FormValidation.I18n[this.options.locale][b]["default"]:return FormValidation.I18n[this.options.locale][b]["default"];default:return this.options.message}},_getMessageContainer:function(a,b){if(!this.options.err.parent)throw new Error("The err.parent option is not defined");var c=a.parent();if(c.is(b))return c;var d=c.attr("class");return d&&this.options.err.parent.test(d)?c:this._getMessageContainer(c,b)},_parseAddOnOptions:function(){var a=this._namespace,b=this.$form.attr("data-"+a+"-addons"),c=this.options.addOns||{};if(b){b=b.replace(/\s/g,"").split(",");for(var d=0;d<b.length;d++)c[b[d]]||(c[b[d]]={})}var e,f,g,h;for(e in c)if(FormValidation.AddOn[e]){if(f=FormValidation.AddOn[e].html5Attributes)for(g in f)h=this.$form.attr("data-"+a+"-addons-"+e.toLowerCase()+"-"+g.toLowerCase()),h&&(c[e][f[g]]=h)}else delete c[e];return c},_parseOptions:function(b){var c,d,e,f,g,h,i,j,k,l=this._namespace,m=b.attr("name")||b.attr("data-"+l+"-field"),n={};for(d in FormValidation.Validator)if(c=FormValidation.Validator[d],e="data-"+l+"-"+d.toLowerCase(),f=b.attr(e)+"",k="function"==typeof c.enableByHtml5?c.enableByHtml5(b):null,k&&"false"!==f||k!==!0&&(""===f||"true"===f||e===f.toLowerCase())){c.html5Attributes=a.extend({},{message:"message",onerror:"onError",onsuccess:"onSuccess",transformer:"transformer"},c.html5Attributes),n[d]=a.extend({},k===!0?{}:k,n[d]);for(j in c.html5Attributes)g=c.html5Attributes[j],h="data-"+l+"-"+d.toLowerCase()+"-"+j,i=b.attr(h),i&&("true"===i||h===i.toLowerCase()?i=!0:"false"===i&&(i=!1),n[d][g]=i)}var o={autoFocus:b.attr("data-"+l+"-autofocus"),err:b.attr("data-"+l+"-err-container")||b.attr("data-"+l+"-container"),excluded:b.attr("data-"+l+"-excluded"),icon:b.attr("data-"+l+"-icon")||b.attr("data-"+l+"-feedbackicons")||(this.options.fields&&this.options.fields[m]?this.options.fields[m].feedbackIcons:null),message:b.attr("data-"+l+"-message"),onError:b.attr("data-"+l+"-onerror"),onStatus:b.attr("data-"+l+"-onstatus"),onSuccess:b.attr("data-"+l+"-onsuccess"),row:b.attr("data-"+l+"-row")||b.attr("data-"+l+"-group")||(this.options.fields&&this.options.fields[m]?this.options.fields[m].group:null),selector:b.attr("data-"+l+"-selector"),threshold:b.attr("data-"+l+"-threshold"),transformer:b.attr("data-"+l+"-transformer"),trigger:b.attr("data-"+l+"-trigger"),verbose:b.attr("data-"+l+"-verbose"),validators:n},p=a.isEmptyObject(o),q=a.isEmptyObject(n);return!q||!p&&this.options.fields&&this.options.fields[m]?(o.validators=n,o):null},_submit:function(){var b=this.isValid();if(null!==b){var c=b?this.options.events.formSuccess:this.options.events.formError,d=a.Event(c);this.$form.trigger(d),this.$submitButton&&(b?this._onSuccess(d):this._onError(d))}},_onError:function(b){if(!b.isDefaultPrevented()){if("submitted"===this.options.live){this.options.live="enabled";var c=this;for(var d in this.options.fields)!function(b){var d=c.getFieldElements(b);d.length&&c.onLiveChange(d,"live",function(){c._exceedThreshold(a(this))&&c.validateField(a(this))})}(d)}for(var e=this._namespace,f=0;f<this.$invalidFields.length;f++){var g=this.$invalidFields.eq(f),h=this.isOptionEnabled(g.attr("data-"+e+"-field"),"autoFocus");if(h){g.focus();break}}}},_onFieldValidated:function(b,c){var d=this._namespace,e=b.attr("data-"+d+"-field"),f=this.options.fields[e].validators,g={},h=0,i={bv:this,fv:this,field:e,element:b,validator:c,result:b.data(d+".response."+c)};if(c)switch(b.data(d+".result."+c)){case this.STATUS_INVALID:b.trigger(a.Event(this.options.events.validatorError),i);break;case this.STATUS_VALID:b.trigger(a.Event(this.options.events.validatorSuccess),i);break;case this.STATUS_IGNORED:b.trigger(a.Event(this.options.events.validatorIgnored),i)}g[this.STATUS_NOT_VALIDATED]=0,g[this.STATUS_VALIDATING]=0,g[this.STATUS_INVALID]=0,g[this.STATUS_VALID]=0,g[this.STATUS_IGNORED]=0;for(var j in f)if(f[j].enabled!==!1){h++;var k=b.data(d+".result."+j);k&&g[k]++}g[this.STATUS_VALID]+g[this.STATUS_IGNORED]===h?(this.$invalidFields=this.$invalidFields.not(b),b.trigger(a.Event(this.options.events.fieldSuccess),i)):(0===g[this.STATUS_NOT_VALIDATED]||!this.isOptionEnabled(e,"verbose"))&&0===g[this.STATUS_VALIDATING]&&g[this.STATUS_INVALID]>0&&(this.$invalidFields=this.$invalidFields.add(b),b.trigger(a.Event(this.options.events.fieldError),i))},_onSuccess:function(a){a.isDefaultPrevented()||this.disableSubmitButtons(!0).defaultSubmit()},_fixIcon:function(){},_createTooltip:function(){},_destroyTooltip:function(){},_hideTooltip:function(){},_showTooltip:function(){},defaultSubmit:function(){var b=this._namespace;this.$submitButton&&a("<input/>").attr({type:"hidden",name:this.$submitButton.attr("name")}).attr("data-"+b+"-submit-hidden","").val(this.$submitButton.val()).appendTo(this.$form),this.$form.off("submit."+b).submit()},disableSubmitButtons:function(a){return a?"disabled"!==this.options.live&&this.$form.find(this.options.button.selector).attr("disabled","disabled").addClass(this.options.button.disabled):this.$form.find(this.options.button.selector).removeAttr("disabled").removeClass(this.options.button.disabled),this},getFieldElements:function(b){if(!this._cacheFields[b])if(this.options.fields[b]&&this.options.fields[b].selector){var c=this.$form.find(this.options.fields[b].selector);this._cacheFields[b]=c.length?c:a(this.options.fields[b].selector)}else this._cacheFields[b]=this.$form.find('[name="'+b+'"]');return this._cacheFields[b]},getFieldValue:function(a,b){var c,d=this._namespace;if("string"==typeof a){if(c=this.getFieldElements(a),0===c.length)return null}else c=a,a=c.attr("data-"+d+"-field");if(!a||!this.options.fields[a])return c.val();var e=(this.options.fields[a].validators&&this.options.fields[a].validators[b]?this.options.fields[a].validators[b].transformer:null)||this.options.fields[a].transformer;return e?FormValidation.Helper.call(e,[c,b,this]):c.val()},getNamespace:function(){return this._namespace},getOptions:function(a,b,c){var d=this._namespace;if(!a)return c?this.options[c]:this.options;if("object"==typeof a&&(a=a.attr("data-"+d+"-field")),!this.options.fields[a])return null;var e=this.options.fields[a];return b?e.validators&&e.validators[b]?c?e.validators[b][c]:e.validators[b]:null:c?e[c]:e},getStatus:function(a,b){var c=this._namespace;switch(typeof a){case"object":return a.data(c+".result."+b);case"string":default:return this.getFieldElements(a).eq(0).data(c+".result."+b)}},isOptionEnabled:function(a,b){return!this.options.fields[a]||"true"!==this.options.fields[a][b]&&this.options.fields[a][b]!==!0?!this.options.fields[a]||"false"!==this.options.fields[a][b]&&this.options.fields[a][b]!==!1?"true"===this.options[b]||this.options[b]===!0:!1:!0},isValid:function(){for(var a in this.options.fields){var b=this.isValidField(a);if(null===b)return null;if(b===!1)return!1}return!0},isValidContainer:function(b){var c=this,d=this._namespace,e=[],f="string"==typeof b?a(b):b;if(0===f.length)return!0;f.find("[data-"+d+"-field]").each(function(){var b=a(this);c._isExcluded(b)||e.push(b)});for(var g=e.length,h=0;g>h;h++){var i=e[h],j=i.attr("data-"+d+"-field"),k=i.data(d+".messages").find("."+this.options.err.clazz.split(" ").join(".")+"[data-"+d+"-validator][data-"+d+'-for="'+j+'"]');if(k.filter("[data-"+d+'-result="'+this.STATUS_INVALID+'"]').length>0)return!1;if(k.filter("[data-"+d+'-result="'+this.STATUS_NOT_VALIDATED+'"]').length>0||k.filter("[data-"+d+'-result="'+this.STATUS_VALIDATING+'"]').length>0)return null}return!0},isValidField:function(b){var c=this._namespace,d=a([]);switch(typeof b){case"object":d=b,b=b.attr("data-"+c+"-field");break;case"string":d=this.getFieldElements(b)}if(0===d.length||!this.options.fields[b]||this.options.fields[b].enabled===!1)return!0;for(var e,f,g,h=d.attr("type"),i="radio"===h||"checkbox"===h?1:d.length,j=0;i>j;j++)if(e=d.eq(j),!this._isExcluded(e))for(f in this.options.fields[b].validators)if(this.options.fields[b].validators[f].enabled!==!1){if(g=e.data(c+".result."+f),g===this.STATUS_VALIDATING||g===this.STATUS_NOT_VALIDATED)return null;if(g===this.STATUS_INVALID)return!1}return!0},offLiveChange:function(b,c){if(null===b||0===b.length)return this;var d=this._namespace,e=this._getFieldTrigger(b.eq(0)),f=a.map(e,function(a){return a+"."+c+"."+d}).join(" ");return b.off(f),this},onLiveChange:function(b,c,d){if(null===b||0===b.length)return this;var e=this._namespace,f=this._getFieldTrigger(b.eq(0)),g=a.map(f,function(a){return a+"."+c+"."+e}).join(" ");switch(this.options.live){case"submitted":break;case"disabled":b.off(g);break;case"enabled":default:b.off(g).on(g,function(){d.apply(this,arguments)})}return this},updateMessage:function(b,c,d){var e=this,f=this._namespace,g=a([]);switch(typeof b){case"object":g=b,b=b.attr("data-"+f+"-field");break;case"string":g=this.getFieldElements(b)}return g.each(function(){a(this).data(f+".messages").find("."+e.options.err.clazz+"[data-"+f+'-validator="'+c+'"][data-'+f+'-for="'+b+'"]').html(d)}),this},updateStatus:function(b,c,d){var e=this._namespace,f=a([]);switch(typeof b){case"object":f=b,b=b.attr("data-"+e+"-field");break;case"string":f=this.getFieldElements(b)}if(!b||!this.options.fields[b])return this;c===this.STATUS_NOT_VALIDATED&&(this._submitIfValid=!1);for(var g=this,h=f.attr("type"),i=this.options.fields[b].row||this.options.row.selector,j="radio"===h||"checkbox"===h?1:f.length,k=0;j>k;k++){var l=f.eq(k);if(!this._isExcluded(l)){var m,n,o=l.closest(i),p=l.data(e+".messages"),q=p.find("."+this.options.err.clazz.split(" ").join(".")+"[data-"+e+"-validator][data-"+e+'-for="'+b+'"]'),r=d?q.filter("[data-"+e+'-validator="'+d+'"]'):q,s=l.data(e+".icon"),t="function"==typeof(this.options.fields[b].container||this.options.fields[b].err||this.options.err.container)?(this.options.fields[b].container||this.options.fields[b].err||this.options.err.container).call(this,l,this):this.options.fields[b].container||this.options.fields[b].err||this.options.err.container,u=null;if(d)l.data(e+".result."+d,c);else for(var v in this.options.fields[b].validators)l.data(e+".result."+v,c);switch(r.attr("data-"+e+"-result",c),c){case this.STATUS_VALIDATING:u=null,this.disableSubmitButtons(!0),l.removeClass(this.options.control.valid).removeClass(this.options.control.invalid),o.removeClass(this.options.row.valid).removeClass(this.options.row.invalid),s&&s.removeClass(this.options.icon.valid).removeClass(this.options.icon.invalid).addClass(this.options.icon.validating).show();break;case this.STATUS_INVALID:u=!1,this.disableSubmitButtons(!0),l.removeClass(this.options.control.valid).addClass(this.options.control.invalid),o.removeClass(this.options.row.valid).addClass(this.options.row.invalid),s&&s.removeClass(this.options.icon.valid).removeClass(this.options.icon.validating).addClass(this.options.icon.invalid).show();break;case this.STATUS_IGNORED:case this.STATUS_VALID:m=q.filter("[data-"+e+'-result="'+this.STATUS_VALIDATING+'"]').length>0,n=q.filter("[data-"+e+'-result="'+this.STATUS_NOT_VALIDATED+'"]').length>0;var w=q.filter("[data-"+e+'-result="'+this.STATUS_IGNORED+'"]').length;u=m||n?null:q.filter("[data-"+e+'-result="'+this.STATUS_VALID+'"]').length+w===q.length,l.removeClass(this.options.control.valid).removeClass(this.options.control.invalid),u===!0?(this.disableSubmitButtons(this.isValid()===!1),c===this.STATUS_VALID&&l.addClass(this.options.control.valid)):u===!1&&(this.disableSubmitButtons(!0),c===this.STATUS_VALID&&l.addClass(this.options.control.invalid)),s&&(s.removeClass(this.options.icon.invalid).removeClass(this.options.icon.validating).removeClass(this.options.icon.valid),(c===this.STATUS_VALID||w!==q.length)&&s.addClass(null===u?"":u?this.options.icon.valid:m?this.options.icon.validating:this.options.icon.invalid).show());var x=this.isValidContainer(o);null!==x&&(o.removeClass(this.options.row.valid).removeClass(this.options.row.invalid),(c===this.STATUS_VALID||w!==q.length)&&o.addClass(x?this.options.row.valid:this.options.row.invalid));break;case this.STATUS_NOT_VALIDATED:default:u=null,this.disableSubmitButtons(!1),l.removeClass(this.options.control.valid).removeClass(this.options.control.invalid),o.removeClass(this.options.row.valid).removeClass(this.options.row.invalid),s&&s.removeClass(this.options.icon.valid).removeClass(this.options.icon.invalid).removeClass(this.options.icon.validating).hide()}!s||"tooltip"!==t&&"popover"!==t?c===this.STATUS_INVALID?r.show():r.hide():u===!1?this._createTooltip(l,q.filter("[data-"+e+'-result="'+g.STATUS_INVALID+'"]').eq(0).html(),t):this._destroyTooltip(l,t),l.trigger(a.Event(this.options.events.fieldStatus),{bv:this,fv:this,field:b,element:l,status:c}),this._onFieldValidated(l,d)}}return this},validate:function(){if(a.isEmptyObject(this.options.fields))return this._submit(),this;this.disableSubmitButtons(!0),this._submitIfValid=!1;for(var b in this.options.fields)this.validateField(b);return this._submit(),this._submitIfValid=!0,this},validateField:function(b){var c=this._namespace,d=a([]);switch(typeof b){case"object":d=b,b=b.attr("data-"+c+"-field");break;case"string":d=this.getFieldElements(b)}if(0===d.length||!this.options.fields[b]||this.options.fields[b].enabled===!1)return this;for(var e,f,g=this,h=d.attr("type"),i="radio"===h||"checkbox"===h?1:d.length,j="radio"===h||"checkbox"===h,k=this.options.fields[b].validators,l=this.isOptionEnabled(b,"verbose"),m=0;i>m;m++){var n=d.eq(m);if(!this._isExcluded(n)){var o=!1;for(e in k){if(n.data(c+".dfs."+e)&&n.data(c+".dfs."+e).reject(),o)break;var p=n.data(c+".result."+e);if(p!==this.STATUS_VALID&&p!==this.STATUS_INVALID)if(k[e].enabled!==!1)if(n.data(c+".result."+e,this.STATUS_VALIDATING),f=FormValidation.Validator[e].validate(this,n,k[e]),"object"==typeof f&&f.resolve)this.updateStatus(j?b:n,this.STATUS_VALIDATING,e),n.data(c+".dfs."+e,f),f.done(function(a,b,d){a.removeData(c+".dfs."+b).data(c+".response."+b,d),d.message&&g.updateMessage(a,b,d.message),g.updateStatus(j?a.attr("data-"+c+"-field"):a,d.valid===!0?g.STATUS_VALID:d.valid===!1?g.STATUS_INVALID:g.STATUS_IGNORED,b),d.valid&&g._submitIfValid===!0?g._submit():d.valid!==!1||l||(o=!0)});else if("object"==typeof f&&void 0!==f.valid){if(n.data(c+".response."+e,f),f.message&&this.updateMessage(j?b:n,e,f.message),this.updateStatus(j?b:n,f.valid===!0?this.STATUS_VALID:f.valid===!1?this.STATUS_INVALID:this.STATUS_IGNORED,e),f.valid===!1&&!l)break}else if("boolean"==typeof f){if(n.data(c+".response."+e,f),this.updateStatus(j?b:n,f?this.STATUS_VALID:this.STATUS_INVALID,e),!f&&!l)break}else null===f&&(n.data(c+".response."+e,f),this.updateStatus(j?b:n,this.STATUS_IGNORED,e));else this.updateStatus(j?b:n,this.STATUS_IGNORED,e);else this._onFieldValidated(n,e)}}}return this},addField:function(b,c){var d=this._namespace,e=a([]);switch(typeof b){case"object":e=b,b=b.attr("data-"+d+"-field")||b.attr("name");break;case"string":delete this._cacheFields[b],e=this.getFieldElements(b)}e.attr("data-"+d+"-field",b);for(var f=e.attr("type"),g="radio"===f||"checkbox"===f?1:e.length,h=0;g>h;h++){var i=e.eq(h),j=this._parseOptions(i);j=null===j?c:a.extend(!0,j,c),this.options.fields[b]=a.extend(!0,this.options.fields[b],j),this._cacheFields[b]=this._cacheFields[b]?this._cacheFields[b].add(i):i,this._initField("checkbox"===f||"radio"===f?b:i)}return this.disableSubmitButtons(!1),this.$form.trigger(a.Event(this.options.events.fieldAdded),{field:b,element:e,options:this.options.fields[b]}),this},destroy:function(){var a,b,c,d,e,f,g,h=this._namespace;for(b in this.options.fields)for(c=this.getFieldElements(b),a=0;a<c.length;a++){d=c.eq(a);for(e in this.options.fields[b].validators)d.data(h+".dfs."+e)&&d.data(h+".dfs."+e).reject(),d.removeData(h+".result."+e).removeData(h+".response."+e).removeData(h+".dfs."+e),"function"==typeof FormValidation.Validator[e].destroy&&FormValidation.Validator[e].destroy(this,d,this.options.fields[b].validators[e])}for(b in this.options.fields)for(c=this.getFieldElements(b),g=this.options.fields[b].row||this.options.row.selector,a=0;a<c.length;a++){d=c.eq(a),d.data(h+".messages").find("."+this.options.err.clazz.split(" ").join(".")+"[data-"+h+"-validator][data-"+h+'-for="'+b+'"]').remove().end().end().removeData(h+".messages").closest(g).removeClass(this.options.row.valid).removeClass(this.options.row.invalid).removeClass(this.options.row.feedback).end().off("."+h).removeAttr("data-"+h+"-field");var i="function"==typeof(this.options.fields[b].container||this.options.fields[b].err||this.options.err.container)?(this.options.fields[b].container||this.options.fields[b].err||this.options.err.container).call(this,d,this):this.options.fields[b].container||this.options.fields[b].err||this.options.err.container;("tooltip"===i||"popover"===i)&&this._destroyTooltip(d,i),f=d.data(h+".icon"),f&&f.remove(),d.removeData(h+".icon").removeData(h+".trigger")}for(var j in this.options.addOns)"function"==typeof FormValidation.AddOn[j].destroy&&FormValidation.AddOn[j].destroy(this,this.options.addOns[j]);this.disableSubmitButtons(!1),this.$hiddenButton.remove(),this.$form.removeClass(this.options.elementClass).off("."+h).removeData("bootstrapValidator").removeData("formValidation").find("[data-"+h+"-submit-hidden]").remove().end().find('[type="submit"]').off("click."+h)},enableFieldValidators:function(a,b,c){var d=this.options.fields[a].validators;if(c&&d&&d[c]&&d[c].enabled!==b)this.options.fields[a].validators[c].enabled=b,this.updateStatus(a,this.STATUS_NOT_VALIDATED,c);else if(!c&&this.options.fields[a].enabled!==b){this.options.fields[a].enabled=b;for(var e in d)this.enableFieldValidators(a,b,e)}return this},getDynamicOption:function(a,b){var c="string"==typeof a?this.getFieldElements(a):a,d=c.val();if("function"==typeof b)return FormValidation.Helper.call(b,[d,this,c]);if("string"==typeof b){var e=this.getFieldElements(b);return e.length?e.val():FormValidation.Helper.call(b,[d,this,c])||b}return null},getForm:function(){return this.$form},getInvalidFields:function(){return this.$invalidFields},getLocale:function(){return this.options.locale},getMessages:function(b,c){var d=this,e=this._namespace,f=[],g=a([]);switch(!0){case b&&"object"==typeof b:g=b;break;case b&&"string"==typeof b:var h=this.getFieldElements(b);if(h.length>0){var i=h.attr("type");g="radio"===i||"checkbox"===i?h.eq(0):h}break;default:g=this.$invalidFields}var j=c?"[data-"+e+'-validator="'+c+'"]':"";return g.each(function(){f=f.concat(a(this).data(e+".messages").find("."+d.options.err.clazz+"[data-"+e+'-for="'+a(this).attr("data-"+e+"-field")+'"][data-'+e+'-result="'+d.STATUS_INVALID+'"]'+j).map(function(){var b=a(this).attr("data-"+e+"-validator"),c=a(this).attr("data-"+e+"-for");return d.options.fields[c].validators[b].enabled===!1?"":a(this).html()}).get())}),f},getSubmitButton:function(){return this.$submitButton},removeField:function(b){var c=this._namespace,d=a([]);switch(typeof b){case"object":d=b,b=b.attr("data-"+c+"-field")||b.attr("name"),d.attr("data-"+c+"-field",b);break;case"string":d=this.getFieldElements(b)}if(0===d.length)return this;for(var e=d.attr("type"),f="radio"===e||"checkbox"===e?1:d.length,g=0;f>g;g++){var h=d.eq(g);this.$invalidFields=this.$invalidFields.not(h),this._cacheFields[b]=this._cacheFields[b].not(h)}return this._cacheFields[b]&&0!==this._cacheFields[b].length||delete this.options.fields[b],("checkbox"===e||"radio"===e)&&this._initField(b),this.disableSubmitButtons(!1),this.$form.trigger(a.Event(this.options.events.fieldRemoved),{field:b,element:d}),this},resetField:function(b,c){var d=this._namespace,e=a([]);switch(typeof b){case"object":e=b,b=b.attr("data-"+d+"-field");break;case"string":e=this.getFieldElements(b)}var f=e.length;if(this.options.fields[b])for(var g=0;f>g;g++)for(var h in this.options.fields[b].validators)e.eq(g).removeData(d+".dfs."+h);if(c){var i=e.attr("type");"radio"===i||"checkbox"===i?e.prop("checked",!1).removeAttr("selected"):e.val("")}return this.updateStatus(b,this.STATUS_NOT_VALIDATED),this;},resetForm:function(b){for(var c in this.options.fields)this.resetField(c,b);return this.$invalidFields=a([]),this.$submitButton=null,this.disableSubmitButtons(!1),this},revalidateField:function(a){return this.updateStatus(a,this.STATUS_NOT_VALIDATED).validateField(a),this},setLocale:function(b){return this.options.locale=b,this.$form.trigger(a.Event(this.options.events.localeChanged),{locale:b,bv:this,fv:this}),this},updateOption:function(a,b,c,d){var e=this._namespace;return"object"==typeof a&&(a=a.attr("data-"+e+"-field")),this.options.fields[a]&&this.options.fields[a].validators[b]&&(this.options.fields[a].validators[b][c]=d,this.updateStatus(a,this.STATUS_NOT_VALIDATED,b)),this},validateContainer:function(b){var c=this,d=this._namespace,e=[],f="string"==typeof b?a(b):b;if(0===f.length)return this;f.find("[data-"+d+"-field]").each(function(){var b=a(this);c._isExcluded(b)||e.push(b)});for(var g=e.length,h=0;g>h;h++)this.validateField(e[h]);return this}},a.fn.formValidation=function(b){var c=arguments;return this.each(function(){var d=a(this),e=d.data("formValidation"),f="object"==typeof b&&b;if(!e){var g=(f.framework||d.attr("data-fv-framework")||"bootstrap").toLowerCase(),h=g.substr(0,1).toUpperCase()+g.substr(1);if("undefined"==typeof FormValidation.Framework[h])throw new Error("The class FormValidation.Framework."+h+" is not implemented");e=new FormValidation.Framework[h](this,f),d.addClass("fv-form-"+g).data("formValidation",e)}"string"==typeof b&&e[b].apply(e,Array.prototype.slice.call(c,1))})},a.fn.formValidation.Constructor=FormValidation.Base,a.fn.formValidation.DEFAULT_OPTIONS={autoFocus:!0,declarative:!0,elementClass:"fv-form",events:{formInit:"init.form.fv",formError:"err.form.fv",formSuccess:"success.form.fv",fieldAdded:"added.field.fv",fieldRemoved:"removed.field.fv",fieldInit:"init.field.fv",fieldError:"err.field.fv",fieldSuccess:"success.field.fv",fieldStatus:"status.field.fv",localeChanged:"changed.locale.fv",validatorError:"err.validator.fv",validatorSuccess:"success.validator.fv",validatorIgnored:"ignored.validator.fv"},excluded:[":disabled",":hidden",":not(:visible)"],fields:null,live:"enabled",locale:"en_US",message:"This value is not valid",threshold:null,verbose:!0,button:{selector:'[type="submit"]:not([formnovalidate])',disabled:""},control:{valid:"",invalid:""},err:{clazz:"",container:null,parent:null},icon:{valid:null,invalid:null,validating:null,feedback:""},row:{selector:null,valid:"",invalid:"",feedback:""}}}(jQuery),function(a){FormValidation.Helper={call:function(a,b){if("function"==typeof a)return a.apply(this,b);if("string"==typeof a){"()"===a.substring(a.length-2)&&(a=a.substring(0,a.length-2));for(var c=a.split("."),d=c.pop(),e=window,f=0;f<c.length;f++)e=e[c[f]];return"undefined"==typeof e[d]?null:e[d].apply(this,b)}},date:function(a,b,c,d){if(isNaN(a)||isNaN(b)||isNaN(c))return!1;if(c.length>2||b.length>2||a.length>4)return!1;if(c=parseInt(c,10),b=parseInt(b,10),a=parseInt(a,10),1e3>a||a>9999||0>=b||b>12)return!1;var e=[31,28,31,30,31,30,31,31,30,31,30,31];if((a%400===0||a%100!==0&&a%4===0)&&(e[1]=29),0>=c||c>e[b-1])return!1;if(d===!0){var f=new Date,g=f.getFullYear(),h=f.getMonth(),i=f.getDate();return g>a||a===g&&h>b-1||a===g&&b-1===h&&i>c}return!0},format:function(b,c){a.isArray(c)||(c=[c]);for(var d in c)b=b.replace("%s",c[d]);return b},luhn:function(a){for(var b=a.length,c=0,d=[[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]],e=0;b--;)e+=d[c][parseInt(a.charAt(b),10)],c^=1;return e%10===0&&e>0},mod11And10:function(a){for(var b=5,c=a.length,d=0;c>d;d++)b=(2*(b||10)%11+parseInt(a.charAt(d),10))%10;return 1===b},mod37And36:function(a,b){b=b||"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";for(var c=b.length,d=a.length,e=Math.floor(c/2),f=0;d>f;f++)e=(2*(e||c)%(c+1)+b.indexOf(a.charAt(f)))%c;return 1===e}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{base64:{"default":"Please enter a valid base 64 encoded"}}}),FormValidation.Validator.base64={validate:function(a,b){var c=a.getFieldValue(b,"base64");return""===c?!0:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(c)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{between:{"default":"Please enter a value between %s and %s",notInclusive:"Please enter a value between %s and %s strictly"}}}),FormValidation.Validator.between={html5Attributes:{message:"message",min:"min",max:"max",inclusive:"inclusive"},enableByHtml5:function(a){return"range"===a.attr("type")?{min:a.attr("min"),max:a.attr("max")}:!1},validate:function(b,c,d){var e=b.getFieldValue(c,"between");if(""===e)return!0;if(e=this._format(e),!a.isNumeric(e))return!1;var f=b.getLocale(),g=a.isNumeric(d.min)?d.min:b.getDynamicOption(c,d.min),h=a.isNumeric(d.max)?d.max:b.getDynamicOption(c,d.max),i=this._format(g),j=this._format(h);return e=parseFloat(e),d.inclusive===!0||void 0===d.inclusive?{valid:e>=i&&j>=e,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].between["default"],[g,h])}:{valid:e>i&&j>e,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].between.notInclusive,[g,h])}},_format:function(a){return(a+"").replace(",",".")}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{bic:{"default":"Please enter a valid BIC number"}}}),FormValidation.Validator.bic={validate:function(a,b){var c=a.getFieldValue(b,"bic");return""===c?!0:/^[a-zA-Z]{6}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?$/.test(c)}}}(jQuery),function(){FormValidation.Validator.blank={validate:function(){return!0}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{callback:{"default":"Please enter a valid value"}}}),FormValidation.Validator.callback={html5Attributes:{message:"message",callback:"callback"},validate:function(b,c,d){var e=b.getFieldValue(c,"callback"),f=new a.Deferred,g={valid:!0};if(d.callback){var h=FormValidation.Helper.call(d.callback,[e,b,c]);g="boolean"==typeof h||null===h?{valid:h}:h}return f.resolve(c,"callback",g),f}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{choice:{"default":"Please enter a valid value",less:"Please choose %s options at minimum",more:"Please choose %s options at maximum",between:"Please choose %s - %s options"}}}),FormValidation.Validator.choice={html5Attributes:{message:"message",min:"min",max:"max"},validate:function(b,c,d){var e=b.getLocale(),f=b.getNamespace(),g=c.is("select")?b.getFieldElements(c.attr("data-"+f+"-field")).find("option").filter(":selected").length:b.getFieldElements(c.attr("data-"+f+"-field")).filter(":checked").length,h=d.min?a.isNumeric(d.min)?d.min:b.getDynamicOption(c,d.min):null,i=d.max?a.isNumeric(d.max)?d.max:b.getDynamicOption(c,d.max):null,j=!0,k=d.message||FormValidation.I18n[e].choice["default"];switch((h&&g<parseInt(h,10)||i&&g>parseInt(i,10))&&(j=!1),!0){case!!h&&!!i:k=FormValidation.Helper.format(d.message||FormValidation.I18n[e].choice.between,[parseInt(h,10),parseInt(i,10)]);break;case!!h:k=FormValidation.Helper.format(d.message||FormValidation.I18n[e].choice.less,parseInt(h,10));break;case!!i:k=FormValidation.Helper.format(d.message||FormValidation.I18n[e].choice.more,parseInt(i,10))}return{valid:j,message:k}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{color:{"default":"Please enter a valid color"}}}),FormValidation.Validator.color={html5Attributes:{message:"message",type:"type"},enableByHtml5:function(a){return"color"===a.attr("type")},SUPPORTED_TYPES:["hex","rgb","rgba","hsl","hsla","keyword"],KEYWORD_COLORS:["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],validate:function(b,c,d){var e=b.getFieldValue(c,"color");if(""===e)return!0;if(this.enableByHtml5(c))return/^#[0-9A-F]{6}$/i.test(e);var f=d.type||this.SUPPORTED_TYPES;a.isArray(f)||(f=f.replace(/s/g,"").split(","));for(var g,h,i=!1,j=0;j<f.length;j++)if(h=f[j],g="_"+h.toLowerCase(),i=i||this[g](e))return!0;return!1},_hex:function(a){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a)},_hsl:function(a){return/^hsl\((\s*(-?\d+)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*)\)$/.test(a)},_hsla:function(a){return/^hsla\((\s*(-?\d+)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*,){2}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/.test(a)},_keyword:function(b){return a.inArray(b,this.KEYWORD_COLORS)>=0},_rgb:function(a){var b=/^rgb\((\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*,){2}(\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*)\)$/,c=/^rgb\((\s*(\b(0?\d{1,2}|100)\b%)\s*,){2}(\s*(\b(0?\d{1,2}|100)\b%)\s*)\)$/;return b.test(a)||c.test(a)},_rgba:function(a){var b=/^rgba\((\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*,){3}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/,c=/^rgba\((\s*(\b(0?\d{1,2}|100)\b%)\s*,){3}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/;return b.test(a)||c.test(a)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{creditCard:{"default":"Please enter a valid credit card number"}}}),FormValidation.Validator.creditCard={validate:function(b,c){var d=b.getFieldValue(c,"creditCard");if(""===d)return!0;if(/[^0-9-\s]+/.test(d))return!1;if(d=d.replace(/\D/g,""),!FormValidation.Helper.luhn(d))return!1;var e,f,g={AMERICAN_EXPRESS:{length:[15],prefix:["34","37"]},DINERS_CLUB:{length:[14],prefix:["300","301","302","303","304","305","36"]},DINERS_CLUB_US:{length:[16],prefix:["54","55"]},DISCOVER:{length:[16],prefix:["6011","622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925","644","645","646","647","648","649","65"]},JCB:{length:[16],prefix:["3528","3529","353","354","355","356","357","358"]},LASER:{length:[16,17,18,19],prefix:["6304","6706","6771","6709"]},MAESTRO:{length:[12,13,14,15,16,17,18,19],prefix:["5018","5020","5038","6304","6759","6761","6762","6763","6764","6765","6766"]},MASTERCARD:{length:[16],prefix:["51","52","53","54","55"]},SOLO:{length:[16,18,19],prefix:["6334","6767"]},UNIONPAY:{length:[16,17,18,19],prefix:["622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925"]},VISA:{length:[16],prefix:["4"]}};for(e in g)for(f in g[e].prefix)if(d.substr(0,g[e].prefix[f].length)===g[e].prefix[f]&&-1!==a.inArray(d.length,g[e].length))return{valid:!0,type:e};return!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{cusip:{"default":"Please enter a valid CUSIP number"}}}),FormValidation.Validator.cusip={validate:function(b,c){var d=b.getFieldValue(c,"cusip");if(""===d)return!0;if(d=d.toUpperCase(),!/^[0-9A-Z]{9}$/.test(d))return!1;for(var e=a.map(d.split(""),function(a){var b=a.charCodeAt(0);return b>="A".charCodeAt(0)&&b<="Z".charCodeAt(0)?b-"A".charCodeAt(0)+10:a}),f=e.length,g=0,h=0;f-1>h;h++){var i=parseInt(e[h],10);h%2!==0&&(i*=2),i>9&&(i-=9),g+=i}return g=(10-g%10)%10,g===parseInt(e[f-1],10)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{cvv:{"default":"Please enter a valid CVV number"}}}),FormValidation.Validator.cvv={html5Attributes:{message:"message",ccfield:"creditCardField"},init:function(a,b,c){if(c.creditCardField){var d=a.getFieldElements(c.creditCardField);a.onLiveChange(d,"live_cvv",function(){var c=a.getStatus(b,"cvv");c!==a.STATUS_NOT_VALIDATED&&a.revalidateField(b)})}},destroy:function(a,b,c){if(c.creditCardField){var d=a.getFieldElements(c.creditCardField);a.offLiveChange(d,"live_cvv")}},validate:function(b,c,d){var e=b.getFieldValue(c,"cvv");if(""===e)return!0;if(!/^[0-9]{3,4}$/.test(e))return!1;if(!d.creditCardField)return!0;var f=b.getFieldElements(d.creditCardField).val();if(""===f)return!0;f=f.replace(/\D/g,"");var g,h,i={AMERICAN_EXPRESS:{length:[15],prefix:["34","37"]},DINERS_CLUB:{length:[14],prefix:["300","301","302","303","304","305","36"]},DINERS_CLUB_US:{length:[16],prefix:["54","55"]},DISCOVER:{length:[16],prefix:["6011","622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925","644","645","646","647","648","649","65"]},JCB:{length:[16],prefix:["3528","3529","353","354","355","356","357","358"]},LASER:{length:[16,17,18,19],prefix:["6304","6706","6771","6709"]},MAESTRO:{length:[12,13,14,15,16,17,18,19],prefix:["5018","5020","5038","6304","6759","6761","6762","6763","6764","6765","6766"]},MASTERCARD:{length:[16],prefix:["51","52","53","54","55"]},SOLO:{length:[16,18,19],prefix:["6334","6767"]},UNIONPAY:{length:[16,17,18,19],prefix:["622126","622127","622128","622129","62213","62214","62215","62216","62217","62218","62219","6222","6223","6224","6225","6226","6227","6228","62290","62291","622920","622921","622922","622923","622924","622925"]},VISA:{length:[16],prefix:["4"]}},j=null;for(g in i)for(h in i[g].prefix)if(f.substr(0,i[g].prefix[h].length)===i[g].prefix[h]&&-1!==a.inArray(f.length,i[g].length)){j=g;break}return null===j?!1:"AMERICAN_EXPRESS"===j?4===e.length:3===e.length}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{date:{"default":"Please enter a valid date",min:"Please enter a date after %s",max:"Please enter a date before %s",range:"Please enter a date in the range %s - %s"}}}),FormValidation.Validator.date={html5Attributes:{message:"message",format:"format",min:"min",max:"max",separator:"separator"},validate:function(b,c,d){var e=b.getFieldValue(c,"date");if(""===e)return!0;d.format=d.format||"MM/DD/YYYY","date"===c.attr("type")&&(d.format="YYYY-MM-DD");var f=b.getLocale(),g=d.message||FormValidation.I18n[f].date["default"],h=d.format.split(" "),i=h[0],j=h.length>1?h[1]:null,k=h.length>2?h[2]:null,l=e.split(" "),m=l[0],n=l.length>1?l[1]:null;if(h.length!==l.length)return{valid:!1,message:g};var o=d.separator;if(o||(o=-1!==m.indexOf("/")?"/":-1!==m.indexOf("-")?"-":-1!==m.indexOf(".")?".":null),null===o||-1===m.indexOf(o))return{valid:!1,message:g};if(m=m.split(o),i=i.split(o),m.length!==i.length)return{valid:!1,message:g};var p=m[a.inArray("YYYY",i)],q=m[a.inArray("MM",i)],r=m[a.inArray("DD",i)];if(!p||!q||!r||4!==p.length)return{valid:!1,message:g};var s=null,t=null,u=null;if(j){if(j=j.split(":"),n=n.split(":"),j.length!==n.length)return{valid:!1,message:g};if(t=n.length>0?n[0]:null,s=n.length>1?n[1]:null,u=n.length>2?n[2]:null,""===t||""===s||""===u)return{valid:!1,message:g};if(u){if(isNaN(u)||u.length>2)return{valid:!1,message:g};if(u=parseInt(u,10),0>u||u>60)return{valid:!1,message:g}}if(t){if(isNaN(t)||t.length>2)return{valid:!1,message:g};if(t=parseInt(t,10),0>t||t>=24||k&&t>12)return{valid:!1,message:g}}if(s){if(isNaN(s)||s.length>2)return{valid:!1,message:g};if(s=parseInt(s,10),0>s||s>59)return{valid:!1,message:g}}}var v=FormValidation.Helper.date(p,q,r),w=null,x=null,y=d.min,z=d.max;switch(y&&(isNaN(Date.parse(y))&&(y=b.getDynamicOption(c,y)),w=y instanceof Date?y:this._parseDate(y,i,o),y=y instanceof Date?this._formatDate(y,d.format):y),z&&(isNaN(Date.parse(z))&&(z=b.getDynamicOption(c,z)),x=z instanceof Date?z:this._parseDate(z,i,o),z=z instanceof Date?this._formatDate(z,d.format):z),m=new Date(p,q-1,r,t,s,u),!0){case y&&!z&&v:v=m.getTime()>=w.getTime(),g=d.message||FormValidation.Helper.format(FormValidation.I18n[f].date.min,y);break;case z&&!y&&v:v=m.getTime()<=x.getTime(),g=d.message||FormValidation.Helper.format(FormValidation.I18n[f].date.max,z);break;case z&&y&&v:v=m.getTime()<=x.getTime()&&m.getTime()>=w.getTime(),g=d.message||FormValidation.Helper.format(FormValidation.I18n[f].date.range,[y,z])}return{valid:v,message:g}},_parseDate:function(b,c,d){var e=0,f=0,g=0,h=b.split(" "),i=h[0],j=h.length>1?h[1]:null;i=i.split(d);var k=i[a.inArray("YYYY",c)],l=i[a.inArray("MM",c)],m=i[a.inArray("DD",c)];return j&&(j=j.split(":"),f=j.length>0?j[0]:null,e=j.length>1?j[1]:null,g=j.length>2?j[2]:null),new Date(k,l-1,m,f,e,g)},_formatDate:function(a,b){b=b.replace(/Y/g,"y").replace(/M/g,"m").replace(/D/g,"d").replace(/:m/g,":M").replace(/:mm/g,":MM").replace(/:S/,":s").replace(/:SS/,":ss");var c={d:function(a){return a.getDate()},dd:function(a){var b=a.getDate();return 10>b?"0"+b:b},m:function(a){return a.getMonth()+1},mm:function(a){var b=a.getMonth()+1;return 10>b?"0"+b:b},yy:function(a){return(""+a.getFullYear()).substr(2)},yyyy:function(a){return a.getFullYear()},h:function(a){return a.getHours()%12||12},hh:function(a){var b=a.getHours()%12||12;return 10>b?"0"+b:b},H:function(a){return a.getHours()},HH:function(a){var b=a.getHours();return 10>b?"0"+b:b},M:function(a){return a.getMinutes()},MM:function(a){var b=a.getMinutes();return 10>b?"0"+b:b},s:function(a){return a.getSeconds()},ss:function(a){var b=a.getSeconds();return 10>b?"0"+b:b}};return b.replace(/d{1,4}|m{1,4}|yy(?:yy)?|([HhMs])\1?|"[^"]*"|'[^']*'/g,function(b){return c[b]?c[b](a):b.slice(1,b.length-1)})}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{different:{"default":"Please enter a different value"}}}),FormValidation.Validator.different={html5Attributes:{message:"message",field:"field"},init:function(a,b,c){for(var d=c.field.split(","),e=0;e<d.length;e++){var f=a.getFieldElements(d[e]);a.onLiveChange(f,"live_different",function(){var c=a.getStatus(b,"different");c!==a.STATUS_NOT_VALIDATED&&a.revalidateField(b)})}},destroy:function(a,b,c){for(var d=c.field.split(","),e=0;e<d.length;e++){var f=a.getFieldElements(d[e]);a.offLiveChange(f,"live_different")}},validate:function(a,b,c){var d=a.getFieldValue(b,"different");if(""===d)return!0;for(var e=c.field.split(","),f=!0,g=0;g<e.length;g++){var h=a.getFieldElements(e[g]);if(null!=h&&0!==h.length){var i=a.getFieldValue(h,"different");d===i?f=!1:""!==i&&a.updateStatus(h,a.STATUS_VALID,"different")}}return f}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{digits:{"default":"Please enter only digits"}}}),FormValidation.Validator.digits={validate:function(a,b){var c=a.getFieldValue(b,"digits");return""===c?!0:/^\d+$/.test(c)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{ean:{"default":"Please enter a valid EAN number"}}}),FormValidation.Validator.ean={validate:function(a,b){var c=a.getFieldValue(b,"ean");if(""===c)return!0;if(!/^(\d{8}|\d{12}|\d{13})$/.test(c))return!1;for(var d=c.length,e=0,f=8===d?[3,1]:[1,3],g=0;d-1>g;g++)e+=parseInt(c.charAt(g),10)*f[g%2];return e=(10-e%10)%10,e+""===c.charAt(d-1)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{ein:{"default":"Please enter a valid EIN number"}}}),FormValidation.Validator.ein={CAMPUS:{ANDOVER:["10","12"],ATLANTA:["60","67"],AUSTIN:["50","53"],BROOKHAVEN:["01","02","03","04","05","06","11","13","14","16","21","22","23","25","34","51","52","54","55","56","57","58","59","65"],CINCINNATI:["30","32","35","36","37","38","61"],FRESNO:["15","24"],KANSAS_CITY:["40","44"],MEMPHIS:["94","95"],OGDEN:["80","90"],PHILADELPHIA:["33","39","41","42","43","46","48","62","63","64","66","68","71","72","73","74","75","76","77","81","82","83","84","85","86","87","88","91","92","93","98","99"],INTERNET:["20","26","27","45","46"],SMALL_BUSINESS_ADMINISTRATION:["31"]},validate:function(b,c){var d=b.getFieldValue(c,"ein");if(""===d)return!0;if(!/^[0-9]{2}-?[0-9]{7}$/.test(d))return!1;var e=d.substr(0,2)+"";for(var f in this.CAMPUS)if(-1!==a.inArray(e,this.CAMPUS[f]))return{valid:!0,campus:f};return!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{emailAddress:{"default":"Please enter a valid email address"}}}),FormValidation.Validator.emailAddress={html5Attributes:{message:"message",multiple:"multiple",separator:"separator"},enableByHtml5:function(a){return"email"===a.attr("type")},validate:function(a,b,c){var d=a.getFieldValue(b,"emailAddress");if(""===d)return!0;var e=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,f=c.multiple===!0||"true"===c.multiple;if(f){for(var g=c.separator||/[,;]/,h=this._splitEmailAddresses(d,g),i=0;i<h.length;i++)if(!e.test(h[i]))return!1;return!0}return e.test(d)},_splitEmailAddresses:function(a,b){for(var c=a.split(/"/),d=c.length,e=[],f="",g=0;d>g;g++)if(g%2===0){var h=c[g].split(b),i=h.length;if(1===i)f+=h[0];else{e.push(f+h[0]);for(var j=1;i-1>j;j++)e.push(h[j]);f=h[i-1]}}else f+='"'+c[g],d-1>g&&(f+='"');return e.push(f),e}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{file:{"default":"Please choose a valid file"}}}),FormValidation.Validator.file={html5Attributes:{extension:"extension",maxfiles:"maxFiles",minfiles:"minFiles",maxsize:"maxSize",minsize:"minSize",maxtotalsize:"maxTotalSize",mintotalsize:"minTotalSize",message:"message",type:"type"},validate:function(b,c,d){var e=b.getFieldValue(c,"file");if(""===e)return!0;var f,g=d.extension?d.extension.toLowerCase().split(","):null,h=d.type?d.type.toLowerCase().split(","):null,i=window.File&&window.FileList&&window.FileReader;if(i){var j=c.get(0).files,k=j.length,l=0;if(d.maxFiles&&k>parseInt(d.maxFiles,10)||d.minFiles&&k<parseInt(d.minFiles,10))return!1;for(var m=0;k>m;m++)if(l+=j[m].size,f=j[m].name.substr(j[m].name.lastIndexOf(".")+1),d.minSize&&j[m].size<parseInt(d.minSize,10)||d.maxSize&&j[m].size>parseInt(d.maxSize,10)||g&&-1===a.inArray(f.toLowerCase(),g)||j[m].type&&h&&-1===a.inArray(j[m].type.toLowerCase(),h))return!1;if(d.maxTotalSize&&l>parseInt(d.maxTotalSize,10)||d.minTotalSize&&l<parseInt(d.minTotalSize,10))return!1}else if(f=e.substr(e.lastIndexOf(".")+1),g&&-1===a.inArray(f.toLowerCase(),g))return!1;return!0}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{greaterThan:{"default":"Please enter a value greater than or equal to %s",notInclusive:"Please enter a value greater than %s"}}}),FormValidation.Validator.greaterThan={html5Attributes:{message:"message",value:"value",inclusive:"inclusive"},enableByHtml5:function(a){var b=a.attr("type"),c=a.attr("min");return c&&"date"!==b?{value:c}:!1},validate:function(b,c,d){var e=b.getFieldValue(c,"greaterThan");if(""===e)return!0;if(e=this._format(e),!a.isNumeric(e))return!1;var f=b.getLocale(),g=a.isNumeric(d.value)?d.value:b.getDynamicOption(c,d.value),h=this._format(g);return e=parseFloat(e),d.inclusive===!0||void 0===d.inclusive?{valid:e>=h,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].greaterThan["default"],g)}:{valid:e>h,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].greaterThan.notInclusive,g)}},_format:function(a){return(a+"").replace(",",".")}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{grid:{"default":"Please enter a valid GRId number"}}}),FormValidation.Validator.grid={validate:function(a,b){var c=a.getFieldValue(b,"grid");return""===c?!0:(c=c.toUpperCase(),/^[GRID:]*([0-9A-Z]{2})[-\s]*([0-9A-Z]{5})[-\s]*([0-9A-Z]{10})[-\s]*([0-9A-Z]{1})$/g.test(c)?(c=c.replace(/\s/g,"").replace(/-/g,""),"GRID:"===c.substr(0,5)&&(c=c.substr(5)),FormValidation.Helper.mod37And36(c)):!1)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{hex:{"default":"Please enter a valid hexadecimal number"}}}),FormValidation.Validator.hex={validate:function(a,b){var c=a.getFieldValue(b,"hex");return""===c?!0:/^[0-9a-fA-F]+$/.test(c)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{iban:{"default":"Please enter a valid IBAN number",country:"Please enter a valid IBAN number in %s",countries:{AD:"Andorra",AE:"United Arab Emirates",AL:"Albania",AO:"Angola",AT:"Austria",AZ:"Azerbaijan",BA:"Bosnia and Herzegovina",BE:"Belgium",BF:"Burkina Faso",BG:"Bulgaria",BH:"Bahrain",BI:"Burundi",BJ:"Benin",BR:"Brazil",CH:"Switzerland",CI:"Ivory Coast",CM:"Cameroon",CR:"Costa Rica",CV:"Cape Verde",CY:"Cyprus",CZ:"Czech Republic",DE:"Germany",DK:"Denmark",DO:"Dominican Republic",DZ:"Algeria",EE:"Estonia",ES:"Spain",FI:"Finland",FO:"Faroe Islands",FR:"France",GB:"United Kingdom",GE:"Georgia",GI:"Gibraltar",GL:"Greenland",GR:"Greece",GT:"Guatemala",HR:"Croatia",HU:"Hungary",IE:"Ireland",IL:"Israel",IR:"Iran",IS:"Iceland",IT:"Italy",JO:"Jordan",KW:"Kuwait",KZ:"Kazakhstan",LB:"Lebanon",LI:"Liechtenstein",LT:"Lithuania",LU:"Luxembourg",LV:"Latvia",MC:"Monaco",MD:"Moldova",ME:"Montenegro",MG:"Madagascar",MK:"Macedonia",ML:"Mali",MR:"Mauritania",MT:"Malta",MU:"Mauritius",MZ:"Mozambique",NL:"Netherlands",NO:"Norway",PK:"Pakistan",PL:"Poland",PS:"Palestine",PT:"Portugal",QA:"Qatar",RO:"Romania",RS:"Serbia",SA:"Saudi Arabia",SE:"Sweden",SI:"Slovenia",SK:"Slovakia",SM:"San Marino",SN:"Senegal",TL:"East Timor",TN:"Tunisia",TR:"Turkey",VG:"Virgin Islands, British",XK:"Republic of Kosovo"}}}}),FormValidation.Validator.iban={html5Attributes:{message:"message",country:"country",sepa:"sepa"},REGEX:{AD:"AD[0-9]{2}[0-9]{4}[0-9]{4}[A-Z0-9]{12}",AE:"AE[0-9]{2}[0-9]{3}[0-9]{16}",AL:"AL[0-9]{2}[0-9]{8}[A-Z0-9]{16}",AO:"AO[0-9]{2}[0-9]{21}",AT:"AT[0-9]{2}[0-9]{5}[0-9]{11}",AZ:"AZ[0-9]{2}[A-Z]{4}[A-Z0-9]{20}",BA:"BA[0-9]{2}[0-9]{3}[0-9]{3}[0-9]{8}[0-9]{2}",BE:"BE[0-9]{2}[0-9]{3}[0-9]{7}[0-9]{2}",BF:"BF[0-9]{2}[0-9]{23}",BG:"BG[0-9]{2}[A-Z]{4}[0-9]{4}[0-9]{2}[A-Z0-9]{8}",BH:"BH[0-9]{2}[A-Z]{4}[A-Z0-9]{14}",BI:"BI[0-9]{2}[0-9]{12}",BJ:"BJ[0-9]{2}[A-Z]{1}[0-9]{23}",BR:"BR[0-9]{2}[0-9]{8}[0-9]{5}[0-9]{10}[A-Z][A-Z0-9]",CH:"CH[0-9]{2}[0-9]{5}[A-Z0-9]{12}",CI:"CI[0-9]{2}[A-Z]{1}[0-9]{23}",CM:"CM[0-9]{2}[0-9]{23}",CR:"CR[0-9]{2}[0-9]{3}[0-9]{14}",CV:"CV[0-9]{2}[0-9]{21}",CY:"CY[0-9]{2}[0-9]{3}[0-9]{5}[A-Z0-9]{16}",CZ:"CZ[0-9]{2}[0-9]{20}",DE:"DE[0-9]{2}[0-9]{8}[0-9]{10}",DK:"DK[0-9]{2}[0-9]{14}",DO:"DO[0-9]{2}[A-Z0-9]{4}[0-9]{20}",DZ:"DZ[0-9]{2}[0-9]{20}",EE:"EE[0-9]{2}[0-9]{2}[0-9]{2}[0-9]{11}[0-9]{1}",ES:"ES[0-9]{2}[0-9]{4}[0-9]{4}[0-9]{1}[0-9]{1}[0-9]{10}",FI:"FI[0-9]{2}[0-9]{6}[0-9]{7}[0-9]{1}",FO:"FO[0-9]{2}[0-9]{4}[0-9]{9}[0-9]{1}",FR:"FR[0-9]{2}[0-9]{5}[0-9]{5}[A-Z0-9]{11}[0-9]{2}",GB:"GB[0-9]{2}[A-Z]{4}[0-9]{6}[0-9]{8}",GE:"GE[0-9]{2}[A-Z]{2}[0-9]{16}",GI:"GI[0-9]{2}[A-Z]{4}[A-Z0-9]{15}",GL:"GL[0-9]{2}[0-9]{4}[0-9]{9}[0-9]{1}",GR:"GR[0-9]{2}[0-9]{3}[0-9]{4}[A-Z0-9]{16}",GT:"GT[0-9]{2}[A-Z0-9]{4}[A-Z0-9]{20}",HR:"HR[0-9]{2}[0-9]{7}[0-9]{10}",HU:"HU[0-9]{2}[0-9]{3}[0-9]{4}[0-9]{1}[0-9]{15}[0-9]{1}",IE:"IE[0-9]{2}[A-Z]{4}[0-9]{6}[0-9]{8}",IL:"IL[0-9]{2}[0-9]{3}[0-9]{3}[0-9]{13}",IR:"IR[0-9]{2}[0-9]{22}",IS:"IS[0-9]{2}[0-9]{4}[0-9]{2}[0-9]{6}[0-9]{10}",IT:"IT[0-9]{2}[A-Z]{1}[0-9]{5}[0-9]{5}[A-Z0-9]{12}",JO:"JO[0-9]{2}[A-Z]{4}[0-9]{4}[0]{8}[A-Z0-9]{10}",KW:"KW[0-9]{2}[A-Z]{4}[0-9]{22}",KZ:"KZ[0-9]{2}[0-9]{3}[A-Z0-9]{13}",LB:"LB[0-9]{2}[0-9]{4}[A-Z0-9]{20}",LI:"LI[0-9]{2}[0-9]{5}[A-Z0-9]{12}",LT:"LT[0-9]{2}[0-9]{5}[0-9]{11}",LU:"LU[0-9]{2}[0-9]{3}[A-Z0-9]{13}",LV:"LV[0-9]{2}[A-Z]{4}[A-Z0-9]{13}",MC:"MC[0-9]{2}[0-9]{5}[0-9]{5}[A-Z0-9]{11}[0-9]{2}",MD:"MD[0-9]{2}[A-Z0-9]{20}",ME:"ME[0-9]{2}[0-9]{3}[0-9]{13}[0-9]{2}",MG:"MG[0-9]{2}[0-9]{23}",MK:"MK[0-9]{2}[0-9]{3}[A-Z0-9]{10}[0-9]{2}",ML:"ML[0-9]{2}[A-Z]{1}[0-9]{23}",MR:"MR13[0-9]{5}[0-9]{5}[0-9]{11}[0-9]{2}",MT:"MT[0-9]{2}[A-Z]{4}[0-9]{5}[A-Z0-9]{18}",MU:"MU[0-9]{2}[A-Z]{4}[0-9]{2}[0-9]{2}[0-9]{12}[0-9]{3}[A-Z]{3}",MZ:"MZ[0-9]{2}[0-9]{21}",NL:"NL[0-9]{2}[A-Z]{4}[0-9]{10}",NO:"NO[0-9]{2}[0-9]{4}[0-9]{6}[0-9]{1}",PK:"PK[0-9]{2}[A-Z]{4}[A-Z0-9]{16}",PL:"PL[0-9]{2}[0-9]{8}[0-9]{16}",PS:"PS[0-9]{2}[A-Z]{4}[A-Z0-9]{21}",PT:"PT[0-9]{2}[0-9]{4}[0-9]{4}[0-9]{11}[0-9]{2}",QA:"QA[0-9]{2}[A-Z]{4}[A-Z0-9]{21}",RO:"RO[0-9]{2}[A-Z]{4}[A-Z0-9]{16}",RS:"RS[0-9]{2}[0-9]{3}[0-9]{13}[0-9]{2}",SA:"SA[0-9]{2}[0-9]{2}[A-Z0-9]{18}",SE:"SE[0-9]{2}[0-9]{3}[0-9]{16}[0-9]{1}",SI:"SI[0-9]{2}[0-9]{5}[0-9]{8}[0-9]{2}",SK:"SK[0-9]{2}[0-9]{4}[0-9]{6}[0-9]{10}",SM:"SM[0-9]{2}[A-Z]{1}[0-9]{5}[0-9]{5}[A-Z0-9]{12}",SN:"SN[0-9]{2}[A-Z]{1}[0-9]{23}",TL:"TL38[0-9]{3}[0-9]{14}[0-9]{2}",TN:"TN59[0-9]{2}[0-9]{3}[0-9]{13}[0-9]{2}",TR:"TR[0-9]{2}[0-9]{5}[A-Z0-9]{1}[A-Z0-9]{16}",VG:"VG[0-9]{2}[A-Z]{4}[0-9]{16}",XK:"XK[0-9]{2}[0-9]{4}[0-9]{10}[0-9]{2}"},SEPA_COUNTRIES:["AT","BE","BG","CH","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GI","GR","HR","HU","IE","IS","IT","LI","LT","LU","LV","MC","MT","NL","NO","PL","PT","RO","SE","SI","SK","SM"],validate:function(b,c,d){var e=b.getFieldValue(c,"iban");if(""===e)return!0;e=e.replace(/[^a-zA-Z0-9]/g,"").toUpperCase();var f=d.country;f?"string"==typeof f&&this.REGEX[f]||(f=b.getDynamicOption(c,f)):f=e.substr(0,2);var g=b.getLocale();if(!this.REGEX[f])return!1;if(void 0!==typeof d.sepa){var h=-1!==a.inArray(f,this.SEPA_COUNTRIES);if(("true"===d.sepa||d.sepa===!0)&&!h||("false"===d.sepa||d.sepa===!1)&&h)return!1}if(!new RegExp("^"+this.REGEX[f]+"$").test(e))return{valid:!1,message:FormValidation.Helper.format(d.message||FormValidation.I18n[g].iban.country,FormValidation.I18n[g].iban.countries[f])};e=e.substr(4)+e.substr(0,4),e=a.map(e.split(""),function(a){var b=a.charCodeAt(0);return b>="A".charCodeAt(0)&&b<="Z".charCodeAt(0)?b-"A".charCodeAt(0)+10:a}),e=e.join("");for(var i=parseInt(e.substr(0,1),10),j=e.length,k=1;j>k;++k)i=(10*i+parseInt(e.substr(k,1),10))%97;return{valid:1===i,message:FormValidation.Helper.format(d.message||FormValidation.I18n[g].iban.country,FormValidation.I18n[g].iban.countries[f])}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{id:{"default":"Please enter a valid identification number",country:"Please enter a valid identification number in %s",countries:{BA:"Bosnia and Herzegovina",BG:"Bulgaria",BR:"Brazil",CH:"Switzerland",CL:"Chile",CN:"China",CZ:"Czech Republic",DK:"Denmark",EE:"Estonia",ES:"Spain",FI:"Finland",HR:"Croatia",IE:"Ireland",IS:"Iceland",LT:"Lithuania",LV:"Latvia",ME:"Montenegro",MK:"Macedonia",NL:"Netherlands",PL:"Poland",RO:"Romania",RS:"Serbia",SE:"Sweden",SI:"Slovenia",SK:"Slovakia",SM:"San Marino",TH:"Thailand",ZA:"South Africa"}}}}),FormValidation.Validator.id={html5Attributes:{message:"message",country:"country"},COUNTRY_CODES:["BA","BG","BR","CH","CL","CN","CZ","DK","EE","ES","FI","HR","IE","IS","LT","LV","ME","MK","NL","PL","RO","RS","SE","SI","SK","SM","TH","ZA"],validate:function(b,c,d){
var e=b.getFieldValue(c,"id");if(""===e)return!0;var f=b.getLocale(),g=d.country;if(g?("string"!=typeof g||-1===a.inArray(g.toUpperCase(),this.COUNTRY_CODES))&&(g=b.getDynamicOption(c,g)):g=e.substr(0,2),-1===a.inArray(g,this.COUNTRY_CODES))return!0;var h=["_",g.toLowerCase()].join("");return this[h](e)?!0:{valid:!1,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].id.country,FormValidation.I18n[f].id.countries[g.toUpperCase()])}},_validateJMBG:function(a,b){if(!/^\d{13}$/.test(a))return!1;var c=parseInt(a.substr(0,2),10),d=parseInt(a.substr(2,2),10),e=(parseInt(a.substr(4,3),10),parseInt(a.substr(7,2),10)),f=parseInt(a.substr(12,1),10);if(c>31||d>12)return!1;for(var g=0,h=0;6>h;h++)g+=(7-h)*(parseInt(a.charAt(h),10)+parseInt(a.charAt(h+6),10));if(g=11-g%11,(10===g||11===g)&&(g=0),g!==f)return!1;switch(b.toUpperCase()){case"BA":return e>=10&&19>=e;case"MK":return e>=41&&49>=e;case"ME":return e>=20&&29>=e;case"RS":return e>=70&&99>=e;case"SI":return e>=50&&59>=e;default:return!0}},_ba:function(a){return this._validateJMBG(a,"BA")},_mk:function(a){return this._validateJMBG(a,"MK")},_me:function(a){return this._validateJMBG(a,"ME")},_rs:function(a){return this._validateJMBG(a,"RS")},_si:function(a){return this._validateJMBG(a,"SI")},_bg:function(a){if(!/^\d{10}$/.test(a)&&!/^\d{6}\s\d{3}\s\d{1}$/.test(a))return!1;a=a.replace(/\s/g,"");var b=parseInt(a.substr(0,2),10)+1900,c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10);if(c>40?(b+=100,c-=40):c>20&&(b-=100,c-=20),!FormValidation.Helper.date(b,c,d))return!1;for(var e=0,f=[2,4,8,5,10,9,7,3,6],g=0;9>g;g++)e+=parseInt(a.charAt(g),10)*f[g];return e=e%11%10,e+""===a.substr(9,1)},_br:function(a){if(a=a.replace(/\D/g,""),!/^\d{11}$/.test(a)||/^1{11}|2{11}|3{11}|4{11}|5{11}|6{11}|7{11}|8{11}|9{11}|0{11}$/.test(a))return!1;for(var b=0,c=0;9>c;c++)b+=(10-c)*parseInt(a.charAt(c),10);if(b=11-b%11,(10===b||11===b)&&(b=0),b+""!==a.charAt(9))return!1;var d=0;for(c=0;10>c;c++)d+=(11-c)*parseInt(a.charAt(c),10);return d=11-d%11,(10===d||11===d)&&(d=0),d+""===a.charAt(10)},_ch:function(a){if(!/^756[\.]{0,1}[0-9]{4}[\.]{0,1}[0-9]{4}[\.]{0,1}[0-9]{2}$/.test(a))return!1;a=a.replace(/\D/g,"").substr(3);for(var b=a.length,c=0,d=8===b?[3,1]:[1,3],e=0;b-1>e;e++)c+=parseInt(a.charAt(e),10)*d[e%2];return c=10-c%10,c+""===a.charAt(b-1)},_cl:function(a){if(!/^\d{7,8}[-]{0,1}[0-9K]$/i.test(a))return!1;for(a=a.replace(/\-/g,"");a.length<9;)a="0"+a;for(var b=0,c=[3,2,7,6,5,4,3,2],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b=11-b%11,11===b?b=0:10===b&&(b="K"),b+""===a.charAt(8).toUpperCase()},_cn:function(b){if(b=b.trim(),!/^\d{15}$/.test(b)&&!/^\d{17}[\dXx]{1}$/.test(b))return!1;var c={11:{0:[0],1:[[0,9],[11,17]],2:[0,28,29]},12:{0:[0],1:[[0,16]],2:[0,21,23,25]},13:{0:[0],1:[[0,5],7,8,21,[23,33],[81,85]],2:[[0,5],[7,9],[23,25],27,29,30,81,83],3:[[0,4],[21,24]],4:[[0,4],6,21,[23,35],81],5:[[0,3],[21,35],81,82],6:[[0,4],[21,38],[81,84]],7:[[0,3],5,6,[21,33]],8:[[0,4],[21,28]],9:[[0,3],[21,30],[81,84]],10:[[0,3],[22,26],28,81,82],11:[[0,2],[21,28],81,82]},14:{0:[0],1:[0,1,[5,10],[21,23],81],2:[[0,3],11,12,[21,27]],3:[[0,3],11,21,22],4:[[0,2],11,21,[23,31],81],5:[[0,2],21,22,24,25,81],6:[[0,3],[21,24]],7:[[0,2],[21,29],81],8:[[0,2],[21,30],81,82],9:[[0,2],[21,32],81],10:[[0,2],[21,34],81,82],11:[[0,2],[21,30],81,82],23:[[0,3],22,23,[25,30],32,33]},15:{0:[0],1:[[0,5],[21,25]],2:[[0,7],[21,23]],3:[[0,4]],4:[[0,4],[21,26],[28,30]],5:[[0,2],[21,26],81],6:[[0,2],[21,27]],7:[[0,3],[21,27],[81,85]],8:[[0,2],[21,26]],9:[[0,2],[21,29],81],22:[[0,2],[21,24]],25:[[0,2],[22,31]],26:[[0,2],[24,27],[29,32],34],28:[0,1,[22,27]],29:[0,[21,23]]},21:{0:[0],1:[[0,6],[11,14],[22,24],81],2:[[0,4],[11,13],24,[81,83]],3:[[0,4],11,21,23,81],4:[[0,4],11,[21,23]],5:[[0,5],21,22],6:[[0,4],24,81,82],7:[[0,3],11,26,27,81,82],8:[[0,4],11,81,82],9:[[0,5],11,21,22],10:[[0,5],11,21,81],11:[[0,3],21,22],12:[[0,2],4,21,23,24,81,82],13:[[0,3],21,22,24,81,82],14:[[0,4],21,22,81]},22:{0:[0],1:[[0,6],12,22,[81,83]],2:[[0,4],11,21,[81,84]],3:[[0,3],22,23,81,82],4:[[0,3],21,22],5:[[0,3],21,23,24,81,82],6:[[0,2],4,5,[21,23],25,81],7:[[0,2],[21,24],81],8:[[0,2],21,22,81,82],24:[[0,6],24,26]},23:{0:[0],1:[[0,12],21,[23,29],[81,84]],2:[[0,8],21,[23,25],27,[29,31],81],3:[[0,7],21,81,82],4:[[0,7],21,22],5:[[0,3],5,6,[21,24]],6:[[0,6],[21,24]],7:[[0,16],22,81],8:[[0,5],11,22,26,28,33,81,82],9:[[0,4],21],10:[[0,5],24,25,81,[83,85]],11:[[0,2],21,23,24,81,82],12:[[0,2],[21,26],[81,83]],27:[[0,4],[21,23]]},31:{0:[0],1:[0,1,[3,10],[12,20]],2:[0,30]},32:{0:[0],1:[[0,7],11,[13,18],24,25],2:[[0,6],11,81,82],3:[[0,5],11,12,[21,24],81,82],4:[[0,2],4,5,11,12,81,82],5:[[0,9],[81,85]],6:[[0,2],11,12,21,23,[81,84]],7:[0,1,3,5,6,[21,24]],8:[[0,4],11,26,[29,31]],9:[[0,3],[21,25],28,81,82],10:[[0,3],11,12,23,81,84,88],11:[[0,2],11,12,[81,83]],12:[[0,4],[81,84]],13:[[0,2],11,[21,24]]},33:{0:[0],1:[[0,6],[8,10],22,27,82,83,85],2:[0,1,[3,6],11,12,25,26,[81,83]],3:[[0,4],22,24,[26,29],81,82],4:[[0,2],11,21,24,[81,83]],5:[[0,3],[21,23]],6:[[0,2],21,24,[81,83]],7:[[0,3],23,26,27,[81,84]],8:[[0,3],22,24,25,81],9:[[0,3],21,22],10:[[0,4],[21,24],81,82],11:[[0,2],[21,27],81]},34:{0:[0],1:[[0,4],11,[21,24],81],2:[[0,4],7,8,[21,23],25],3:[[0,4],11,[21,23]],4:[[0,6],21],5:[[0,4],6,[21,23]],6:[[0,4],21],7:[[0,3],11,21],8:[[0,3],11,[22,28],81],10:[[0,4],[21,24]],11:[[0,3],22,[24,26],81,82],12:[[0,4],21,22,25,26,82],13:[[0,2],[21,24]],14:[[0,2],[21,24]],15:[[0,3],[21,25]],16:[[0,2],[21,23]],17:[[0,2],[21,23]],18:[[0,2],[21,25],81]},35:{0:[0],1:[[0,5],11,[21,25],28,81,82],2:[[0,6],[11,13]],3:[[0,5],22],4:[[0,3],21,[23,30],81],5:[[0,5],21,[24,27],[81,83]],6:[[0,3],[22,29],81],7:[[0,2],[21,25],[81,84]],8:[[0,2],[21,25],81],9:[[0,2],[21,26],81,82]},36:{0:[0],1:[[0,5],11,[21,24]],2:[[0,3],22,81],3:[[0,2],13,[21,23]],4:[[0,3],21,[23,30],81,82],5:[[0,2],21],6:[[0,2],22,81],7:[[0,2],[21,35],81,82],8:[[0,3],[21,30],81],9:[[0,2],[21,26],[81,83]],10:[[0,2],[21,30]],11:[[0,2],[21,30],81]},37:{0:[0],1:[[0,5],12,13,[24,26],81],2:[[0,3],5,[11,14],[81,85]],3:[[0,6],[21,23]],4:[[0,6],81],5:[[0,3],[21,23]],6:[[0,2],[11,13],34,[81,87]],7:[[0,5],24,25,[81,86]],8:[[0,2],11,[26,32],[81,83]],9:[[0,3],11,21,23,82,83],10:[[0,2],[81,83]],11:[[0,3],21,22],12:[[0,3]],13:[[0,2],11,12,[21,29]],14:[[0,2],[21,28],81,82],15:[[0,2],[21,26],81],16:[[0,2],[21,26]],17:[[0,2],[21,28]]},41:{0:[0],1:[[0,6],8,22,[81,85]],2:[[0,5],11,[21,25]],3:[[0,7],11,[22,29],81],4:[[0,4],11,[21,23],25,81,82],5:[[0,3],5,6,22,23,26,27,81],6:[[0,3],11,21,22],7:[[0,4],11,21,[24,28],81,82],8:[[0,4],11,[21,23],25,[81,83]],9:[[0,2],22,23,[26,28]],10:[[0,2],[23,25],81,82],11:[[0,4],[21,23]],12:[[0,2],21,22,24,81,82],13:[[0,3],[21,30],81],14:[[0,3],[21,26],81],15:[[0,3],[21,28]],16:[[0,2],[21,28],81],17:[[0,2],[21,29]],90:[0,1]},42:{0:[0],1:[[0,7],[11,17]],2:[[0,5],22,81],3:[[0,3],[21,25],81],5:[[0,6],[25,29],[81,83]],6:[[0,2],6,7,[24,26],[82,84]],7:[[0,4]],8:[[0,2],4,21,22,81],9:[[0,2],[21,23],81,82,84],10:[[0,3],[22,24],81,83,87],11:[[0,2],[21,27],81,82],12:[[0,2],[21,24],81],13:[[0,3],21,81],28:[[0,2],22,23,[25,28]],90:[0,[4,6],21]},43:{0:[0],1:[[0,5],11,12,21,22,24,81],2:[[0,4],11,21,[23,25],81],3:[[0,2],4,21,81,82],4:[0,1,[5,8],12,[21,24],26,81,82],5:[[0,3],11,[21,25],[27,29],81],6:[[0,3],11,21,23,24,26,81,82],7:[[0,3],[21,26],81],8:[[0,2],11,21,22],9:[[0,3],[21,23],81],10:[[0,3],[21,28],81],11:[[0,3],[21,29]],12:[[0,2],[21,30],81],13:[[0,2],21,22,81,82],31:[0,1,[22,27],30]},44:{0:[0],1:[[0,7],[11,16],83,84],2:[[0,5],21,22,24,29,32,33,81,82],3:[0,1,[3,8]],4:[[0,4]],5:[0,1,[6,15],23,82,83],6:[0,1,[4,8]],7:[0,1,[3,5],81,[83,85]],8:[[0,4],11,23,25,[81,83]],9:[[0,3],23,[81,83]],12:[[0,3],[23,26],83,84],13:[[0,3],[22,24],81],14:[[0,2],[21,24],26,27,81],15:[[0,2],21,23,81],16:[[0,2],[21,25]],17:[[0,2],21,23,81],18:[[0,3],21,23,[25,27],81,82],19:[0],20:[0],51:[[0,3],21,22],52:[[0,3],21,22,24,81],53:[[0,2],[21,23],81]},45:{0:[0],1:[[0,9],[21,27]],2:[[0,5],[21,26]],3:[[0,5],11,12,[21,32]],4:[0,1,[3,6],11,[21,23],81],5:[[0,3],12,21],6:[[0,3],21,81],7:[[0,3],21,22],8:[[0,4],21,81],9:[[0,3],[21,24],81],10:[[0,2],[21,31]],11:[[0,2],[21,23]],12:[[0,2],[21,29],81],13:[[0,2],[21,24],81],14:[[0,2],[21,25],81]},46:{0:[0],1:[0,1,[5,8]],2:[0,1],3:[0,[21,23]],90:[[0,3],[5,7],[21,39]]},50:{0:[0],1:[[0,19]],2:[0,[22,38],[40,43]],3:[0,[81,84]]},51:{0:[0],1:[0,1,[4,8],[12,15],[21,24],29,31,32,[81,84]],3:[[0,4],11,21,22],4:[[0,3],11,21,22],5:[[0,4],21,22,24,25],6:[0,1,3,23,26,[81,83]],7:[0,1,3,4,[22,27],81],8:[[0,2],11,12,[21,24]],9:[[0,4],[21,23]],10:[[0,2],11,24,25,28],11:[[0,2],[11,13],23,24,26,29,32,33,81],13:[[0,4],[21,25],81],14:[[0,2],[21,25]],15:[[0,3],[21,29]],16:[[0,3],[21,23],81],17:[[0,3],[21,25],81],18:[[0,3],[21,27]],19:[[0,3],[21,23]],20:[[0,2],21,22,81],32:[0,[21,33]],33:[0,[21,38]],34:[0,1,[22,37]]},52:{0:[0],1:[[0,3],[11,15],[21,23],81],2:[0,1,3,21,22],3:[[0,3],[21,30],81,82],4:[[0,2],[21,25]],5:[[0,2],[21,27]],6:[[0,3],[21,28]],22:[0,1,[22,30]],23:[0,1,[22,28]],24:[0,1,[22,28]],26:[0,1,[22,36]],27:[[0,2],22,23,[25,32]]},53:{0:[0],1:[[0,3],[11,14],21,22,[24,29],81],3:[[0,2],[21,26],28,81],4:[[0,2],[21,28]],5:[[0,2],[21,24]],6:[[0,2],[21,30]],7:[[0,2],[21,24]],8:[[0,2],[21,29]],9:[[0,2],[21,27]],23:[0,1,[22,29],31],25:[[0,4],[22,32]],26:[0,1,[21,28]],27:[0,1,[22,30]],28:[0,1,22,23],29:[0,1,[22,32]],31:[0,2,3,[22,24]],34:[0,[21,23]],33:[0,21,[23,25]],35:[0,[21,28]]},54:{0:[0],1:[[0,2],[21,27]],21:[0,[21,29],32,33],22:[0,[21,29],[31,33]],23:[0,1,[22,38]],24:[0,[21,31]],25:[0,[21,27]],26:[0,[21,27]]},61:{0:[0],1:[[0,4],[11,16],22,[24,26]],2:[[0,4],22],3:[[0,4],[21,24],[26,31]],4:[[0,4],[22,31],81],5:[[0,2],[21,28],81,82],6:[[0,2],[21,32]],7:[[0,2],[21,30]],8:[[0,2],[21,31]],9:[[0,2],[21,29]],10:[[0,2],[21,26]]},62:{0:[0],1:[[0,5],11,[21,23]],2:[0,1],3:[[0,2],21],4:[[0,3],[21,23]],5:[[0,3],[21,25]],6:[[0,2],[21,23]],7:[[0,2],[21,25]],8:[[0,2],[21,26]],9:[[0,2],[21,24],81,82],10:[[0,2],[21,27]],11:[[0,2],[21,26]],12:[[0,2],[21,28]],24:[0,21,[24,29]],26:[0,21,[23,30]],29:[0,1,[21,27]],30:[0,1,[21,27]]},63:{0:[0],1:[[0,5],[21,23]],2:[0,2,[21,25]],21:[0,[21,23],[26,28]],22:[0,[21,24]],23:[0,[21,24]],25:[0,[21,25]],26:[0,[21,26]],27:[0,1,[21,26]],28:[[0,2],[21,23]]},64:{0:[0],1:[0,1,[4,6],21,22,81],2:[[0,3],5,[21,23]],3:[[0,3],[21,24],81],4:[[0,2],[21,25]],5:[[0,2],21,22]},65:{0:[0],1:[[0,9],21],2:[[0,5]],21:[0,1,22,23],22:[0,1,22,23],23:[[0,3],[23,25],27,28],28:[0,1,[22,29]],29:[0,1,[22,29]],30:[0,1,[22,24]],31:[0,1,[21,31]],32:[0,1,[21,27]],40:[0,2,3,[21,28]],42:[[0,2],21,[23,26]],43:[0,1,[21,26]],90:[[0,4]],27:[[0,2],22,23]},71:{0:[0]},81:{0:[0]},82:{0:[0]}},d=parseInt(b.substr(0,2),10),e=parseInt(b.substr(2,2),10),f=parseInt(b.substr(4,2),10);if(!c[d]||!c[d][e])return!1;for(var g=!1,h=c[d][e],i=0;i<h.length;i++)if(a.isArray(h[i])&&h[i][0]<=f&&f<=h[i][1]||!a.isArray(h[i])&&f===h[i]){g=!0;break}if(!g)return!1;var j;j=18===b.length?b.substr(6,8):"19"+b.substr(6,6);var k=parseInt(j.substr(0,4),10),l=parseInt(j.substr(4,2),10),m=parseInt(j.substr(6,2),10);if(!FormValidation.Helper.date(k,l,m))return!1;if(18===b.length){var n=0,o=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];for(i=0;17>i;i++)n+=parseInt(b.charAt(i),10)*o[i];n=(12-n%11)%11;var p="X"!==b.charAt(17).toUpperCase()?parseInt(b.charAt(17),10):10;return p===n}return!0},_cz:function(a){if(!/^\d{9,10}$/.test(a))return!1;var b=1900+parseInt(a.substr(0,2),10),c=parseInt(a.substr(2,2),10)%50%20,d=parseInt(a.substr(4,2),10);if(9===a.length){if(b>=1980&&(b-=100),b>1953)return!1}else 1954>b&&(b+=100);if(!FormValidation.Helper.date(b,c,d))return!1;if(10===a.length){var e=parseInt(a.substr(0,9),10)%11;return 1985>b&&(e%=10),e+""===a.substr(9,1)}return!0},_dk:function(a){if(!/^[0-9]{6}[-]{0,1}[0-9]{4}$/.test(a))return!1;a=a.replace(/-/g,"");var b=parseInt(a.substr(0,2),10),c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10);switch(!0){case-1!=="5678".indexOf(a.charAt(6))&&d>=58:d+=1800;break;case-1!=="0123".indexOf(a.charAt(6)):case-1!=="49".indexOf(a.charAt(6))&&d>=37:d+=1900;break;default:d+=2e3}return FormValidation.Helper.date(d,c,b)},_ee:function(a){return this._lt(a)},_es:function(a){var b=/^[0-9]{8}[-]{0,1}[A-HJ-NP-TV-Z]$/.test(a),c=/^[XYZ][-]{0,1}[0-9]{7}[-]{0,1}[A-HJ-NP-TV-Z]$/.test(a),d=/^[A-HNPQS][-]{0,1}[0-9]{7}[-]{0,1}[0-9A-J]$/.test(a);if(!b&&!c&&!d)return!1;a=a.replace(/-/g,"");var e;if(b||c){var f="XYZ".indexOf(a.charAt(0));return-1!==f&&(a=f+a.substr(1)+""),e=parseInt(a.substr(0,8),10),e="TRWAGMYFPDXBNJZSQVHLCKE"[e%23],e===a.substr(8,1)}e=a.substr(1,7);for(var g=a[0],h=a.substr(-1),i=0,j=0;j<e.length;j++)if(j%2!==0)i+=parseInt(e[j],10);else{var k=""+2*parseInt(e[j],10);i+=parseInt(k[0],10),2===k.length&&(i+=parseInt(k[1],10))}var l=i-10*Math.floor(i/10);return 0!==l&&(l=10-l),-1!=="KQS".indexOf(g)?h==="JABCDEFGHI"[l]:-1!=="ABEH".indexOf(g)?h===""+l:h===""+l||h==="JABCDEFGHI"[l]},_fi:function(a){if(!/^[0-9]{6}[-+A][0-9]{3}[0-9ABCDEFHJKLMNPRSTUVWXY]$/.test(a))return!1;var b=parseInt(a.substr(0,2),10),c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10),e={"+":1800,"-":1900,A:2e3};if(d=e[a.charAt(6)]+d,!FormValidation.Helper.date(d,c,b))return!1;var f=parseInt(a.substr(7,3),10);if(2>f)return!1;var g=a.substr(0,6)+a.substr(7,3)+"";return g=parseInt(g,10),"0123456789ABCDEFHJKLMNPRSTUVWXY".charAt(g%31)===a.charAt(10)},_hr:function(a){return/^[0-9]{11}$/.test(a)?FormValidation.Helper.mod11And10(a):!1},_ie:function(a){if(!/^\d{7}[A-W][AHWTX]?$/.test(a))return!1;var b=function(a){for(;a.length<7;)a="0"+a;for(var b="WABCDEFGHIJKLMNOPQRSTUV",c=0,d=0;7>d;d++)c+=parseInt(a.charAt(d),10)*(8-d);return c+=9*b.indexOf(a.substr(7)),b[c%23]};return 9!==a.length||"A"!==a.charAt(8)&&"H"!==a.charAt(8)?a.charAt(7)===b(a.substr(0,7)):a.charAt(7)===b(a.substr(0,7)+a.substr(8)+"")},_is:function(a){if(!/^[0-9]{6}[-]{0,1}[0-9]{4}$/.test(a))return!1;a=a.replace(/-/g,"");var b=parseInt(a.substr(0,2),10),c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10),e=parseInt(a.charAt(9),10);if(d=9===e?1900+d:100*(20+e)+d,!FormValidation.Helper.date(d,c,b,!0))return!1;for(var f=0,g=[3,2,7,6,5,4,3,2],h=0;8>h;h++)f+=parseInt(a.charAt(h),10)*g[h];return f=11-f%11,f+""===a.charAt(8)},_lt:function(a){if(!/^[0-9]{11}$/.test(a))return!1;var b=parseInt(a.charAt(0),10),c=parseInt(a.substr(1,2),10),d=parseInt(a.substr(3,2),10),e=parseInt(a.substr(5,2),10),f=b%2===0?17+b/2:17+(b+1)/2;if(c=100*f+c,!FormValidation.Helper.date(c,d,e,!0))return!1;for(var g=0,h=[1,2,3,4,5,6,7,8,9,1],i=0;10>i;i++)g+=parseInt(a.charAt(i),10)*h[i];if(g%=11,10!==g)return g+""===a.charAt(10);for(g=0,h=[3,4,5,6,7,8,9,1,2,3],i=0;10>i;i++)g+=parseInt(a.charAt(i),10)*h[i];return g%=11,10===g&&(g=0),g+""===a.charAt(10)},_lv:function(a){if(!/^[0-9]{6}[-]{0,1}[0-9]{5}$/.test(a))return!1;a=a.replace(/\D/g,"");var b=parseInt(a.substr(0,2),10),c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10);if(d=d+1800+100*parseInt(a.charAt(6),10),!FormValidation.Helper.date(d,c,b,!0))return!1;for(var e=0,f=[10,5,8,4,2,1,6,3,7,9],g=0;10>g;g++)e+=parseInt(a.charAt(g),10)*f[g];return e=(e+1)%11%10,e+""===a.charAt(10)},_nl:function(a){for(;a.length<9;)a="0"+a;if(!/^[0-9]{4}[.]{0,1}[0-9]{2}[.]{0,1}[0-9]{3}$/.test(a))return!1;if(a=a.replace(/\./g,""),0===parseInt(a,10))return!1;for(var b=0,c=a.length,d=0;c-1>d;d++)b+=(9-d)*parseInt(a.charAt(d),10);return b%=11,10===b&&(b=0),b+""===a.charAt(c-1)},_pl:function(a){if(!/^[0-9]{11}$/.test(a))return!1;for(var b=0,c=a.length,d=[1,3,7,9,1,3,7,9,1,3,7],e=0;c-1>e;e++)b+=d[e]*parseInt(a.charAt(e),10);return b%=10,0===b&&(b=10),b=10-b,b+""===a.charAt(c-1)},_ro:function(a){if(!/^[0-9]{13}$/.test(a))return!1;var b=parseInt(a.charAt(0),10);if(0===b||7===b||8===b)return!1;var c=parseInt(a.substr(1,2),10),d=parseInt(a.substr(3,2),10),e=parseInt(a.substr(5,2),10),f={1:1900,2:1900,3:1800,4:1800,5:2e3,6:2e3};if(e>31&&d>12)return!1;if(9!==b&&(c=f[b+""]+c,!FormValidation.Helper.date(c,d,e)))return!1;for(var g=0,h=[2,7,9,1,4,6,3,5,8,2,7,9],i=a.length,j=0;i-1>j;j++)g+=parseInt(a.charAt(j),10)*h[j];return g%=11,10===g&&(g=1),g+""===a.charAt(i-1)},_se:function(a){if(!/^[0-9]{10}$/.test(a)&&!/^[0-9]{6}[-|+][0-9]{4}$/.test(a))return!1;a=a.replace(/[^0-9]/g,"");var b=parseInt(a.substr(0,2),10)+1900,c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10);return FormValidation.Helper.date(b,c,d)?FormValidation.Helper.luhn(a):!1},_sk:function(a){return this._cz(a)},_sm:function(a){return/^\d{5}$/.test(a)},_th:function(a){if(13!==a.length)return!1;for(var b=0,c=0;12>c;c++)b+=parseInt(a.charAt(c),10)*(13-c);return(11-b%11)%10===parseInt(a.charAt(12),10)},_za:function(a){if(!/^[0-9]{10}[0|1][8|9][0-9]$/.test(a))return!1;var b=parseInt(a.substr(0,2),10),c=(new Date).getFullYear()%100,d=parseInt(a.substr(2,2),10),e=parseInt(a.substr(4,2),10);return b=b>=c?b+1900:b+2e3,FormValidation.Helper.date(b,d,e)?FormValidation.Helper.luhn(a):!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{identical:{"default":"Please enter the same value"}}}),FormValidation.Validator.identical={html5Attributes:{message:"message",field:"field"},init:function(a,b,c){var d=a.getFieldElements(c.field);a.onLiveChange(d,"live_identical",function(){var c=a.getStatus(b,"identical");c!==a.STATUS_NOT_VALIDATED&&a.revalidateField(b)})},destroy:function(a,b,c){var d=a.getFieldElements(c.field);a.offLiveChange(d,"live_identical")},validate:function(a,b,c){var d=a.getFieldValue(b,"identical"),e=a.getFieldElements(c.field);if(null===e||0===e.length)return!0;var f=a.getFieldValue(e,"identical");return d===f?(a.updateStatus(e,a.STATUS_VALID,"identical"),!0):!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{imei:{"default":"Please enter a valid IMEI number"}}}),FormValidation.Validator.imei={validate:function(a,b){var c=a.getFieldValue(b,"imei");if(""===c)return!0;switch(!0){case/^\d{15}$/.test(c):case/^\d{2}-\d{6}-\d{6}-\d{1}$/.test(c):case/^\d{2}\s\d{6}\s\d{6}\s\d{1}$/.test(c):return c=c.replace(/[^0-9]/g,""),FormValidation.Helper.luhn(c);case/^\d{14}$/.test(c):case/^\d{16}$/.test(c):case/^\d{2}-\d{6}-\d{6}(|-\d{2})$/.test(c):case/^\d{2}\s\d{6}\s\d{6}(|\s\d{2})$/.test(c):return!0;default:return!1}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{imo:{"default":"Please enter a valid IMO number"}}}),FormValidation.Validator.imo={validate:function(a,b){var c=a.getFieldValue(b,"imo");if(""===c)return!0;if(!/^IMO \d{7}$/i.test(c))return!1;for(var d=0,e=c.replace(/^.*(\d{7})$/,"$1"),f=6;f>=1;f--)d+=e.slice(6-f,-f)*(f+1);return d%10===parseInt(e.charAt(6),10)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{integer:{"default":"Please enter a valid number"}}}),FormValidation.Validator.integer={enableByHtml5:function(a){return"number"===a.attr("type")&&(void 0===a.attr("step")||a.attr("step")%1===0)},validate:function(a,b){if(this.enableByHtml5(b)&&b.get(0).validity&&b.get(0).validity.badInput===!0)return!1;var c=a.getFieldValue(b,"integer");return""===c?!0:/^(?:-?(?:0|[1-9][0-9]*))$/.test(c)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{ip:{"default":"Please enter a valid IP address",ipv4:"Please enter a valid IPv4 address",ipv6:"Please enter a valid IPv6 address"}}}),FormValidation.Validator.ip={html5Attributes:{message:"message",ipv4:"ipv4",ipv6:"ipv6"},validate:function(b,c,d){var e=b.getFieldValue(c,"ip");if(""===e)return!0;d=a.extend({},{ipv4:!0,ipv6:!0},d);var f,g=b.getLocale(),h=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,i=/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,j=!1;switch(!0){case d.ipv4&&!d.ipv6:j=h.test(e),f=d.message||FormValidation.I18n[g].ip.ipv4;break;case!d.ipv4&&d.ipv6:j=i.test(e),f=d.message||FormValidation.I18n[g].ip.ipv6;break;case d.ipv4&&d.ipv6:default:j=h.test(e)||i.test(e),f=d.message||FormValidation.I18n[g].ip["default"]}return{valid:j,message:f}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{isbn:{"default":"Please enter a valid ISBN number"}}}),FormValidation.Validator.isbn={validate:function(a,b){var c=a.getFieldValue(b,"isbn");if(""===c)return!0;var d;switch(!0){case/^\d{9}[\dX]$/.test(c):case 13===c.length&&/^(\d+)-(\d+)-(\d+)-([\dX])$/.test(c):case 13===c.length&&/^(\d+)\s(\d+)\s(\d+)\s([\dX])$/.test(c):d="ISBN10";break;case/^(978|979)\d{9}[\dX]$/.test(c):case 17===c.length&&/^(978|979)-(\d+)-(\d+)-(\d+)-([\dX])$/.test(c):case 17===c.length&&/^(978|979)\s(\d+)\s(\d+)\s(\d+)\s([\dX])$/.test(c):d="ISBN13";break;default:return!1}c=c.replace(/[^0-9X]/gi,"");var e,f,g=c.split(""),h=g.length,i=0;switch(d){case"ISBN10":for(i=0,e=0;h-1>e;e++)i+=parseInt(g[e],10)*(10-e);return f=11-i%11,11===f?f=0:10===f&&(f="X"),f+""===g[h-1];case"ISBN13":for(i=0,e=0;h-1>e;e++)i+=e%2===0?parseInt(g[e],10):3*parseInt(g[e],10);return f=10-i%10,10===f&&(f="0"),f+""===g[h-1];default:return!1}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{isin:{"default":"Please enter a valid ISIN number"}}}),FormValidation.Validator.isin={COUNTRY_CODES:"AF|AX|AL|DZ|AS|AD|AO|AI|AQ|AG|AR|AM|AW|AU|AT|AZ|BS|BH|BD|BB|BY|BE|BZ|BJ|BM|BT|BO|BQ|BA|BW|BV|BR|IO|BN|BG|BF|BI|KH|CM|CA|CV|KY|CF|TD|CL|CN|CX|CC|CO|KM|CG|CD|CK|CR|CI|HR|CU|CW|CY|CZ|DK|DJ|DM|DO|EC|EG|SV|GQ|ER|EE|ET|FK|FO|FJ|FI|FR|GF|PF|TF|GA|GM|GE|DE|GH|GI|GR|GL|GD|GP|GU|GT|GG|GN|GW|GY|HT|HM|VA|HN|HK|HU|IS|IN|ID|IR|IQ|IE|IM|IL|IT|JM|JP|JE|JO|KZ|KE|KI|KP|KR|KW|KG|LA|LV|LB|LS|LR|LY|LI|LT|LU|MO|MK|MG|MW|MY|MV|ML|MT|MH|MQ|MR|MU|YT|MX|FM|MD|MC|MN|ME|MS|MA|MZ|MM|NA|NR|NP|NL|NC|NZ|NI|NE|NG|NU|NF|MP|NO|OM|PK|PW|PS|PA|PG|PY|PE|PH|PN|PL|PT|PR|QA|RE|RO|RU|RW|BL|SH|KN|LC|MF|PM|VC|WS|SM|ST|SA|SN|RS|SC|SL|SG|SX|SK|SI|SB|SO|ZA|GS|SS|ES|LK|SD|SR|SJ|SZ|SE|CH|SY|TW|TJ|TZ|TH|TL|TG|TK|TO|TT|TN|TR|TM|TC|TV|UG|UA|AE|GB|US|UM|UY|UZ|VU|VE|VN|VG|VI|WF|EH|YE|ZM|ZW",validate:function(a,b){var c=a.getFieldValue(b,"isin");if(""===c)return!0;c=c.toUpperCase();var d=new RegExp("^("+this.COUNTRY_CODES+")[0-9A-Z]{10}$");if(!d.test(c))return!1;for(var e="",f=c.length,g=0;f-1>g;g++){var h=c.charCodeAt(g);e+=h>57?(h-55).toString():c.charAt(g)}var i="",j=e.length,k=j%2!==0?0:1;for(g=0;j>g;g++)i+=parseInt(e[g],10)*(g%2===k?2:1)+"";var l=0;for(g=0;g<i.length;g++)l+=parseInt(i.charAt(g),10);return l=(10-l%10)%10,l+""===c.charAt(f-1)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{ismn:{"default":"Please enter a valid ISMN number"}}}),FormValidation.Validator.ismn={validate:function(a,b){var c=a.getFieldValue(b,"ismn");if(""===c)return!0;var d;switch(!0){case/^M\d{9}$/.test(c):case/^M-\d{4}-\d{4}-\d{1}$/.test(c):case/^M\s\d{4}\s\d{4}\s\d{1}$/.test(c):d="ISMN10";break;case/^9790\d{9}$/.test(c):case/^979-0-\d{4}-\d{4}-\d{1}$/.test(c):case/^979\s0\s\d{4}\s\d{4}\s\d{1}$/.test(c):d="ISMN13";break;default:return!1}"ISMN10"===d&&(c="9790"+c.substr(1)),c=c.replace(/[^0-9]/gi,"");for(var e=c.length,f=0,g=[1,3],h=0;e-1>h;h++)f+=parseInt(c.charAt(h),10)*g[h%2];return f=10-f%10,f+""===c.charAt(e-1)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{issn:{"default":"Please enter a valid ISSN number"}}}),FormValidation.Validator.issn={validate:function(a,b){var c=a.getFieldValue(b,"issn");if(""===c)return!0;if(!/^\d{4}\-\d{3}[\dX]$/.test(c))return!1;c=c.replace(/[^0-9X]/gi,"");var d=c.split(""),e=d.length,f=0;"X"===d[7]&&(d[7]=10);for(var g=0;e>g;g++)f+=parseInt(d[g],10)*(8-g);return f%11===0}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{lessThan:{"default":"Please enter a value less than or equal to %s",notInclusive:"Please enter a value less than %s"}}}),FormValidation.Validator.lessThan={html5Attributes:{message:"message",value:"value",inclusive:"inclusive"},enableByHtml5:function(a){var b=a.attr("type"),c=a.attr("max");return c&&"date"!==b?{value:c}:!1},validate:function(b,c,d){var e=b.getFieldValue(c,"lessThan");if(""===e)return!0;if(e=this._format(e),!a.isNumeric(e))return!1;var f=b.getLocale(),g=a.isNumeric(d.value)?d.value:b.getDynamicOption(c,d.value),h=this._format(g);return e=parseFloat(e),d.inclusive===!0||void 0===d.inclusive?{valid:h>=e,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].lessThan["default"],g)}:{valid:h>e,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].lessThan.notInclusive,g)}},_format:function(a){return(a+"").replace(",",".")}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{mac:{"default":"Please enter a valid MAC address"}}}),FormValidation.Validator.mac={validate:function(a,b){var c=a.getFieldValue(b,"mac");return""===c?!0:/^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/.test(c)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{meid:{"default":"Please enter a valid MEID number"}}}),FormValidation.Validator.meid={validate:function(a,b){var c=a.getFieldValue(b,"meid");if(""===c)return!0;switch(!0){case/^[0-9A-F]{15}$/i.test(c):case/^[0-9A-F]{2}[- ][0-9A-F]{6}[- ][0-9A-F]{6}[- ][0-9A-F]$/i.test(c):case/^\d{19}$/.test(c):case/^\d{5}[- ]\d{5}[- ]\d{4}[- ]\d{4}[- ]\d$/.test(c):var d=c.charAt(c.length-1);if(c=c.replace(/[- ]/g,""),c.match(/^\d*$/i))return FormValidation.Helper.luhn(c);c=c.slice(0,-1);for(var e="",f=1;13>=f;f+=2)e+=(2*parseInt(c.charAt(f),16)).toString(16);var g=0;for(f=0;f<e.length;f++)g+=parseInt(e.charAt(f),16);return g%10===0?"0"===d:d===(2*(10*Math.floor((g+10)/10)-g)).toString(16);case/^[0-9A-F]{14}$/i.test(c):case/^[0-9A-F]{2}[- ][0-9A-F]{6}[- ][0-9A-F]{6}$/i.test(c):case/^\d{18}$/.test(c):case/^\d{5}[- ]\d{5}[- ]\d{4}[- ]\d{4}$/.test(c):return!0;default:return!1}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{notEmpty:{"default":"Please enter a value"}}}),FormValidation.Validator.notEmpty={enableByHtml5:function(a){var b=a.attr("required")+"";return"required"===b||"true"===b},validate:function(b,c){var d=c.attr("type");if("radio"===d||"checkbox"===d){var e=b.getNamespace();return b.getFieldElements(c.attr("data-"+e+"-field")).filter(":checked").length>0}if("number"===d&&c.get(0).validity&&c.get(0).validity.badInput===!0)return!0;var f=b.getFieldValue(c,"notEmpty");return""!==a.trim(f)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{numeric:{"default":"Please enter a valid float number"}}}),FormValidation.Validator.numeric={html5Attributes:{message:"message",separator:"separator"},enableByHtml5:function(a){return"number"===a.attr("type")&&void 0!==a.attr("step")&&a.attr("step")%1!==0},validate:function(a,b,c){if(this.enableByHtml5(b)&&b.get(0).validity&&b.get(0).validity.badInput===!0)return!1;var d=a.getFieldValue(b,"numeric");if(""===d)return!0;var e=c.separator||".";return"."!==e&&(d=d.replace(e,".")),!isNaN(parseFloat(d))&&isFinite(d)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{phone:{"default":"Please enter a valid phone number",country:"Please enter a valid phone number in %s",countries:{AE:"United Arab Emirates",BG:"Bulgaria",BR:"Brazil",CN:"China",CZ:"Czech Republic",DE:"Germany",DK:"Denmark",ES:"Spain",FR:"France",GB:"United Kingdom",IN:"India",MA:"Morocco",NL:"Netherlands",PK:"Pakistan",RO:"Romania",RU:"Russia",SK:"Slovakia",TH:"Thailand",US:"USA",VE:"Venezuela"}}}}),FormValidation.Validator.phone={html5Attributes:{message:"message",country:"country"},COUNTRY_CODES:["AE","BG","BR","CN","CZ","DE","DK","ES","FR","GB","IN","MA","NL","PK","RO","RU","SK","TH","US","VE"],validate:function(b,c,d){var e=b.getFieldValue(c,"phone");if(""===e)return!0;var f=b.getLocale(),g=d.country;if(("string"!=typeof g||-1===a.inArray(g,this.COUNTRY_CODES))&&(g=b.getDynamicOption(c,g)),!g||-1===a.inArray(g.toUpperCase(),this.COUNTRY_CODES))return!0;var h=!0;switch(g.toUpperCase()){case"AE":e=a.trim(e),h=/^(((\+|00)?971[\s\.-]?(\(0\)[\s\.-]?)?|0)(\(5(0|2|5|6)\)|5(0|2|5|6)|2|3|4|6|7|9)|60)([\s\.-]?[0-9]){7}$/.test(e);break;case"BG":e=e.replace(/\+|\s|-|\/|\(|\)/gi,""),h=/^(0|359|00)(((700|900)[0-9]{5}|((800)[0-9]{5}|(800)[0-9]{4}))|(87|88|89)([0-9]{7})|((2[0-9]{7})|(([3-9][0-9])(([0-9]{6})|([0-9]{5})))))$/.test(e);break;case"BR":e=a.trim(e),h=/^(([\d]{4}[-.\s]{1}[\d]{2,3}[-.\s]{1}[\d]{2}[-.\s]{1}[\d]{2})|([\d]{4}[-.\s]{1}[\d]{3}[-.\s]{1}[\d]{4})|((\(?\+?[0-9]{2}\)?\s?)?(\(?\d{2}\)?\s?)?\d{4,5}[-.\s]?\d{4}))$/.test(e);break;case"CN":e=a.trim(e),h=/^((00|\+)?(86(?:-| )))?((\d{11})|(\d{3}[- ]{1}\d{4}[- ]{1}\d{4})|((\d{2,4}[- ]){1}(\d{7,8}|(\d{3,4}[- ]{1}\d{4}))([- ]{1}\d{1,4})?))$/.test(e);break;case"CZ":h=/^(((00)([- ]?)|\+)(420)([- ]?))?((\d{3})([- ]?)){2}(\d{3})$/.test(e);break;case"DE":e=a.trim(e),h=/^(((((((00|\+)49[ \-/]?)|0)[1-9][0-9]{1,4})[ \-/]?)|((((00|\+)49\()|\(0)[1-9][0-9]{1,4}\)[ \-/]?))[0-9]{1,7}([ \-/]?[0-9]{1,5})?)$/.test(e);break;case"DK":e=a.trim(e),h=/^(\+45|0045|\(45\))?\s?[2-9](\s?\d){7}$/.test(e);break;case"ES":e=a.trim(e),h=/^(?:(?:(?:\+|00)34\D?))?(?:5|6|7|8|9)(?:\d\D?){8}$/.test(e);break;case"FR":e=a.trim(e),h=/^(?:(?:(?:\+|00)33[ ]?(?:\(0\)[ ]?)?)|0){1}[1-9]{1}([ .-]?)(?:\d{2}\1?){3}\d{2}$/.test(e);break;case"GB":e=a.trim(e),h=/^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$/.test(e);break;case"IN":e=a.trim(e),h=/((\+?)((0[ -]+)*|(91 )*)(\d{12}|\d{10}))|\d{5}([- ]*)\d{6}/.test(e);break;case"MA":e=a.trim(e),h=/^(?:(?:(?:\+|00)212[\s]?(?:[\s]?\(0\)[\s]?)?)|0){1}(?:5[\s.-]?[2-3]|6[\s.-]?[13-9]){1}[0-9]{1}(?:[\s.-]?\d{2}){3}$/.test(e);break;case"NL":e=a.trim(e),h=/^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9])((\s|\s?-\s?)?[0-9])((\s|\s?-\s?)?[0-9])\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]\s?[0-9]$/gm.test(e);break;case"PK":e=a.trim(e),h=/^0?3[0-9]{2}[0-9]{7}$/.test(e);break;case"RO":h=/^(\+4|)?(07[0-8]{1}[0-9]{1}|02[0-9]{2}|03[0-9]{2}){1}?(\s|\.|\-)?([0-9]{3}(\s|\.|\-|)){2}$/g.test(e);break;case"RU":h=/^((8|\+7|007)[\-\.\/ ]?)?([\(\/\.]?\d{3}[\)\/\.]?[\-\.\/ ]?)?[\d\-\.\/ ]{7,10}$/g.test(e);break;case"SK":h=/^(((00)([- ]?)|\+)(421)([- ]?))?((\d{3})([- ]?)){2}(\d{3})$/.test(e);break;case"TH":h=/^0\(?([6|8-9]{2})*-([0-9]{3})*-([0-9]{4})$/.test(e);break;case"VE":e=a.trim(e),h=/^0(?:2(?:12|4[0-9]|5[1-9]|6[0-9]|7[0-8]|8[1-35-8]|9[1-5]|3[45789])|4(?:1[246]|2[46]))\d{7}$/.test(e);break;case"US":default:h=/^(?:(1\-?)|(\+1 ?))?\(?(\d{3})[\)\-\.]?(\d{3})[\-\.]?(\d{4})$/.test(e)}return{valid:h,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].phone.country,FormValidation.I18n[f].phone.countries[g])}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{promise:{"default":"Please enter a valid value"}}}),FormValidation.Validator.promise={html5Attributes:{message:"message",promise:"promise"},validate:function(b,c,d){var e=b.getFieldValue(c,"promise"),f=new a.Deferred,g=FormValidation.Helper.call(d.promise,[e,b,c]);return g.done(function(a){
f.resolve(c,"promise",a)}).fail(function(a){a=a||{},a.valid=!1,f.resolve(c,"promise",a)}),f}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{regexp:{"default":"Please enter a value matching the pattern"}}}),FormValidation.Validator.regexp={html5Attributes:{message:"message",regexp:"regexp"},enableByHtml5:function(a){var b=a.attr("pattern");return b?{regexp:b}:!1},validate:function(a,b,c){var d=a.getFieldValue(b,"regexp");if(""===d)return!0;var e="string"==typeof c.regexp?new RegExp(c.regexp):c.regexp;return e.test(d)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{remote:{"default":"Please enter a valid value"}}}),FormValidation.Validator.remote={html5Attributes:{crossdomain:"crossDomain",data:"data",datatype:"dataType",delay:"delay",message:"message",name:"name",type:"type",url:"url",validkey:"validKey"},destroy:function(a,b){var c=a.getNamespace(),d=b.data(c+".remote.timer");d&&(clearTimeout(d),b.removeData(c+".remote.timer"))},validate:function(b,c,d){function e(){var b=a.ajax(m);return b.success(function(a){a.valid=a[l]===!0||"true"===a[l]?!0:a[l]===!1||"false"===a[l]?!1:null,h.resolve(c,"remote",a)}).error(function(){h.resolve(c,"remote",{valid:!1})}),h.fail(function(){b.abort()}),h}var f=b.getNamespace(),g=b.getFieldValue(c,"remote"),h=new a.Deferred;if(""===g)return h.resolve(c,"remote",{valid:!0}),h;var i=c.attr("data-"+f+"-field"),j=d.data||{},k=d.url,l=d.validKey||"valid";"function"==typeof j&&(j=j.call(this,b)),"string"==typeof j&&(j=JSON.parse(j)),"function"==typeof k&&(k=k.call(this,b)),j[d.name||i]=g;var m={data:j,dataType:d.dataType||"json",headers:d.headers||{},type:d.type||"GET",url:k};return null!==d.crossDomain&&(m.crossDomain=d.crossDomain===!0||"true"===d.crossDomain),d.delay?(c.data(f+".remote.timer")&&clearTimeout(c.data(f+".remote.timer")),c.data(f+".remote.timer",setTimeout(e,d.delay)),h):e()}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{rtn:{"default":"Please enter a valid RTN number"}}}),FormValidation.Validator.rtn={validate:function(a,b){var c=a.getFieldValue(b,"rtn");if(""===c)return!0;if(!/^\d{9}$/.test(c))return!1;for(var d=0,e=0;e<c.length;e+=3)d+=3*parseInt(c.charAt(e),10)+7*parseInt(c.charAt(e+1),10)+parseInt(c.charAt(e+2),10);return 0!==d&&d%10===0}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{sedol:{"default":"Please enter a valid SEDOL number"}}}),FormValidation.Validator.sedol={validate:function(a,b){var c=a.getFieldValue(b,"sedol");if(""===c)return!0;if(c=c.toUpperCase(),!/^[0-9A-Z]{7}$/.test(c))return!1;for(var d=0,e=[1,3,1,7,3,9,1],f=c.length,g=0;f-1>g;g++)d+=e[g]*parseInt(c.charAt(g),36);return d=(10-d%10)%10,d+""===c.charAt(f-1)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{siren:{"default":"Please enter a valid SIREN number"}}}),FormValidation.Validator.siren={validate:function(a,b){var c=a.getFieldValue(b,"siren");return""===c?!0:/^\d{9}$/.test(c)?FormValidation.Helper.luhn(c):!1}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{siret:{"default":"Please enter a valid SIRET number"}}}),FormValidation.Validator.siret={validate:function(a,b){var c=a.getFieldValue(b,"siret");if(""===c)return!0;for(var d,e=0,f=c.length,g=0;f>g;g++)d=parseInt(c.charAt(g),10),g%2===0&&(d=2*d,d>9&&(d-=9)),e+=d;return e%10===0}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{step:{"default":"Please enter a valid step of %s"}}}),FormValidation.Validator.step={html5Attributes:{message:"message",base:"baseValue",step:"step"},validate:function(b,c,d){var e=b.getFieldValue(c,"step");if(""===e)return!0;if(d=a.extend({},{baseValue:0,step:1},d),e=parseFloat(e),!a.isNumeric(e))return!1;var f=function(a,b){var c=Math.pow(10,b);a*=c;var d=a>0|-(0>a),e=a%1===.5*d;return e?(Math.floor(a)+(d>0))/c:Math.round(a)/c},g=function(a,b){if(0===b)return 1;var c=(a+"").split("."),d=(b+"").split("."),e=(1===c.length?0:c[1].length)+(1===d.length?0:d[1].length);return f(a-b*Math.floor(a/b),e)},h=b.getLocale(),i=g(e-d.baseValue,d.step);return{valid:0===i||i===d.step,message:FormValidation.Helper.format(d.message||FormValidation.I18n[h].step["default"],[d.step])}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{stringCase:{"default":"Please enter only lowercase characters",upper:"Please enter only uppercase characters"}}}),FormValidation.Validator.stringCase={html5Attributes:{message:"message","case":"case"},validate:function(a,b,c){var d=a.getFieldValue(b,"stringCase");if(""===d)return!0;var e=a.getLocale(),f=(c["case"]||"lower").toLowerCase();return{valid:"upper"===f?d===d.toUpperCase():d===d.toLowerCase(),message:c.message||("upper"===f?FormValidation.I18n[e].stringCase.upper:FormValidation.I18n[e].stringCase["default"])}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{stringLength:{"default":"Please enter a value with valid length",less:"Please enter less than %s characters",more:"Please enter more than %s characters",between:"Please enter value between %s and %s characters long"}}}),FormValidation.Validator.stringLength={html5Attributes:{message:"message",min:"min",max:"max",trim:"trim",utf8bytes:"utf8Bytes"},enableByHtml5:function(b){var c={},d=b.attr("maxlength"),e=b.attr("minlength");return d&&(c.max=parseInt(d,10)),e&&(c.min=parseInt(e,10)),a.isEmptyObject(c)?!1:c},validate:function(b,c,d){var e=b.getFieldValue(c,"stringLength");if((d.trim===!0||"true"===d.trim)&&(e=a.trim(e)),""===e)return!0;var f=b.getLocale(),g=a.isNumeric(d.min)?d.min:b.getDynamicOption(c,d.min),h=a.isNumeric(d.max)?d.max:b.getDynamicOption(c,d.max),i=function(a){for(var b=a.length,c=a.length-1;c>=0;c--){var d=a.charCodeAt(c);d>127&&2047>=d?b++:d>2047&&65535>=d&&(b+=2),d>=56320&&57343>=d&&c--}return b},j=d.utf8Bytes?i(e):e.length,k=!0,l=d.message||FormValidation.I18n[f].stringLength["default"];switch((g&&j<parseInt(g,10)||h&&j>parseInt(h,10))&&(k=!1),!0){case!!g&&!!h:l=FormValidation.Helper.format(d.message||FormValidation.I18n[f].stringLength.between,[parseInt(g,10),parseInt(h,10)]);break;case!!g:l=FormValidation.Helper.format(d.message||FormValidation.I18n[f].stringLength.more,parseInt(g,10));break;case!!h:l=FormValidation.Helper.format(d.message||FormValidation.I18n[f].stringLength.less,parseInt(h,10))}return{valid:k,message:l}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{uri:{"default":"Please enter a valid URI"}}}),FormValidation.Validator.uri={html5Attributes:{message:"message",allowlocal:"allowLocal",allowemptyprotocol:"allowEmptyProtocol",protocol:"protocol"},enableByHtml5:function(a){return"url"===a.attr("type")},validate:function(a,b,c){var d=a.getFieldValue(b,"uri");if(""===d)return!0;var e=c.allowLocal===!0||"true"===c.allowLocal,f=c.allowEmptyProtocol===!0||"true"===c.allowEmptyProtocol,g=(c.protocol||"http, https, ftp").split(",").join("|").replace(/\s/g,""),h=new RegExp("^(?:(?:"+g+")://)"+(f?"?":"")+"(?:\\S+(?::\\S*)?@)?(?:"+(e?"":"(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})")+"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9])*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))"+(e?"?":"")+")(?::\\d{2,5})?(?:/[^\\s]*)?$","i");return h.test(d)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{uuid:{"default":"Please enter a valid UUID number",version:"Please enter a valid UUID version %s number"}}}),FormValidation.Validator.uuid={html5Attributes:{message:"message",version:"version"},validate:function(a,b,c){var d=a.getFieldValue(b,"uuid");if(""===d)return!0;var e=a.getLocale(),f={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i},g=c.version?c.version+"":"all";return{valid:null===f[g]?!0:f[g].test(d),message:c.version?FormValidation.Helper.format(c.message||FormValidation.I18n[e].uuid.version,c.version):c.message||FormValidation.I18n[e].uuid["default"]}}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{vat:{"default":"Please enter a valid VAT number",country:"Please enter a valid VAT number in %s",countries:{AT:"Austria",BE:"Belgium",BG:"Bulgaria",BR:"Brazil",CH:"Switzerland",CY:"Cyprus",CZ:"Czech Republic",DE:"Germany",DK:"Denmark",EE:"Estonia",ES:"Spain",FI:"Finland",FR:"France",GB:"United Kingdom",GR:"Greek",EL:"Greek",HU:"Hungary",HR:"Croatia",IE:"Ireland",IS:"Iceland",IT:"Italy",LT:"Lithuania",LU:"Luxembourg",LV:"Latvia",MT:"Malta",NL:"Netherlands",NO:"Norway",PL:"Poland",PT:"Portugal",RO:"Romania",RU:"Russia",RS:"Serbia",SE:"Sweden",SI:"Slovenia",SK:"Slovakia",VE:"Venezuela",ZA:"South Africa"}}}}),FormValidation.Validator.vat={html5Attributes:{message:"message",country:"country"},COUNTRY_CODES:["AT","BE","BG","BR","CH","CY","CZ","DE","DK","EE","EL","ES","FI","FR","GB","GR","HR","HU","IE","IS","IT","LT","LU","LV","MT","NL","NO","PL","PT","RO","RU","RS","SE","SK","SI","VE","ZA"],validate:function(b,c,d){var e=b.getFieldValue(c,"vat");if(""===e)return!0;var f=b.getLocale(),g=d.country;if(g?("string"!=typeof g||-1===a.inArray(g.toUpperCase(),this.COUNTRY_CODES))&&(g=b.getDynamicOption(c,g)):g=e.substr(0,2),-1===a.inArray(g,this.COUNTRY_CODES))return!0;var h=["_",g.toLowerCase()].join("");return this[h](e)?!0:{valid:!1,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].vat.country,FormValidation.I18n[f].vat.countries[g.toUpperCase()])}},_at:function(a){if(/^ATU[0-9]{8}$/.test(a)&&(a=a.substr(2)),!/^U[0-9]{8}$/.test(a))return!1;a=a.substr(1);for(var b=0,c=[1,2,1,2,1,2,1],d=0,e=0;7>e;e++)d=parseInt(a.charAt(e),10)*c[e],d>9&&(d=Math.floor(d/10)+d%10),b+=d;return b=10-(b+4)%10,10===b&&(b=0),b+""===a.substr(7,1)},_be:function(a){if(/^BE[0]{0,1}[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0]{0,1}[0-9]{9}$/.test(a))return!1;if(9===a.length&&(a="0"+a),"0"===a.substr(1,1))return!1;var b=parseInt(a.substr(0,8),10)+parseInt(a.substr(8,2),10);return b%97===0},_bg:function(a){if(/^BG[0-9]{9,10}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9,10}$/.test(a))return!1;var b=0,c=0;if(9===a.length){for(c=0;8>c;c++)b+=parseInt(a.charAt(c),10)*(c+1);if(b%=11,10===b)for(b=0,c=0;8>c;c++)b+=parseInt(a.charAt(c),10)*(c+3);return b%=10,b+""===a.substr(8)}if(10===a.length){var d=function(a){var b=parseInt(a.substr(0,2),10)+1900,c=parseInt(a.substr(2,2),10),d=parseInt(a.substr(4,2),10);if(c>40?(b+=100,c-=40):c>20&&(b-=100,c-=20),!FormValidation.Helper.date(b,c,d))return!1;for(var e=0,f=[2,4,8,5,10,9,7,3,6],g=0;9>g;g++)e+=parseInt(a.charAt(g),10)*f[g];return e=e%11%10,e+""===a.substr(9,1)},e=function(a){for(var b=0,c=[21,19,17,13,11,9,7,3,1],d=0;9>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%=10,b+""===a.substr(9,1)},f=function(a){for(var b=0,c=[4,3,2,7,6,5,4,3,2],d=0;9>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b=11-b%11,10===b?!1:(11===b&&(b=0),b+""===a.substr(9,1))};return d(a)||e(a)||f(a)}return!1},_br:function(a){if(""===a)return!0;var b=a.replace(/[^\d]+/g,"");if(""===b||14!==b.length)return!1;if("00000000000000"===b||"11111111111111"===b||"22222222222222"===b||"33333333333333"===b||"44444444444444"===b||"55555555555555"===b||"66666666666666"===b||"77777777777777"===b||"88888888888888"===b||"99999999999999"===b)return!1;for(var c=b.length-2,d=b.substring(0,c),e=b.substring(c),f=0,g=c-7,h=c;h>=1;h--)f+=parseInt(d.charAt(c-h),10)*g--,2>g&&(g=9);var i=2>f%11?0:11-f%11;if(i!==parseInt(e.charAt(0),10))return!1;for(c+=1,d=b.substring(0,c),f=0,g=c-7,h=c;h>=1;h--)f+=parseInt(d.charAt(c-h),10)*g--,2>g&&(g=9);return i=2>f%11?0:11-f%11,i===parseInt(e.charAt(1),10)},_ch:function(a){if(/^CHE[0-9]{9}(MWST)?$/.test(a)&&(a=a.substr(2)),!/^E[0-9]{9}(MWST)?$/.test(a))return!1;a=a.substr(1);for(var b=0,c=[5,4,3,2,7,6,5,4],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b=11-b%11,10===b?!1:(11===b&&(b=0),b+""===a.substr(8,1))},_cy:function(a){if(/^CY[0-5|9]{1}[0-9]{7}[A-Z]{1}$/.test(a)&&(a=a.substr(2)),!/^[0-5|9]{1}[0-9]{7}[A-Z]{1}$/.test(a))return!1;if("12"===a.substr(0,2))return!1;for(var b=0,c={0:1,1:0,2:5,3:7,4:9,5:13,6:15,7:17,8:19,9:21},d=0;8>d;d++){var e=parseInt(a.charAt(d),10);d%2===0&&(e=c[e+""]),b+=e}return b="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[b%26],b+""===a.substr(8,1)},_cz:function(a){if(/^CZ[0-9]{8,10}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{8,10}$/.test(a))return!1;var b=0,c=0;if(8===a.length){if(a.charAt(0)+""=="9")return!1;for(b=0,c=0;7>c;c++)b+=parseInt(a.charAt(c),10)*(8-c);return b=11-b%11,10===b&&(b=0),11===b&&(b=1),b+""===a.substr(7,1)}if(9===a.length&&a.charAt(0)+""=="6"){for(b=0,c=0;7>c;c++)b+=parseInt(a.charAt(c+1),10)*(8-c);return b=11-b%11,10===b&&(b=0),11===b&&(b=1),b=[8,7,6,5,4,3,2,1,0,9,10][b-1],b+""===a.substr(8,1)}if(9===a.length||10===a.length){var d=1900+parseInt(a.substr(0,2),10),e=parseInt(a.substr(2,2),10)%50%20,f=parseInt(a.substr(4,2),10);if(9===a.length){if(d>=1980&&(d-=100),d>1953)return!1}else 1954>d&&(d+=100);if(!FormValidation.Helper.date(d,e,f))return!1;if(10===a.length){var g=parseInt(a.substr(0,9),10)%11;return 1985>d&&(g%=10),g+""===a.substr(9,1)}return!0}return!1},_de:function(a){return/^DE[0-9]{9}$/.test(a)&&(a=a.substr(2)),/^[0-9]{9}$/.test(a)?FormValidation.Helper.mod11And10(a):!1},_dk:function(a){if(/^DK[0-9]{8}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{8}$/.test(a))return!1;for(var b=0,c=[2,7,6,5,4,3,2,1],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%11===0},_ee:function(a){if(/^EE[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9}$/.test(a))return!1;for(var b=0,c=[3,7,1,3,7,1,3,7,1],d=0;9>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%10===0},_es:function(a){if(/^ES[0-9A-Z][0-9]{7}[0-9A-Z]$/.test(a)&&(a=a.substr(2)),!/^[0-9A-Z][0-9]{7}[0-9A-Z]$/.test(a))return!1;var b=function(a){var b=parseInt(a.substr(0,8),10);return b="TRWAGMYFPDXBNJZSQVHLCKE"[b%23],b+""===a.substr(8,1)},c=function(a){var b=["XYZ".indexOf(a.charAt(0)),a.substr(1)].join("");return b=parseInt(b,10),b="TRWAGMYFPDXBNJZSQVHLCKE"[b%23],b+""===a.substr(8,1)},d=function(a){var b,c=a.charAt(0);if(-1!=="KLM".indexOf(c))return b=parseInt(a.substr(1,8),10),b="TRWAGMYFPDXBNJZSQVHLCKE"[b%23],b+""===a.substr(8,1);if(-1!=="ABCDEFGHJNPQRSUVW".indexOf(c)){for(var d=0,e=[2,1,2,1,2,1,2],f=0,g=0;7>g;g++)f=parseInt(a.charAt(g+1),10)*e[g],f>9&&(f=Math.floor(f/10)+f%10),d+=f;return d=10-d%10,10===d&&(d=0),d+""===a.substr(8,1)||"JABCDEFGHI"[d]===a.substr(8,1)}return!1},e=a.charAt(0);return/^[0-9]$/.test(e)?b(a):/^[XYZ]$/.test(e)?c(a):d(a)},_fi:function(a){if(/^FI[0-9]{8}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{8}$/.test(a))return!1;for(var b=0,c=[7,9,10,5,8,4,2,1],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%11===0},_fr:function(a){if(/^FR[0-9A-Z]{2}[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0-9A-Z]{2}[0-9]{9}$/.test(a))return!1;if(!FormValidation.Helper.luhn(a.substr(2)))return!1;if(/^[0-9]{2}$/.test(a.substr(0,2)))return a.substr(0,2)===parseInt(a.substr(2)+"12",10)%97+"";var b,c="0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";return b=/^[0-9]{1}$/.test(a.charAt(0))?24*c.indexOf(a.charAt(0))+c.indexOf(a.charAt(1))-10:34*c.indexOf(a.charAt(0))+c.indexOf(a.charAt(1))-100,(parseInt(a.substr(2),10)+1+Math.floor(b/11))%11===b%11},_gb:function(a){if((/^GB[0-9]{9}$/.test(a)||/^GB[0-9]{12}$/.test(a)||/^GBGD[0-9]{3}$/.test(a)||/^GBHA[0-9]{3}$/.test(a)||/^GB(GD|HA)8888[0-9]{5}$/.test(a))&&(a=a.substr(2)),!(/^[0-9]{9}$/.test(a)||/^[0-9]{12}$/.test(a)||/^GD[0-9]{3}$/.test(a)||/^HA[0-9]{3}$/.test(a)||/^(GD|HA)8888[0-9]{5}$/.test(a)))return!1;var b=a.length;if(5===b){var c=a.substr(0,2),d=parseInt(a.substr(2),10);return"GD"===c&&500>d||"HA"===c&&d>=500}if(11===b&&("GD8888"===a.substr(0,6)||"HA8888"===a.substr(0,6)))return"GD"===a.substr(0,2)&&parseInt(a.substr(6,3),10)>=500||"HA"===a.substr(0,2)&&parseInt(a.substr(6,3),10)<500?!1:parseInt(a.substr(6,3),10)%97===parseInt(a.substr(9,2),10);if(9===b||12===b){for(var e=0,f=[8,7,6,5,4,3,2,10,1],g=0;9>g;g++)e+=parseInt(a.charAt(g),10)*f[g];return e%=97,parseInt(a.substr(0,3),10)>=100?0===e||42===e||55===e:0===e}return!0},_gr:function(a){if(/^(GR|EL)[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9}$/.test(a))return!1;8===a.length&&(a="0"+a);for(var b=0,c=[256,128,64,32,16,8,4,2],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b=b%11%10,b+""===a.substr(8,1)},_el:function(a){return this._gr(a)},_hu:function(a){if(/^HU[0-9]{8}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{8}$/.test(a))return!1;for(var b=0,c=[9,7,3,1,9,7,3,1],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%10===0},_hr:function(a){return/^HR[0-9]{11}$/.test(a)&&(a=a.substr(2)),/^[0-9]{11}$/.test(a)?FormValidation.Helper.mod11And10(a):!1},_ie:function(a){if(/^IE[0-9]{1}[0-9A-Z\*\+]{1}[0-9]{5}[A-Z]{1,2}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{1}[0-9A-Z\*\+]{1}[0-9]{5}[A-Z]{1,2}$/.test(a))return!1;var b=function(a){for(;a.length<7;)a="0"+a;for(var b="WABCDEFGHIJKLMNOPQRSTUV",c=0,d=0;7>d;d++)c+=parseInt(a.charAt(d),10)*(8-d);return c+=9*b.indexOf(a.substr(7)),b[c%23]};return/^[0-9]+$/.test(a.substr(0,7))?a.charAt(7)===b(a.substr(0,7)+a.substr(8)+""):-1!=="ABCDEFGHIJKLMNOPQRSTUVWXYZ+*".indexOf(a.charAt(1))?a.charAt(7)===b(a.substr(2,5)+a.substr(0,1)+""):!0},_is:function(a){return/^IS[0-9]{5,6}$/.test(a)&&(a=a.substr(2)),/^[0-9]{5,6}$/.test(a)},_it:function(a){if(/^IT[0-9]{11}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{11}$/.test(a))return!1;if(0===parseInt(a.substr(0,7),10))return!1;var b=parseInt(a.substr(7,3),10);return 1>b||b>201&&999!==b&&888!==b?!1:FormValidation.Helper.luhn(a)},_lt:function(a){if(/^LT([0-9]{7}1[0-9]{1}|[0-9]{10}1[0-9]{1})$/.test(a)&&(a=a.substr(2)),!/^([0-9]{7}1[0-9]{1}|[0-9]{10}1[0-9]{1})$/.test(a))return!1;var b,c=a.length,d=0;for(b=0;c-1>b;b++)d+=parseInt(a.charAt(b),10)*(1+b%9);var e=d%11;if(10===e)for(d=0,b=0;c-1>b;b++)d+=parseInt(a.charAt(b),10)*(1+(b+2)%9);return e=e%11%10,e+""===a.charAt(c-1)},_lu:function(a){return/^LU[0-9]{8}$/.test(a)&&(a=a.substr(2)),/^[0-9]{8}$/.test(a)?parseInt(a.substr(0,6),10)%89+""===a.substr(6,2):!1},_lv:function(a){if(/^LV[0-9]{11}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{11}$/.test(a))return!1;var b,c=parseInt(a.charAt(0),10),d=0,e=[],f=a.length;if(c>3){for(d=0,e=[9,1,4,8,3,10,2,5,7,6,1],b=0;f>b;b++)d+=parseInt(a.charAt(b),10)*e[b];return d%=11,3===d}var g=parseInt(a.substr(0,2),10),h=parseInt(a.substr(2,2),10),i=parseInt(a.substr(4,2),10);if(i=i+1800+100*parseInt(a.charAt(6),10),!FormValidation.Helper.date(i,h,g))return!1;for(d=0,e=[10,5,8,4,2,1,6,3,7,9],b=0;f-1>b;b++)d+=parseInt(a.charAt(b),10)*e[b];return d=(d+1)%11%10,d+""===a.charAt(f-1)},_mt:function(a){if(/^MT[0-9]{8}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{8}$/.test(a))return!1;for(var b=0,c=[3,4,6,7,8,9,10,1],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%37===0},_nl:function(a){if(/^NL[0-9]{9}B[0-9]{2}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9}B[0-9]{2}$/.test(a))return!1;for(var b=0,c=[9,8,7,6,5,4,3,2],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%=11,b>9&&(b=0),b+""===a.substr(8,1)},_no:function(a){if(/^NO[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9}$/.test(a))return!1;for(var b=0,c=[3,2,7,6,5,4,3,2],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b=11-b%11,11===b&&(b=0),b+""===a.substr(8,1)},_pl:function(a){if(/^PL[0-9]{10}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{10}$/.test(a))return!1;for(var b=0,c=[6,5,7,2,3,4,5,6,7,-1],d=0;10>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b%11===0},_pt:function(a){if(/^PT[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9}$/.test(a))return!1;for(var b=0,c=[9,8,7,6,5,4,3,2],d=0;8>d;d++)b+=parseInt(a.charAt(d),10)*c[d];return b=11-b%11,b>9&&(b=0),b+""===a.substr(8,1)},_ro:function(a){if(/^RO[1-9][0-9]{1,9}$/.test(a)&&(a=a.substr(2)),!/^[1-9][0-9]{1,9}$/.test(a))return!1;for(var b=a.length,c=[7,5,3,2,1,7,5,3,2].slice(10-b),d=0,e=0;b-1>e;e++)d+=parseInt(a.charAt(e),10)*c[e];return d=10*d%11%10,d+""===a.substr(b-1,1)},_ru:function(a){if(/^RU([0-9]{10}|[0-9]{12})$/.test(a)&&(a=a.substr(2)),!/^([0-9]{10}|[0-9]{12})$/.test(a))return!1;var b=0;if(10===a.length){var c=0,d=[2,4,10,3,5,9,4,6,8,0];for(b=0;10>b;b++)c+=parseInt(a.charAt(b),10)*d[b];return c%=11,c>9&&(c%=10),c+""===a.substr(9,1)}if(12===a.length){var e=0,f=[7,2,4,10,3,5,9,4,6,8,0],g=0,h=[3,7,2,4,10,3,5,9,4,6,8,0];for(b=0;11>b;b++)e+=parseInt(a.charAt(b),10)*f[b],g+=parseInt(a.charAt(b),10)*h[b];return e%=11,e>9&&(e%=10),g%=11,g>9&&(g%=10),e+""===a.substr(10,1)&&g+""===a.substr(11,1)}return!1},_rs:function(a){if(/^RS[0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[0-9]{9}$/.test(a))return!1;for(var b=10,c=0,d=0;8>d;d++)c=(parseInt(a.charAt(d),10)+b)%10,0===c&&(c=10),b=2*c%11;return(b+parseInt(a.substr(8,1),10))%10===1},_se:function(a){return/^SE[0-9]{10}01$/.test(a)&&(a=a.substr(2)),/^[0-9]{10}01$/.test(a)?(a=a.substr(0,10),FormValidation.Helper.luhn(a)):!1},_si:function(a){var b=a.match(/^(SI)?([1-9][0-9]{7})$/);if(!b)return!1;b[1]&&(a=a.substr(2));for(var c=0,d=[8,7,6,5,4,3,2],e=0;7>e;e++)c+=parseInt(a.charAt(e),10)*d[e];return c=11-c%11,10===c&&(c=0),c+""===a.substr(7,1)},_sk:function(a){return/^SK[1-9][0-9][(2-4)|(6-9)][0-9]{7}$/.test(a)&&(a=a.substr(2)),/^[1-9][0-9][(2-4)|(6-9)][0-9]{7}$/.test(a)?parseInt(a,10)%11===0:!1},_ve:function(a){if(/^VE[VEJPG][0-9]{9}$/.test(a)&&(a=a.substr(2)),!/^[VEJPG][0-9]{9}$/.test(a))return!1;for(var b={V:4,E:8,J:12,P:16,G:20},c=b[a.charAt(0)],d=[3,2,7,6,5,4,3,2],e=0;8>e;e++)c+=parseInt(a.charAt(e+1),10)*d[e];return c=11-c%11,(11===c||10===c)&&(c=0),c+""===a.substr(9,1)},_za:function(a){return/^ZA4[0-9]{9}$/.test(a)&&(a=a.substr(2)),/^4[0-9]{9}$/.test(a)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{vin:{"default":"Please enter a valid VIN number"}}}),FormValidation.Validator.vin={validate:function(a,b){var c=a.getFieldValue(b,"vin");if(""===c)return!0;if(!/^[a-hj-npr-z0-9]{8}[0-9xX][a-hj-npr-z0-9]{8}$/i.test(c))return!1;c=c.toUpperCase();for(var d={A:1,B:2,C:3,D:4,E:5,F:6,G:7,H:8,J:1,K:2,L:3,M:4,N:5,P:7,R:9,S:2,T:3,U:4,V:5,W:6,X:7,Y:8,Z:9,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,0:0},e=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2],f=0,g=c.length,h=0;g>h;h++)f+=d[c.charAt(h)+""]*e[h];var i=f%11;return 10===i&&(i="X"),i+""===c.charAt(8)}}}(jQuery),function(a){FormValidation.I18n=a.extend(!0,FormValidation.I18n||{},{en_US:{zipCode:{"default":"Please enter a valid postal code",country:"Please enter a valid postal code in %s",countries:{AT:"Austria",BG:"Bulgaria",BR:"Brazil",CA:"Canada",CH:"Switzerland",CZ:"Czech Republic",DE:"Germany",DK:"Denmark",ES:"Spain",FR:"France",GB:"United Kingdom",IE:"Ireland",IN:"India",IT:"Italy",MA:"Morocco",NL:"Netherlands",PL:"Poland",PT:"Portugal",RO:"Romania",RU:"Russia",SE:"Sweden",SG:"Singapore",SK:"Slovakia",US:"USA"}}}}),FormValidation.Validator.zipCode={html5Attributes:{message:"message",country:"country"},COUNTRY_CODES:["AT","BG","BR","CA","CH","CZ","DE","DK","ES","FR","GB","IE","IN","IT","MA","NL","PL","PT","RO","RU","SE","SG","SK","US"],validate:function(b,c,d){var e=b.getFieldValue(c,"zipCode");if(""===e||!d.country)return!0;var f=b.getLocale(),g=d.country;if(("string"!=typeof g||-1===a.inArray(g,this.COUNTRY_CODES))&&(g=b.getDynamicOption(c,g)),!g||-1===a.inArray(g.toUpperCase(),this.COUNTRY_CODES))return!0;var h=!1;switch(g=g.toUpperCase()){case"AT":h=/^([1-9]{1})(\d{3})$/.test(e);break;case"BG":h=/^([1-9]{1}[0-9]{3})$/.test(a.trim(e));break;case"BR":h=/^(\d{2})([\.]?)(\d{3})([\-]?)(\d{3})$/.test(e);break;case"CA":h=/^(?:A|B|C|E|G|H|J|K|L|M|N|P|R|S|T|V|X|Y){1}[0-9]{1}(?:A|B|C|E|G|H|J|K|L|M|N|P|R|S|T|V|W|X|Y|Z){1}\s?[0-9]{1}(?:A|B|C|E|G|H|J|K|L|M|N|P|R|S|T|V|W|X|Y|Z){1}[0-9]{1}$/i.test(e);break;case"CH":h=/^([1-9]{1})(\d{3})$/.test(e);break;case"CZ":h=/^(\d{3})([ ]?)(\d{2})$/.test(e);break;case"DE":h=/^(?!01000|99999)(0[1-9]\d{3}|[1-9]\d{4})$/.test(e);break;case"DK":h=/^(DK(-|\s)?)?\d{4}$/i.test(e);break;case"ES":h=/^(?:0[1-9]|[1-4][0-9]|5[0-2])\d{3}$/.test(e);break;case"FR":h=/^[0-9]{5}$/i.test(e);break;case"GB":h=this._gb(e);break;case"IN":h=/^\d{3}\s?\d{3}$/.test(e);break;case"IE":h=/^(D6W|[ACDEFHKNPRTVWXY]\d{2})\s[0-9ACDEFHKNPRTVWXY]{4}$/.test(e);break;case"IT":h=/^(I-|IT-)?\d{5}$/i.test(e);break;case"MA":h=/^[1-9][0-9]{4}$/i.test(e);break;case"NL":h=/^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{2}$/i.test(e);break;case"PL":h=/^[0-9]{2}\-[0-9]{3}$/.test(e);break;case"PT":h=/^[1-9]\d{3}-\d{3}$/.test(e);break;case"RO":h=/^(0[1-8]{1}|[1-9]{1}[0-5]{1})?[0-9]{4}$/i.test(e);break;case"RU":h=/^[0-9]{6}$/i.test(e);break;case"SE":h=/^(S-)?\d{3}\s?\d{2}$/i.test(e);break;case"SG":h=/^([0][1-9]|[1-6][0-9]|[7]([0-3]|[5-9])|[8][0-2])(\d{4})$/i.test(e);break;case"SK":h=/^(\d{3})([ ]?)(\d{2})$/.test(e);break;case"US":default:h=/^\d{4,5}([\-]?\d{4})?$/.test(e)}return{valid:h,message:FormValidation.Helper.format(d.message||FormValidation.I18n[f].zipCode.country,FormValidation.I18n[f].zipCode.countries[g])}},_gb:function(a){for(var b="[ABCDEFGHIJKLMNOPRSTUWYZ]",c="[ABCDEFGHKLMNOPQRSTUVWXY]",d="[ABCDEFGHJKPMNRSTUVWXY]",e="[ABEHMNPRVWXY]",f="[ABDEFGHJLNPQRSTUWXYZ]",g=[new RegExp("^("+b+"{1}"+c+"?[0-9]{1,2})(\\s*)([0-9]{1}"+f+"{2})$","i"),new RegExp("^("+b+"{1}[0-9]{1}"+d+"{1})(\\s*)([0-9]{1}"+f+"{2})$","i"),new RegExp("^("+b+"{1}"+c+"{1}?[0-9]{1}"+e+"{1})(\\s*)([0-9]{1}"+f+"{2})$","i"),new RegExp("^(BF1)(\\s*)([0-6]{1}[ABDEFGHJLNPQRST]{1}[ABDEFGHJLNPQRSTUWZYZ]{1})$","i"),/^(GIR)(\s*)(0AA)$/i,/^(BFPO)(\s*)([0-9]{1,4})$/i,/^(BFPO)(\s*)(c\/o\s*[0-9]{1,3})$/i,/^([A-Z]{4})(\s*)(1ZZ)$/i,/^(AI-2640)$/i],h=0;h<g.length;h++)if(g[h].test(a))return!0;return!1}}}(jQuery);
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[137],{
/***/ "./frontend/src/assets/images/banner/banner.png":
/*!******************************************************!*\
!*** ./frontend/src/assets/images/banner/banner.png ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = "/images/_/_/_/_/full-version/frontend/src/assets/images/banner/banner.png";
/***/ }),
/***/ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue":
/*!***************************************************************************!*\
!*** ./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue ***!
\***************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _KnowledgeBaseCategory_vue_vue_type_template_id_37223198___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./KnowledgeBaseCategory.vue?vue&type=template&id=37223198& */ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=template&id=37223198&");
/* harmony import */ var _KnowledgeBaseCategory_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./KnowledgeBaseCategory.vue?vue&type=script&lang=js& */ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _KnowledgeBaseCategory_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss& */ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss&");
/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_KnowledgeBaseCategory_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_KnowledgeBaseCategory_vue_vue_type_template_id_37223198___WEBPACK_IMPORTED_MODULE_0__["render"],
_KnowledgeBaseCategory_vue_vue_type_template_id_37223198___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=script&lang=js&":
/*!****************************************************************************************************!*\
!*** ./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=script&lang=js& ***!
\****************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./KnowledgeBaseCategory.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss&":
/*!*************************************************************************************************************!*\
!*** ./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss& ***!
\*************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/style-loader!../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--7-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--7-3!../../../../../node_modules/sass-loader/dist/cjs.js??ref--11-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss&");
/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__) if(["default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/***/ }),
/***/ "./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=template&id=37223198&":
/*!**********************************************************************************************************!*\
!*** ./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=template&id=37223198& ***!
\**********************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_template_id_37223198___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./KnowledgeBaseCategory.vue?vue&type=template&id=37223198& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=template&id=37223198&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_template_id_37223198___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_KnowledgeBaseCategory_vue_vue_type_template_id_37223198___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ }),
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=script&lang=js&":
/*!************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=script&lang=js& ***!
\************************************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bootstrap-vue */ "./frontend/node_modules/bootstrap-vue/esm/index.js");
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
components: {
BRow: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BRow"],
BCol: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BCol"],
BCard: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BCard"],
BListGroup: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BListGroup"],
BListGroupItem: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BListGroupItem"],
BCardBody: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BCardBody"],
BCardText: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BCardText"],
BForm: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BForm"],
BInputGroup: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BInputGroup"],
BInputGroupPrepend: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BInputGroupPrepend"],
BFormInput: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BFormInput"]
},
data: function data() {
return {
knowledgeBaseSearchQuery: '',
kb: []
};
},
computed: {
filteredKB: function filteredKB() {
var knowledgeBaseSearchQueryLower = this.knowledgeBaseSearchQuery.toLowerCase();
return this.kb.filter(function (item) {
return item.title.toLowerCase().includes(knowledgeBaseSearchQueryLower) || item.questions.filter(function (queObj) {
return queObj.question.toLowerCase().includes(knowledgeBaseSearchQueryLower);
}).length;
});
}
},
created: function created() {
var _this = this;
// ! You have to update the below API call according to route parameter
// * We are using fixed API call for all categories for demo purposes
this.$http.get('/kb/data/category').then(function (res) {
_this.kb = res.data;
});
}
});
/***/ }),
/***/ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss&":
/*!*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-2!./node_modules/sass-loader/dist/cjs.js??ref--7-3!./node_modules/sass-loader/dist/cjs.js??ref--11-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss& ***!
\*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! ../../../../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false);
// imports
// module
exports.push([module.i, "[dir] .knowledge-base-bg {\n background-size: cover;\n background-color: rgba(115, 103, 240, 0.12) !important;\n}\n.knowledge-base-bg .kb-search-input .input-group:focus-within {\n -webkit-box-shadow: none;\n}\n[dir] .knowledge-base-bg .kb-search-input .input-group:focus-within {\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n[dir] .kb-search-content-info .kb-search-content .card-img-top {\n background-color: #fcfcfc;\n}\n.kb-search-content-info .no-result.no-items {\n display: none;\n}\n.kb-title {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n}\n@media (min-width: 768px) {\n.knowledge-base-bg .kb-search-input .input-group {\n width: 576px;\n}\n[dir] .knowledge-base-bg .kb-search-input .input-group {\n margin: 0 auto;\n}\n}\n@media (min-width: 992px) {\n[dir] .knowledge-base-bg .card-body {\n padding: 8rem;\n}\n}\n@media (min-width: 768px) and (max-width: 991.98px) {\n[dir] .knowledge-base-bg .card-body {\n padding: 6rem;\n}\n}\n[dir] .list-group-circle .list-group-item-action:focus, [dir] .list-group-circle .list-group-item-action:active {\n background-color: transparent;\n}\n[dir] .question-content ul li {\n margin-bottom: 1rem;\n}\n.question-content ul li a {\n color: inherit;\n}", ""]);
// exports
/***/ }),
/***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss&":
/*!*****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-2!./node_modules/sass-loader/dist/cjs.js??ref--7-3!./node_modules/sass-loader/dist/cjs.js??ref--11-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss& ***!
\*****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var content = __webpack_require__(/*! !../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--7-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--7-3!../../../../../node_modules/sass-loader/dist/cjs.js??ref--11-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=style&index=0&lang=scss&");
if(typeof content === 'string') content = [[module.i, content, '']];
var transform;
var insertInto;
var options = {"hmr":true}
options.transform = transform
options.insertInto = undefined;
var update = __webpack_require__(/*! ../../../../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options);
if(content.locals) module.exports = content.locals;
if(false) {}
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=template&id=37223198&":
/*!****************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/pages/Knowledge-base/KnowledgeBaseCategory.vue?vue&type=template&id=37223198& ***!
\****************************************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c("div", [
_c(
"section",
{ attrs: { id: "kb-category-search" } },
[
_c(
"b-card",
{
staticClass: "knowledge-base-bg text-center",
style: {
backgroundImage:
"url(" + __webpack_require__(/*! @/assets/images/banner/banner.png */ "./frontend/src/assets/images/banner/banner.png") + ")"
},
attrs: { "no-body": "" }
},
[
_c(
"b-card-body",
{ staticClass: "card-body" },
[
_c("h2", { staticClass: "text-primary" }, [
_vm._v(
"\n Dedicated Source Used on Website\n "
)
]),
_vm._v(" "),
_c("b-card-text", { staticClass: "mb-2" }, [
_c("span", [_vm._v("Popular searches: ")]),
_vm._v(" "),
_c("span", { staticClass: "font-weight-bolder" }, [
_vm._v("Sales automation, Email marketing")
])
]),
_vm._v(" "),
_c(
"b-form",
{ staticClass: "kb-search-input" },
[
_c(
"b-input-group",
{ staticClass: "input-group-merge" },
[
_c(
"b-input-group-prepend",
{ attrs: { "is-text": "" } },
[
_c("feather-icon", {
attrs: { icon: "SearchIcon" }
})
],
1
),
_vm._v(" "),
_c("b-form-input", {
attrs: {
id: "searchbar",
placeholder: "Ask a question...."
},
model: {
value: _vm.knowledgeBaseSearchQuery,
callback: function($$v) {
_vm.knowledgeBaseSearchQuery = $$v
},
expression: "knowledgeBaseSearchQuery"
}
})
],
1
)
],
1
)
],
1
)
],
1
)
],
1
),
_vm._v(" "),
_c(
"div",
{ attrs: { id: "knowledge-base-category" } },
[
_c(
"b-row",
{ staticClass: "match-height" },
[
_vm._l(_vm.filteredKB, function(data, index) {
return _c(
"b-col",
{ key: index, attrs: { md: "4", sm: "6" } },
[
_c(
"b-card",
[
_c(
"h6",
{ staticClass: "kb-title" },
[
_c("feather-icon", {
staticClass: "mr-50",
class: data.iconColor,
attrs: { icon: data.icon, size: "20" }
}),
_vm._v(
_vm._s(data.title) +
" (" +
_vm._s(data.questions.length) +
")\n "
)
],
1
),
_vm._v(" "),
_c(
"b-list-group",
{ staticClass: "list-group-circle mt-2" },
_vm._l(data.questions, function(que) {
return _c(
"b-list-group-item",
{
key: que.question,
staticClass: "text-body",
attrs: {
to: {
name: "pages-knowledge-base-question",
params: {
category: _vm.$route.params.category,
slug: que.slug
}
}
}
},
[
_vm._v(
"\n " +
_vm._s(que.question) +
"\n "
)
]
)
}),
1
)
],
1
)
],
1
)
}),
_vm._v(" "),
_c(
"b-col",
{
directives: [
{
name: "show",
rawName: "v-show",
value: !_vm.filteredKB.length,
expression: "!filteredKB.length"
}
],
staticClass: "text-center",
attrs: { cols: "12" }
},
[
_c("h4", { staticClass: "mt-4" }, [
_vm._v("\n Search result not found!!\n ")
])
]
)
],
2
)
],
1
)
])
}
var staticRenderFns = []
render._withStripped = true
/***/ })
}]);
|
from setuptools import setup, find_packages
setup(name='molSim', version='1.0', packages=find_packages())
|
$(document).ready(function () {
// Get the modal
var modal = document.getElementById("createModal");
// Get the button that opens the modal
var btn = document.getElementById("createModalBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
if(modal != null){
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}
var home__template = document.getElementById("home__template");
if(home__template != null){
$.ajax({
type: 'GET',
url: '/api/getJournal/',
data: {},
dataType: 'json'
}).done(function (data) {
if(data.status == '200'){
$.each(data.data, function (index, item) {
var journal__item = document.createElement('div');
var journal__poster = document.createElement('div');
var journal__overlay = document.createElement('div');
var journal__action = document.createElement('div');
var journal__name = document.createElement('h3');
journal__item.setAttribute('class', 'journal__item');
journal__poster.setAttribute('class', 'journal__item--poster');
journal__poster.setAttribute('style', "background-image: url('" + item.poster_path + "')");
journal__overlay.setAttribute('class', 'journal__item--overlay');
journal__action.setAttribute('class', 'journal__item--action');
journal__name.setAttribute('style', "text-align: center");
journal__name.append(item.name);
var download = document.createElement('a');
download.setAttribute('href', '#');
download.setAttribute('download', item.name);
download.text = "Download";
var read = document.createElement('a');
read.setAttribute('href', "/show/" + item.id);
read.text = 'Read';
journal__action.append(
download,
read
);
journal__overlay.append(journal__action);
journal__poster.append(journal__overlay);
journal__item.append(journal__poster, journal__name);
home__template.append(journal__item);
});
console.log(data.data);
}if(data.status == '401'){
alert(data.msg);
}
});
}
var journal__template = document.getElementById("journal__template");
if(journal__template != null){
var url = new URL(window.location.href);
var id = url.pathname.split('/')[2];
$.ajax({
type: 'GET',
url: '/api/getJournal/' + id,
data: {},
dataType: 'json'
}).done(function (data) {
if(data.status == '200'){
var pdf = document.createElement('iframe');
pdf.setAttribute('width', '100%');
pdf.setAttribute('height', '100%');
pdf.setAttribute('src', data.data[0].journal_path);
journal__template.append(pdf);
}if(data.status == '401'){
alert(data.msg);
}
});
}
$(".trigger__deleteJournal").on('click', function (e) {
e.preventDefault();
var id = $(this).attr('data-id');
$.ajax({
type: 'POST',
url: '/admin/journal/delete',
data: {id: id},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json'
}).done(function (data) {
if(data.status == '200'){
//alert(data.msg);
window.location.reload();
}if(data.status == '401'){
alert(data.msg);
}
});
});
$(".trigger__saveJournal").on('submit', function (e) {
e.preventDefault();
var FD = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: '/admin/journal/save',
data: FD,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
dataType: 'json'
}).done(function (data) {
if(data.status == '200'){
//alert(data.msg);
window.location.reload();
modal.style.display = "none";
}if(data.status == '401'){
alert(data.msg);
}
});
});
});
|
// @flow
import * as React from "react";
import {
View,
Text,
Image,
ScrollView,
ImageBackground
} from "react-native";
import i18n from "../../i18n";
import { colors } from "../../styles/global";
import { viewStyles, textStyles, imageStyles } from "../../styles/auth/loginOrSignup";
import logoImages from "../../assets/logos";
import backgrounds from "../../assets/backgrounds";
import Button from "../UIComponents/Buttons/Button";
import { enabledLargeFonts } from "../../utility/textHelpers";
type Props = {
+navigation: any
}
const LoginOrSignupScreen = ( { navigation }: Props ): React.Node => {
const navToLogin = ( ) => navigation.navigate( "Login" );
const navToAge = ( ) => navigation.navigate( "Age" );
const navToDrawer = ( ) => navigation.navigate( "Drawer" );
return (
<ImageBackground
source={backgrounds.login}
style={viewStyles.container}
>
<ScrollView
contentContainerStyle={[viewStyles.center, viewStyles.scrollContainer]}
scrollEnabled={enabledLargeFonts()}
>
<Image source={logoImages.seek} style={imageStyles.logo} />
<View style={viewStyles.margin} />
<Button
handlePress={navToLogin}
text="login.log_in"
color={colors.white}
greenText
login
/>
<View style={viewStyles.marginSmall} />
<Button
handlePress={navToAge}
text="login.sign_up"
color={colors.white}
greenText
login
/>
<View style={viewStyles.marginSmall} />
<Button
handlePress={navToDrawer}
text="login.skip_login"
large
color={colors.white}
greenText
login
/>
<View style={viewStyles.margin} />
<Text style={textStyles.text}>
{i18n.t( "login.about" )}
</Text>
</ScrollView>
</ImageBackground>
);
};
export default LoginOrSignupScreen;
|
"""
WSGI config for edd project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application # noqa: E402
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "edd.settings")
application = get_wsgi_application()
|
import Vue from 'vue';
import App from './App.vue';
import router from './routes';
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
|
import React, { useContext } from "react"
import styled, { ThemeContext } from "styled-components"
import { useIntl } from "gatsby-plugin-intl"
import Link from "../Link"
import Translation from "../Translation"
import { translateMessageId } from "../../utils/translations"
import { trackCustomEvent } from "../../utils/matomo"
import SoloGlyph from "../../assets/staking/staking-glyph-cpu.svg"
import SaasGlyph from "../../assets/staking/staking-glyph-cloud.svg"
import PoolGlyph from "../../assets/staking/staking-glyph-token-wallet.svg"
const GradientContainer = styled.div`
display: flex;
flex-direction: column;
gap: 2rem;
background: linear-gradient(
83.46deg,
rgba(127, 127, 213, 0.2) 7.03%,
rgba(138, 168, 231, 0.2) 52.42%,
rgba(145, 234, 228, 0.2) 98.77%
);
padding: 2rem;
margin-top: 4rem;
@media (max-width: ${({ theme }) => theme.breakpoints.m}) {
padding: 2rem 1.5rem;
}
h3 {
margin: 0 0 0.5rem;
}
`
const Flex = styled.div`
display: flex;
gap: 1.5rem;
@media (max-width: ${({ theme }) => theme.breakpoints.m}) {
flex-direction: column;
}
`
const Glyph = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
width: 3rem;
max-height: 3rem;
`
const StyledSoloGlyph = styled(SoloGlyph)`
path {
fill: ${({ theme }) => theme.colors.stakingGold};
}
`
const StyledSaasGlyph = styled(SaasGlyph)`
path {
fill: ${({ theme }) => theme.colors.stakingGreen};
}
`
const StyledPoolGlyph = styled(PoolGlyph)`
path {
fill: ${({ theme }) => theme.colors.stakingBlue};
}
`
const StakingComparison = ({ page, className }) => {
const intl = useIntl()
const themeContext = useContext(ThemeContext)
const { stakingGold, stakingGreen, stakingBlue } = themeContext.colors
const solo = {
title: "Solo staking",
linkText: "Learn more about solo staking",
to: "/staking/solo/",
matomo: {
eventCategory: `StakingComparison`,
eventAction: `Clicked`,
eventName: "clicked solo staking",
},
color: stakingGold,
glyph: <StyledSoloGlyph />,
}
const saas = {
title: "Staking as a service (SaaS)",
linkText: "Learn more about staking as a service",
to: "/staking/saas/",
matomo: {
eventCategory: `StakingComparison`,
eventAction: `Clicked`,
eventName: "clicked staking as a service",
},
color: stakingGreen,
glyph: <StyledSaasGlyph />,
}
const pools = {
title: "Pooled staking",
linkText: "Learn more about pooled staking",
to: "/staking/pools/",
matomo: {
eventCategory: `StakingComparison`,
eventAction: `Clicked`,
eventName: "clicked pooled staking",
},
color: stakingBlue,
glyph: <StyledPoolGlyph />,
}
const data = {
solo: [
{
...saas,
content:
"With SaaS providers you're still required to deposit 32 ETH, but don't have to run hardware. You typically maintain access to your validator keys, but also need to share your signing keys so the operator can act on behalf of your validator. This introduces a layer of trust not present when running your own hardware, and unlike solo staking at home, SaaS does not help as much with geographic distribution of nodes. If you're uncomfortable operating hardware but still looking to stake 32 ETH, using a SaaS provider may be a good option for you.",
},
{
...pools,
content:
"Solo staking is significantly more involved than staking with a pooling service, but offer full access to ETH rewards, and full control over the setup and security of your validator. Pooled staking has a significantly lower barrier to entry. Users can stake small amounts of ETH, are not required to generate validator keys, and have no hardware requirements beyond a standard internet connection. Liquidity tokens enable the ability to exit from staking before this is enabled at the protocol level. If you're interested in these features, pooled staking may be a good fit.",
},
],
saas: [
{
...solo,
content:
"Similarities include having your own validator keys without having to pool funds, but with SaaS you must trust a third-party, who may potentially act maliciously or become a target of attack or regulation themselves. If these trust assumptions or centralization risks concern you, the gold standard of self-sovereign staking is solo staking.",
},
{
...pools,
content:
"These are similar in that you're generally relying on someone else to run the validator client, but unlike SaaS, pooled staking allows you to participate with smaller amounts of ETH. If you're looking to stake with less than 32 ETH, consider checking these out.",
},
],
pools: [
{
...solo,
content:
"Pooled staking has a significantly lower barrier to entry when compared to solo staking, but comes with additional risk by delegating all node operations to a third-party, and with a fee. Solo staking gives full sovereignty and control over the choices that go into choosing a staking setup. Stakers never have to hand over their keys, and they earn full rewards without any middlemen taking a cut.",
},
{
...saas,
content:
"These are similar in that stakers do not run the validator software themselves, but unlike pooling options, SaaS requires a full 32 ETH deposit to activate a validator. Rewards accumulate to the staker, and usually involve a monthly fee or other stake to use the service. If you'd prefer your own validator keys and are looking to stake at least 32 ETH, using a SaaS provider may be a good option for you.",
},
],
}
const selectedData = data[page]
return (
<GradientContainer className={className}>
<h2>Comparison with other options</h2>
{selectedData.map(
({ title, linkText, to, color, content, glyph, matomo }, idx) => (
<Flex key={idx}>
{!!glyph && <Glyph>{glyph}</Glyph>}
<div>
<h3 style={{ color }}>{title}</h3>
<p>{content}</p>
<Link
onClick={() => {
trackCustomEvent(matomo)
}}
to={to}
>
{linkText}
</Link>
</div>
</Flex>
)
)}
</GradientContainer>
)
}
export default StakingComparison
|
// Copyright (C) 2013 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 25.3.1.4
description: >
When a generator is paused within the `catch` block of a `try..catch`
statement, `throw` should interrupt control flow as if a `throw` statement
had appeared at that location in the function body.
features: [generators]
---*/
var unreachable = 0;
function* g() {
yield 1;
try {
yield 2;
throw exception;
} catch (e) {
yield e;
unreachable += 1;
}
yield 3;
}
var iter, result, exception;
exception = new Test262Error();
iter = g();
result = iter.next();
assert.sameValue(result.value, 1, 'First result `value`');
assert.sameValue(result.done, false, 'First result `done` flag');
result = iter.next();
assert.sameValue(result.value, 2, 'Second result `value`');
assert.sameValue(result.done, false, 'Second result `done` flag');
result = iter.next();
assert.sameValue(result.value, exception, 'Third result `value`');
assert.sameValue(result.done, false, 'Third result `done` flag');
assert.throws(Test262Error, function() {
iter.throw(new Test262Error());
});
assert.sameValue(
unreachable,
0,
'statement following `yield` not executed (following `throw`)'
);
result = iter.next();
assert.sameValue(
result.value, undefined, 'Result `value` is undefined when done'
);
assert.sameValue(result.done, true, 'Result `done` flag is `true` when done');
assert.sameValue(
unreachable, 0, 'statement following `yield` not executed (once "completed")'
);
iter.next();
|
let crypto = require('crypto');
let util = require('util');
let path = require('path');
let fs = require('fs');
let utils = module.exports;
/**
* Check and invoke callback
*/
utils.invokeCallback = function(cb) {
if (!!cb && typeof cb === 'function') {
cb.apply(null, Array.prototype.slice.call(arguments, 1));
}
};
/*
* Date format
*/
utils.format = function(date, format) {
format = format || 'MM-dd-hhmm';
let o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"h+": date.getHours(), //hour
"m+": date.getMinutes(), //minute
"s+": date.getSeconds(), //second
"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
"S": date.getMilliseconds() //millisecond
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1,
RegExp.$1.length === 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
};
utils.compareServer = function(server1, server2) {
return (server1['host'] === server2['host']) &&
(server1['port'] === server2['port']);
}
/**
* Get the count of elements of object
*/
utils.size = function(obj, type) {
let count = 0;
for (let i in obj) {
if (obj.hasOwnProperty(i) && typeof obj[i] !== 'function') {
if (!type) {
count++;
continue;
}
if (type && type === obj[i]['type']) {
count++;
}
}
}
return count;
};
utils.md5 = function(str) {
let md5sum = crypto.createHash('md5');
md5sum.update(str);
str = md5sum.digest('hex');
return str;
}
utils.defaultAuthUser = function(msg, env, cb) {
let adminUser = null;
let appBase = path.dirname(require.main.filename);
let adminUserPath = path.join(appBase, '/config/adminUser.json');
let presentPath = path.join(appBase, 'config', env, 'adminUser.json');
if (fs.existsSync(adminUserPath)) {
adminUser = require(adminUserPath);
} else if (fs.existsSync(presentPath)) {
adminUser = require(presentPath);
} else {
cb(null);
return;
}
let username = msg['username'];
let password = msg['password'];
let md5 = msg['md5'];
let len = adminUser.length;
if (md5) {
for (let i = 0; i < len; i++) {
let user = adminUser[i];
let p = "";
if (user['username'] === username) {
p = utils.md5(user['password']);
if (password === p) {
cb(user);
return;
}
}
}
} else {
for (let i = 0; i < len; i++) {
let user = adminUser[i];
if (user['username'] === username && user['password'] === password) {
cb(user);
return;
}
}
}
cb(null);
}
utils.defaultAuthServerMaster = function(msg, env, cb) {
let id = msg['id'];
let type = msg['serverType'];
let token = msg['token'];
if (type === 'master') {
cb('ok');
return;
}
let servers = null;
let appBase = path.dirname(require.main.filename);
let serverPath = path.join(appBase, '/config/adminServer.json');
let presentPath = null;
if (env) {
presentPath = path.join(appBase, 'config', env, 'adminServer.json');
}
if (fs.existsSync(serverPath)) {
servers = require(serverPath);
} else if (fs.existsSync(presentPath)) {
servers = require(presentPath);
} else {
cb('ok');
return;
}
let len = servers.length;
for (let i = 0; i < len; i++) {
let server = servers[i];
if (server['type'] === type && server['token'] === token) {
cb('ok');
return;
}
}
cb('bad');
return;
}
utils.defaultAuthServerMonitor = function(msg, env, cb) {
let id = msg['id'];
let type = msg['serverType'];
let servers = null;
let appBase = path.dirname(require.main.filename);
let serverPath = path.join(appBase, '/config/adminServer.json');
let presentPath = null;
if (env) {
presentPath = path.join(appBase, 'config', env, 'adminServer.json');
}
if (fs.existsSync(serverPath)) {
servers = require(serverPath);
} else if (fs.existsSync(presentPath)) {
servers = require(presentPath);
} else {
cb('ok');
return;
}
let len = servers.length;
for (let i = 0; i < len; i++) {
let server = servers[i];
if (server['type'] === type) {
cb(server['token']);
return;
}
}
cb(null);
return;
}
|
/****************************************************************************
Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var SCROLLVIEW_RES = [
"res/cocosui/UIEditorTest/UIScrollView_Editor/UIScrollView_Vertical_Editor/ui_scrollview_editor_1.json",
"res/cocosui/UIEditorTest/UIScrollView_Editor/UIScrollView_Horizontal_Editor/ui_scrollview_horizontal_editor_1.json",
"res/cocosui/UIEditorTest/UIScrollView_Editor/UIScrollView_Both_Editor/ui_scrollview_both_editor_1.json"
];
var SCROLLVIEW_INDEX = 0;
var UIScrollViewEditorTest = UIBaseLayer.extend({
ctor: function () {
this._super();
var root = ccs.uiReader.widgetFromJsonFile(SCROLLVIEW_RES[SCROLLVIEW_INDEX]);
this._mainNode.addChild(root);
var back_label = ccui.helper.seekWidgetByName(root, "back");
back_label.addTouchEventListener(this.backEvent, this);
var left_button = ccui.Button.create();
left_button.loadTextures("res/Images/b1.png", "res/Images/b2.png", "");
left_button.x = 240-50;
left_button.y = 50;
left_button.anchorX = 0.5;
left_button.anchorY = 0.5;
left_button.zOrder = 999;
left_button.addTouchEventListener(this.previousCallback, this);
this._mainNode.addChild(left_button);
var right_button = ccui.Button.create();
right_button.loadTextures("res/Images/f1.png", "res/Images/f2.png", "");
right_button.x = 240+50;
right_button.y = 50;
right_button.zOrder = 999;
right_button.anchorX = 0.5;
right_button.anchorY = 0.5;
right_button.addTouchEventListener(this.nextCallback, this);
this._mainNode.addChild(right_button);
},
previousCallback: function (render, type) {
if (type == ccui.Widget.TOUCH_ENDED) {
SCROLLVIEW_INDEX--;
if (SCROLLVIEW_INDEX < 0)SCROLLVIEW_INDEX = SCROLLVIEW_RES.length-1;
if (SCROLLVIEW_INDEX >= SCROLLVIEW_RES.length)SCROLLVIEW_INDEX = 0;
this.runNextScene();
}
},
nextCallback: function (render, type) {
if (type == ccui.Widget.TOUCH_ENDED) {
SCROLLVIEW_INDEX++;
if (SCROLLVIEW_INDEX < 0)SCROLLVIEW_INDEX = SCROLLVIEW_RES.length-1;
if (SCROLLVIEW_INDEX >= SCROLLVIEW_RES.length)SCROLLVIEW_INDEX = 0;
this.runNextScene();
}
},
runNextScene: function () {
var scene = cc.Scene.create();
scene.addChild(new UIScrollViewEditorTest());
cc.director.runScene(scene);
}
});
|
import axios from 'axios';
export function request(config) {
// axios实例
const instance = axios.create({
baseURL: '/api/',
timeout: 2000
})
return instance(config);
}
|
'use strict';
const supertest = require('supertest');
const defaultConf = require('./testDefaultConfig');
const testUtils = require('./testUtils');
const middleware = require('../lib/middleware');
exports.createServer = () => {
const app = middleware(defaultConf());
const httpServer = app.listen();
const request = supertest.agent(httpServer);
// There is currently a race condition with collection registering to mongoDb.
// @TODO fix the race condition and remove me
return testUtils.timeoutPromise(50)
.then(() => ({ request, close: () => testUtils.asPromise(cb => httpServer.close(cb)) }));
};
exports.getDocumentUrl = (db, collection, documentId) => `/db/${db}/${collection}/${JSON.stringify(documentId)}`;
|
const fs = require('fs')
const path = require('path')
const execa = require('execa')
describe('nuxt3-webpack', () => {
test('build works', async() => {
// Note: this is a hacky solution
await execa('yarn', ['run', 'nuxt', 'build'], { cwd: __dirname })
expect(fs.existsSync(path.join(__dirname, '.output', 'public'))).toBeTruthy()
})
})
|
import {
FETCH_PRODUCT_LIST,
FETCH_PRODUCT
} from './mutation-types'
import axios from 'axios'
export default {
fetchProductList ({ commit }) {
return axios.get('http://localhost:7777/vueproduct/list')
.then((res) => {
commit(FETCH_PRODUCT_LIST, res.data)
})
},
fetchProduct ({ commit }, board_no) {
return axios.get(`http://localhost:7777/vueproduct/${board_no}`)
.then((res) => {
commit(FETCH_PRODUCT, res.data)
})
}
}
|
const multer = require('multer');
const { v4: uuidv4 } = require("uuid");
const MIME_TYPE_MAP = {
"image/png": "png",
"image/jpeg": "jpeg",
"image/jpg": "jpg"
};
const fileUpload = multer({
limits: 500000, //max file size in bytes
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/images');
},
filename: (req, file, cb) => {
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, uuidv4() + '.' + ext);
}
}),
fileFilter: (req, file, cb) => {
const isValid = !!MIME_TYPE_MAP[file.mimetype];
let error = isValid ? null : new Error('Invalid mime type!');
cb(error, isValid);
}
});
module.exports = fileUpload;
|
const set = require('regenerate')(0xAA, 0xB5, 0xBA, 0x345, 0x37F, 0x386, 0x38C, 0x10C7, 0x10CD, 0x1F59, 0x1F5B, 0x1F5D, 0x1FBE, 0x2071, 0x207F, 0x2102, 0x2107, 0x2115, 0x2124, 0x2126, 0x2128, 0x2139, 0x214E, 0x2D27, 0x2D2D, 0x1D4A2, 0x1D4BB, 0x1D546);
set.addRange(0x41, 0x5A).addRange(0x61, 0x7A).addRange(0xC0, 0xD6).addRange(0xD8, 0xF6).addRange(0xF8, 0x1BA).addRange(0x1BC, 0x1BF).addRange(0x1C4, 0x293).addRange(0x295, 0x2B8).addRange(0x2C0, 0x2C1).addRange(0x2E0, 0x2E4).addRange(0x370, 0x373).addRange(0x376, 0x377).addRange(0x37A, 0x37D).addRange(0x388, 0x38A).addRange(0x38E, 0x3A1).addRange(0x3A3, 0x3F5).addRange(0x3F7, 0x481).addRange(0x48A, 0x52F).addRange(0x531, 0x556).addRange(0x560, 0x588).addRange(0x10A0, 0x10C5).addRange(0x10D0, 0x10FA).addRange(0x10FD, 0x10FF).addRange(0x13A0, 0x13F5).addRange(0x13F8, 0x13FD).addRange(0x1C80, 0x1C88).addRange(0x1C90, 0x1CBA).addRange(0x1CBD, 0x1CBF).addRange(0x1D00, 0x1DBF).addRange(0x1E00, 0x1F15).addRange(0x1F18, 0x1F1D).addRange(0x1F20, 0x1F45).addRange(0x1F48, 0x1F4D).addRange(0x1F50, 0x1F57).addRange(0x1F5F, 0x1F7D).addRange(0x1F80, 0x1FB4).addRange(0x1FB6, 0x1FBC).addRange(0x1FC2, 0x1FC4).addRange(0x1FC6, 0x1FCC).addRange(0x1FD0, 0x1FD3).addRange(0x1FD6, 0x1FDB).addRange(0x1FE0, 0x1FEC).addRange(0x1FF2, 0x1FF4).addRange(0x1FF6, 0x1FFC).addRange(0x2090, 0x209C).addRange(0x210A, 0x2113).addRange(0x2119, 0x211D).addRange(0x212A, 0x212D).addRange(0x212F, 0x2134).addRange(0x213C, 0x213F).addRange(0x2145, 0x2149);
set.addRange(0x2160, 0x217F).addRange(0x2183, 0x2184).addRange(0x24B6, 0x24E9).addRange(0x2C00, 0x2C2E).addRange(0x2C30, 0x2C5E).addRange(0x2C60, 0x2CE4).addRange(0x2CEB, 0x2CEE).addRange(0x2CF2, 0x2CF3).addRange(0x2D00, 0x2D25).addRange(0xA640, 0xA66D).addRange(0xA680, 0xA69D).addRange(0xA722, 0xA787).addRange(0xA78B, 0xA78E).addRange(0xA790, 0xA7BF).addRange(0xA7C2, 0xA7CA).addRange(0xA7F5, 0xA7F6).addRange(0xA7F8, 0xA7FA).addRange(0xAB30, 0xAB5A).addRange(0xAB5C, 0xAB68).addRange(0xAB70, 0xABBF).addRange(0xFB00, 0xFB06).addRange(0xFB13, 0xFB17).addRange(0xFF21, 0xFF3A).addRange(0xFF41, 0xFF5A).addRange(0x10400, 0x1044F).addRange(0x104B0, 0x104D3).addRange(0x104D8, 0x104FB).addRange(0x10C80, 0x10CB2).addRange(0x10CC0, 0x10CF2).addRange(0x118A0, 0x118DF).addRange(0x16E40, 0x16E7F).addRange(0x1D400, 0x1D454).addRange(0x1D456, 0x1D49C).addRange(0x1D49E, 0x1D49F).addRange(0x1D4A5, 0x1D4A6).addRange(0x1D4A9, 0x1D4AC).addRange(0x1D4AE, 0x1D4B9).addRange(0x1D4BD, 0x1D4C3).addRange(0x1D4C5, 0x1D505).addRange(0x1D507, 0x1D50A).addRange(0x1D50D, 0x1D514).addRange(0x1D516, 0x1D51C).addRange(0x1D51E, 0x1D539).addRange(0x1D53B, 0x1D53E).addRange(0x1D540, 0x1D544).addRange(0x1D54A, 0x1D550).addRange(0x1D552, 0x1D6A5).addRange(0x1D6A8, 0x1D6C0).addRange(0x1D6C2, 0x1D6DA).addRange(0x1D6DC, 0x1D6FA).addRange(0x1D6FC, 0x1D714);
set.addRange(0x1D716, 0x1D734).addRange(0x1D736, 0x1D74E).addRange(0x1D750, 0x1D76E).addRange(0x1D770, 0x1D788).addRange(0x1D78A, 0x1D7A8).addRange(0x1D7AA, 0x1D7C2).addRange(0x1D7C4, 0x1D7CB).addRange(0x1E900, 0x1E943).addRange(0x1F130, 0x1F149).addRange(0x1F150, 0x1F169).addRange(0x1F170, 0x1F189);
module.exports = set;
|
#! usr/bin/env python3
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Arguments:
suffix {[str]} -- [suffix if the file name to be found]
path {[str]} -- [path of the file system]
Returns:
[str] -- [a list of paths]
"""
if suffix == "":
return []
if not os.path.isdir(path):
return "Invalid Directory"
dir_paths = os.listdir(path)
if dir_paths:
dir_folders = [file for file in dir_paths if str(".") not in file]
dir_files = [file for file in dir_paths if str("." + suffix) in file]
for folder in dir_folders:
dir_files.extend(find_files(suffix, os.path.join(path, folder)))
return dir_files
def main():
root_path = os.getcwd() + "/testdir"
print(find_files("", root_path))
print(find_files("c", root_path))
print(find_files("h", root_path))
print(find_files("x", root_path))
path = "./solution/problem2/problem2.py"
suffix = ".py"
print(find_files(path, suffix))
if __name__ == "__main__":
main()
|
! function(a) {
"function" == typeof define && define.amd ? define(["jquery", "moment"], a) : "object" == typeof exports ? module.exports = a(require("jquery"), require("moment")) : a(jQuery, moment)
}(function(a, e) {
! function() {
var a = {
1: "'inci",
5: "'inci",
8: "'inci",
70: "'inci",
80: "'inci",
2: "'nci",
7: "'nci",
20: "'nci",
50: "'nci",
3: "'üncü",
4: "'üncü",
100: "'üncü",
6: "'ncı",
9: "'uncu",
10: "'uncu",
30: "'uncu",
60: "'ıncı",
90: "'ıncı"
};
e.defineLocale("tr", {
months: "Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"),
monthsShort: "Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"),
weekdays: "Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"),
weekdaysShort: "Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"),
weekdaysMin: "Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"),
longDateFormat: {
LT: "HH:mm",
LTS: "HH:mm:ss",
L: "DD.MM.YYYY",
LL: "D MMMM YYYY",
LLL: "D MMMM YYYY HH:mm",
LLLL: "dddd, D MMMM YYYY HH:mm"
},
calendar: {
sameDay: "[bugün saat] LT",
nextDay: "[yarın saat] LT",
nextWeek: "[haftaya] dddd [saat] LT",
lastDay: "[dün] LT",
lastWeek: "[geçen hafta] dddd [saat] LT",
sameElse: "L"
},
relativeTime: {
future: "%s sonra",
past: "%s önce",
s: "birkaç saniye",
m: "bir dakika",
mm: "%d dakika",
h: "bir saat",
hh: "%d saat",
d: "bir gün",
dd: "%d gün",
M: "bir ay",
MM: "%d ay",
y: "bir yıl",
yy: "%d yıl"
},
dayOfMonthOrdinalParse: /\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/,
ordinal: function(e) {
if (0 === e) return e + "'ıncı";
var t = e % 10,
n = e % 100 - t,
i = e >= 100 ? 100 : null;
return e + (a[t] || a[n] || a[i])
},
week: {
dow: 1,
doy: 7
}
})
}(), a.fullCalendar.datepickerLocale("tr", "tr", {
closeText: "kapat",
prevText: "<geri",
nextText: "ileri>",
currentText: "bugün",
monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
monthNamesShort: ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"],
dayNames: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"],
dayNamesShort: ["Pz", "Pt", "Sa", "Ça", "Pe", "Cu", "Ct"],
dayNamesMin: ["Pz", "Pt", "Sa", "Ça", "Pe", "Cu", "Ct"],
weekHeader: "Hf",
dateFormat: "dd.mm.yy",
firstDay: 1,
isRTL: !1,
showMonthAfterYear: !1,
yearSuffix: ""
}), a.fullCalendar.locale("tr", {
buttonText: {
next: "ileri",
month: "Ay",
week: "Hafta",
day: "Gün",
list: "Ajanda"
},
allDayText: "Tüm gün",
eventLimitText: "daha fazla",
noEventsMessage: "Herhangi bir etkinlik görüntülemek için"
})
});
|
# coding: utf-8
"""
No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
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 pprint import pformat
from six import iteritems
import re
class V1ConfigMap(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, kind=None, apiVersion=None, metadata=None, data=None):
"""
V1ConfigMap - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'kind': 'str',
'apiVersion': 'str',
'metadata': 'V1ObjectMeta',
'data': 'object'
}
self.attribute_map = {
'kind': 'kind',
'apiVersion': 'apiVersion',
'metadata': 'metadata',
'data': 'data'
}
self._kind = kind
self._apiVersion = apiVersion
self._metadata = metadata
self._data = data
@property
def kind(self):
"""
Gets the kind of this V1ConfigMap.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
:return: The kind of this V1ConfigMap.
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""
Sets the kind of this V1ConfigMap.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
:param kind: The kind of this V1ConfigMap.
:type: str
"""
self._kind = kind
@property
def apiVersion(self):
"""
Gets the apiVersion of this V1ConfigMap.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
:return: The apiVersion of this V1ConfigMap.
:rtype: str
"""
return self._apiVersion
@apiVersion.setter
def apiVersion(self, apiVersion):
"""
Sets the apiVersion of this V1ConfigMap.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources
:param apiVersion: The apiVersion of this V1ConfigMap.
:type: str
"""
self._apiVersion = apiVersion
@property
def metadata(self):
"""
Gets the metadata of this V1ConfigMap.
Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
:return: The metadata of this V1ConfigMap.
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""
Sets the metadata of this V1ConfigMap.
Standard object's metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
:param metadata: The metadata of this V1ConfigMap.
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def data(self):
"""
Gets the data of this V1ConfigMap.
Data contains the configuration data. Each key must be a valid DNS_SUBDOMAIN with an optional leading dot.
:return: The data of this V1ConfigMap.
:rtype: object
"""
return self._data
@data.setter
def data(self, data):
"""
Sets the data of this V1ConfigMap.
Data contains the configuration data. Each key must be a valid DNS_SUBDOMAIN with an optional leading dot.
:param data: The data of this V1ConfigMap.
:type: object
"""
self._data = data
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
import tensorflow as tf
import numpy as np
from layers import *
from support import visualize_images
from global_definitions import *
def apply_gradient_descent(var_list, obj):
"""
Sets up the gradient descent optimizer
Args:
var_list: List of variables to optimizer over.
obj: Node of the objective to minimize
Notes:
learning_rate: What learning rate to run with. (Default = ``0.01``) Set with ``LR``
"""
back_prop = tf.train.GradientDescentOptimizer(
learning_rate = LR,
name = 'gradient_descent' ).minimize(loss = obj, \
var_list = var_list )
return back_prop
def apply_adam (var_list, obj, learning_rate = 1e-4):
"""
Sets up the ADAM optimizer
Args:
var_list: List of variables to optimizer over.
obj: Node of the objective to minimize
Notes:
learning_rate: What learning rate to run with. (Default = ``0.01``) Set with ``LR``
"""
back_prop = tf.train.AdamOptimizer(
learning_rate = LR,
name = 'adam' ).minimize(loss = obj, \
var_list = var_list)
return back_prop
def apply_rmsprop( var_list, obj ):
"""
Sets up the RMS Prop optimizer
Args:
var_list: List of variables to optimizer over.
obj: Node of the objective to minimize
Notes:
* learning_rate: What learning rate to run with. (Default = ``0.001``). Set ``LR``
* momentum: What is the weight for momentum to run with. (Default = ``0.7``). Set ``MOMENTUM``
* decay: What rate should learning rate decay. (Default = ``0.95``). Set ``DECAY``
"""
back_prop = tf.train.RMSPropOptimizer(
learning_rate = LR,
decay = DECAY,
momentum = MOMENTUM,
name = 'rmsprop' ).minimize(loss = obj, \
var_list = var_list)
return back_prop
def apply_weight_decay (var_list, name = 'weight_decay'):
"""
This method applies L2 Regularization to all weights and adds it to the ``objectives``
collection.
Args:
name: For the tensorflow scope.
var_list: List of variables to apply.
Notes:
What is the co-efficient of the L2 weight? Set ``WEIGHT_DECAY_COEFF``.( Default = 0.0001 )
"""
for param in var_list:
norm = WEIGHT_DECAY_COEFF * tf.nn.l2_loss(param)
tf.summary.scalar('l2_' + param.name, norm)
tf.add_to_collection('objectives', norm)
def apply_l1 ( var_list, name = 'l1'):
"""
This method applies L1 Regularization to all weights and adds it to the ``objectives``
collection.
Args:
var_list: List of variables to apply l1
name: For the tensorflow scope.
Notes:
What is the co-efficient of the L1 weight? Set ``L1_COEFF``.( Default = 0.0001 )
"""
for param in var_list:
norm = L1_COEFF * tf.reduce_sum(tf.abs(param, name = 'abs'), name = 'l1')
tf.summary.scalar('l1_' + param.name, norm)
tf.add_to_collection( 'objectives', norm)
def process_params(params):
"""
This method adds the params to two collections.
The first element is added to ``regularizer_worthy_params``.
The first and second elements are is added to ``trainable_parmas``.
Args:
params: List of two.
"""
tf.add_to_collection( 'trainable_params', params[0])
tf.add_to_collection( 'trainable_params', params[1])
tf.add_to_collection('regularizer_worthy_params', params[0])
def apply_regularizer ( var_list):
"""
This method applyies Regularization to all weights and adds it to the ``objectives``
collection.
Args:
var_list: List of variables to apply l1
Notes:
What is the co-efficient of the L1 weight? Set ``L1_COEFF``.( Default = 0.0001 )
"""
with tf.variable_scope( 'weight-decay') as scope:
if WEIGHT_DECAY_COEFF > 0:
apply_weight_decay(name = 'weight_decay', var_list = var_list )
with tf.variable_scope( 'l1-regularization') as scope:
if L1_COEFF > 0:
apply_l1(name = 'weight_decay', var_list = var_list)
class lenet5(object):
"""
Definition of the lenet class of networks.
Notes:
* Produces the lenet model and returns the weights. A typical lenet has
two convolutional layers with filters sizes ``5X5`` and ``3X3``. These
are followed by two fully-connected layers and a softmax layer. This
network model, reproduces this network to be trained on MNIST images
of size ``28X28``.
* Most of the important parameters are stored in :mod:`global_definitions`
in the file ``global_definitions.py``.
Args:
images: Placeholder for images
Attributes:
images: This is the placeholder for images. This needs to be fed in from :class:`lenet.dataset.mnist``.
dropout_prob: This is also a placeholder for dropout probability. This needs to be fed in.
logits: Output node of the softmax layer, before softmax. This is an output from a
:meth:`lenet.layers.dot_product_layer`.
inference: Output node of the softmax layer that produces inference.
predictions: Its a predictions node which is :meth:`tf.nn.argmax` of ``inference``.
back_prop: Backprop is an optimizer. This is a node that will be used by a :class:`lenet.trainer.trainer` later.
obj: Is a cumulative objective tensor. This produces the total summer objective in a node.
cost: Cost of the back prop error alone.
labels: Placeholder for labels, needs to be fed in. This is added fed in from the dataset class.
accuracy: Tensor for accuracy. This is a node that measures the accuracy for the mini batch.
"""
def __init__ ( self,
images ):
"""
Class constructor. Creates the model and allthe connections.
"""
self.images = images
# Unflatten Layer
images_square = unflatten_layer ( self.images )
visualize_images(images_square)
# Conv Layer 1
conv1_out, params = conv_2d_layer ( input = images_square,
neurons = C1,
filter_size = F1,
name = 'conv_1',
visualize = True )
process_params(params)
pool1_out = max_pool_2d_layer ( input = conv1_out, name = 'pool_1')
lrn1_out = local_response_normalization_layer (pool1_out, name = 'lrn_1' )
# Conv Layer 2
conv2_out, params = conv_2d_layer ( input = lrn1_out,
neurons = C2,
filter_size = F2,
name = 'conv_2' )
process_params(params)
pool2_out = max_pool_2d_layer ( input = conv2_out, name = 'pool_2')
lrn2_out = local_response_normalization_layer (pool2_out, name = 'lrn_2' )
flattened = flatten_layer(lrn2_out)
# Placeholder probability for dropouts.
self.dropout_prob = tf.placeholder(tf.float32,
name = 'dropout_probability')
# Dropout Layer 1
flattened_dropout = dropout_layer ( input = flattened,
prob = self.dropout_prob,
name = 'dropout_1')
# Dot Product Layer 1
fc1_out, params = dot_product_layer ( input = flattened_dropout,
neurons = D1,
name = 'dot_1')
process_params(params)
# Dropout Layer 2
fc1_out_dropout = dropout_layer ( input = fc1_out,
prob = self.dropout_prob,
name = 'dropout_2')
# Dot Product Layer 2
fc2_out, params = dot_product_layer ( input = fc1_out_dropout,
neurons = D2,
name = 'dot_2')
process_params(params)
# Dropout Layer 3
fc2_out_dropout = dropout_layer ( input = fc2_out,
prob = self.dropout_prob,
name = 'dropout_3')
# Logits layer
self.logits, params = dot_product_layer ( input = fc2_out_dropout,
neurons = C,
activation = 'identity',
name = 'logits_layer')
process_params(params)
# Softmax layer
self.inference, self.predictions = softmax_layer ( input = self.logits,
name = 'softmax_layer' )
def cook(self, labels):
"""
Prepares the network for training
Args:
labels: placeholder for labels
Notes:
* Each optimizer has a lot parameters that, if you want to change, modify in the code
directly. Most do not take in inputs and runs. Some parameters such as learning rates
play a significant role in learning and are good choices to experiment with.
* what optimizer to run with. (Default = ``sgd``), other options include
'rmsprop' and 'adam'. Set ``OPTIMIZER``
"""
with tf.variable_scope('objective') as scope:
self.labels = labels
with tf.variable_scope('cross-entropy') as scope:
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits (
labels = self.labels,
logits = self.logits)
)
self.cost = loss
tf.add_to_collection('objectives', loss )
tf.summary.scalar('cost', loss)
apply_regularizer (var_list = tf.get_collection( 'regularizer_worthy_params') )
self.obj = tf.add_n(tf.get_collection('objectives'), name='objective')
tf.summary.scalar('obj', self.obj)
with tf.variable_scope('train') as scope:
# Change (supply as arguments) parameters here directly in the code.
if OPTIMIZER == 'sgd':
self.back_prop = apply_gradient_descent(var_list = tf.get_collection( \
'trainable_params'),
obj = self.obj )
elif OPTIMIZER == 'rmsprop':
self.back_prop = apply_rmsprop(var_list = tf.get_collection( \
'trainable_params') ,
obj = self.obj)
elif OPTIMIZER == 'adam':
self.back_prop = apply_adam (var_list = tf.get_collection( \
'trainable_params') ,
obj = self.obj )
else:
raise Error('Invalid entry to optimizer')
with tf.variable_scope('test') as scope:
correct_predictions = tf.equal(self.predictions, tf.argmax(self.labels, 1), \
name = 'correct_predictions')
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32) , name ='accuracy')
tf.summary.scalar('accuracy', self.accuracy)
with tf.variable_scope("confusion"):
confusion = tf.confusion_matrix(tf.argmax(self.labels,1), self.predictions,
num_classes=C,
name='confusion')
confusion_image = tf.reshape( tf.cast( confusion, tf.float32),[1, C, C, 1])
tf.summary.image('confusion',confusion_image)
|
# -*- coding: utf-8 -*-
import pymongo
from modularodm import fields
from framework.auth.core import Auth
from website.addons.base import exceptions
from website.addons.base import AddonUserSettingsBase, AddonNodeSettingsBase, GuidFile
from website.addons.base import StorageAddonBase
from website.addons.s3 import utils
class S3GuidFile(GuidFile):
__indices__ = [
{
'key_or_list': [
('node', pymongo.ASCENDING),
('path', pymongo.ASCENDING),
],
'unique': True,
}
]
path = fields.StringField(index=True)
@property
def waterbutler_path(self):
return '/' + self.path
@property
def provider(self):
return 's3'
@property
def version_identifier(self):
return 'version'
@property
def unique_identifier(self):
return self._metadata_cache['extra']['md5']
class AddonS3UserSettings(AddonUserSettingsBase):
access_key = fields.StringField()
secret_key = fields.StringField()
def to_json(self, user):
ret = super(AddonS3UserSettings, self).to_json(user)
ret['has_auth'] = self.has_auth
if self.owner:
ret['name'] = self.owner.display_full_name()
ret['profile_url'] = self.owner.profile_url
return ret
@property
def has_auth(self):
return bool(self.access_key and self.secret_key)
@property
def is_valid(self):
return utils.can_list(self.access_key, self.secret_key)
def revoke_auth(self, auth=None, save=False):
for node_settings in self.addons3nodesettings__authorized:
node_settings.deauthorize(auth=auth, save=True)
self.s3_osf_user, self.access_key, self.secret_key = None, None, None
if save:
self.save()
return True
class AddonS3NodeSettings(StorageAddonBase, AddonNodeSettingsBase):
bucket = fields.StringField()
user_settings = fields.ForeignField(
'addons3usersettings', backref='authorized'
)
@property
def folder_name(self):
return self.bucket
def find_or_create_file_guid(self, path):
path = path.lstrip('/')
return S3GuidFile.get_or_create(node=self.owner, path=path)
@property
def display_name(self):
return u'{0}: {1}'.format(self.config.full_name, self.bucket)
@property
def complete(self):
return self.has_auth and self.bucket is not None
def authorize(self, user_settings, save=False):
self.user_settings = user_settings
self.owner.add_log(
action='s3_node_authorized',
params={
'project': self.owner.parent_id,
'node': self.owner._id,
},
auth=Auth(user_settings.owner),
)
if save:
self.save()
def deauthorize(self, auth=None, log=True, save=False):
self.bucket, self.user_settings = None, None
if log:
self.owner.add_log(
action='s3_node_deauthorized',
params={
'project': self.owner.parent_id,
'node': self.owner._id,
},
auth=auth,
)
if save:
self.save()
def delete(self, save=True):
self.deauthorize(log=False, save=False)
super(AddonS3NodeSettings, self).delete(save=save)
def serialize_waterbutler_credentials(self):
if not self.has_auth:
raise exceptions.AddonError('Cannot serialize credentials for S3 addon')
return {
'access_key': self.user_settings.access_key,
'secret_key': self.user_settings.secret_key,
}
def serialize_waterbutler_settings(self):
if not self.bucket:
raise exceptions.AddonError('Cannot serialize settings for S3 addon')
return {'bucket': self.bucket}
def create_waterbutler_log(self, auth, action, metadata):
url = self.owner.web_url_for('addon_view_or_download_file', path=metadata['path'], provider='s3')
self.owner.add_log(
's3_{0}'.format(action),
auth=auth,
params={
'project': self.owner.parent_id,
'node': self.owner._id,
'path': metadata['materialized'],
'bucket': self.bucket,
'urls': {
'view': url,
'download': url + '?action=download'
}
},
)
def to_json(self, user):
ret = super(AddonS3NodeSettings, self).to_json(user)
user_settings = user.get_addon('s3')
ret.update({
'bucket': self.bucket or '',
'has_bucket': self.bucket is not None,
'user_is_owner': (
self.user_settings and self.user_settings.owner == user
),
'user_has_auth': bool(user_settings) and user_settings.has_auth,
'node_has_auth': self.has_auth,
'owner': None,
'bucket_list': None,
'valid_credentials': user_settings and user_settings.is_valid,
})
if self.has_auth:
ret['owner'] = self.user_settings.owner.fullname
ret['owner_url'] = self.user_settings.owner.url
ret['node_has_auth'] = True
return ret
@property
def has_auth(self):
return bool(self.user_settings and self.user_settings.has_auth)
#TODO Update callbacks
def before_register(self, node, user):
"""
:param Node node:
:param User user:
:return str: Alert message
"""
category = node.project_or_component
if self.user_settings and self.user_settings.has_auth:
return (
u'The contents of S3 add-ons cannot be registered at this time; '
u'the S3 bucket linked to this {category} will not be included '
u'as part of this registration.'
).format(**locals())
def after_fork(self, node, fork, user, save=True):
"""
:param Node node: Original node
:param Node fork: Forked node
:param User user: User creating fork
:param bool save: Save settings after callback
:return tuple: Tuple of cloned settings and alert message
"""
clone, _ = super(AddonS3NodeSettings, self).after_fork(
node, fork, user, save=False
)
# Copy authentication if authenticated by forking user
if self.user_settings and self.user_settings.owner == user:
clone.user_settings = self.user_settings
clone.bucket = self.bucket
message = (
'Amazon Simple Storage authorization copied to forked {cat}.'
).format(
cat=fork.project_or_component,
)
else:
message = (
'Amazon Simple Storage authorization not copied to forked {cat}. You may '
'authorize this fork on the <a href={url}>Settings</a> '
'page.'
).format(
cat=fork.project_or_component,
url=fork.url + 'settings/'
)
if save:
clone.save()
return clone, message
def before_fork(self, node, user):
"""
:param Node node:
:param User user:
:return str: Alert message
"""
if self.user_settings and self.user_settings.owner == user:
return (
'Because you have authenticated the S3 add-on for this '
'{cat}, forking it will also transfer your authorization to '
'the forked {cat}.'
).format(
cat=node.project_or_component,
)
return (
'Because this S3 add-on has been authenticated by a different '
'user, forking it will not transfer authentication to the forked '
'{cat}.'
).format(
cat=node.project_or_component,
)
def before_remove_contributor(self, node, removed):
"""
:param Node node:
:param User removed:
:return str: Alert message
"""
if self.user_settings and self.user_settings.owner == removed:
return (
'The Amazon Simple Storage add-on for this {category} is authenticated '
'by {user}. Removing this user will also remove access '
'to {bucket} unless another contributor re-authenticates.'
).format(
category=node.project_or_component,
user=removed.fullname,
bucket=self.bucket
)
def after_remove_contributor(self, node, removed, auth=None):
"""
:param Node node:
:param User removed:
:return str: Alert message
"""
if self.user_settings and self.user_settings.owner == removed:
self.user_settings = None
self.bucket = None
self.save()
message = (
u'Because the Amazon Simple Storage add-on for {category} "{title}" was '
u'authenticated by {user}, authentication information has been deleted.'
).format(category=node.category_display, title=node.title, user=removed.fullname)
if not auth or auth.user != removed:
url = node.web_url_for('node_setting')
message += (
u' You can re-authenticate on the <a href="{url}">Settings</a> page.'
).format(url=url)
#
return message
def after_delete(self, node, user):
self.deauthorize(Auth(user=user), log=True, save=True)
|
const elements = [
'animate',
'circle',
'defs',
'ellipse',
'g',
'line',
'linearGradient',
'mask',
'path',
'pattern',
'polygon',
'polyline',
'radialGradient',
'rect',
'stop',
'svg',
'text',
'tspan',
];
export default name => elements.indexOf(name) !== -1;
|
function sensor(str){
return str.replace(/##/g,"--")
.replace(/system/g,"printf")
.replace(/freopen/g,"")
.replace(/fstream/g,"")
.replace(/windows.h/g,"")
.replace(/CON/g,"")
}
module.exports = {
sensor
};
|
# -*- coding: utf-8 -*-
import torch
from abc import abstractmethod
from torch.utils.tensorboard.writer import SummaryWriter
# from tensorboardX import SummaryWriter # use this if pytorch <= 1.2
def func(m):
m = torch.nn.DataParallel(m, device_ids=[0, 1])
return m
class BaseTrainer:
"""
Base class for all trainers
"""
def __init__(self, model, loss, metrics, optimizer, config, device=None):
self.config = config
if type(device) == int:
self.device = torch.device("cuda:{}".format(device))
self.device_id = device
else:
self.device = device
self.model = model.to(self.device)
self.loss = loss
if metrics:
self.metrics = metrics
self.has_metric = True
else:
self.has_metric = False
self.optimizer = optimizer
self.start_epoch = 1
self.epochs = config.num_epochs
assert config.save_dir is not None
self.save_dir = config.save_dir
self.vis_train_dir = config.vis_train_dir
self.generated_dir = config.generated_dir
# setup visualization writer instance
self.writer = SummaryWriter(self.save_dir, max_queue=10)
@abstractmethod
def _train_epoch(self, epoch):
"""
Training logic for an epoch
example return:
result = {
'loss': 0.0,
'metric': 1.0,
}
"""
raise NotImplementedError
@abstractmethod
def train(self):
""" Main training loop contained
E.g.
for epoch in range(self.start_epoch, self.epochs + 1):
result = self._train_epoch(epoch)
printing ...(result)
if epoch % self.save_period == 0:
self._save_checkpoint(epoch)
"""
raise NotImplementedError
def _prepare_device(self, use_gpu=[]):
raise NotImplementedError
def _save_checkpoint(self, epoch):
"""
Saving checkpoints
:param epoch: current epoch number
:param log: logging information of the epoch
:param save_best: if True, rename the saved checkpoint to 'model_best.pth'
"""
raise NotImplementedError
def _resume_checkpoint(self, resume_path):
"""
Resume from saved checkpoints
:param resume_path: Checkpoint path to be resumed
"""
raise NotImplementedError
|
import argparse
#from carla_game.carla_benchmark import CarlaBenchmark as CarlaEnv
from carla_game.carla_gamev09 import CarlaEnv
from common.utills import print_square
from model.test_agents import mathDriver, randomDriver, crashDriver
'''
"ClearNoon",
"WetCloudyNoon",
"MidRainyNoon",
"ClearSunset",
"WetCloudySunset",
"MidRainSunset"
'''
def get_sample_image():
city_names = [
'Offroad_1',
'Offroad_2',
'Offroad_3',
'Offroad_4',
'Offroad_5',
'Offroad_6',
'Offroad_7',
'Offroad_8'
]
weathers = [
"ClearNoon",
"WetCloudyNoon",
"MidRainyNoon",
"ClearSunset",
"WetCloudySunset",
"MidRainSunset"
]
for city_name in city_names:
for i, weather in enumerate(weathers):
env = CarlaEnv(
log_dir='./CarlaLog.txt',
render=False,
plot=False,
server_size=(4, 3),
city_name=city_name,
weather=weather,
is_image_state=False
)
if i==0:
init_pos = env.init_pos
init_state = env.init_state
else:
env.init_pos = init_pos
env.init_state = init_state
state = env.reset(reset_position=False)
def main(args):
'''make environment'''
env = CarlaEnv(
log_dir='./CarlaLog.txt',
render=args.render,
render_gcam=False,
plot=args.plot,
server_size=(4, 3),
city_name=args.city_name,
weather=args.weather,
is_image_state=False
)
#agent = crashDriver()
agent = mathDriver(speed_limits = [5, 6])
'''verbose'''
verbose = {}
for key in vars(args):
verbose[key] = getattr(args, key)
print_square(verbose)
'''main loop'''
total_step = 0
total_reward = 0
try:
for episode in range(args.max_episode):
state = env.reset()
episode_reward = 0
step = 0
done = False
while not done:
step += 1
if args.render:
if episode % 100 == 0:
env.render(save=False, step=step, model="None")
else:
env.render()
action = agent.get_action(state)
next_state, reward, done, _ = env.step(action)
rgb_image, _, _ = env.get_full_observation()
next_obs = next_state
total_step += 1
episode_reward += reward
state = next_state
print_square({
"reward": reward,
"steering": action[1],
"throttle": action[0],
"speed": env.epinfos["speed"],
"track_width": env.epinfos["track_width"],
"mileage": env.epinfos["mileage"],
"distance_from_center": env.epinfos["distance_from_center"],
"current_step": env.epinfos["current_step"],
"is_collision": env.epinfos["is_collision"],
})
if total_step > args.max_step:
break
total_reward += episode_reward
print("#{}-th Episode, Total_Reward {}".format(episode, episode_reward))
except KeyboardInterrupt:
print("KeyboardInterrupt")
finally:
env.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--city-name', default='Offroad_1', type=str)
parser.add_argument('--weather', default='ClearNoon', type=str)
parser.add_argument('--max-episode', default=1, type=int)
parser.add_argument('--max-step', default=1000, type=int)
args = parser.parse_args()
args.render = True
args.plot = False
main(args)
#get_sample_image()
|
var group__group__smartio__functions__du =
[
[ "Cy_SmartIO_GetDuTr", "group__group__smartio__functions__du.html#gae59c99daba955d9d9e03ab439b59aaae", null ],
[ "Cy_SmartIO_SetDuTr", "group__group__smartio__functions__du.html#ga2791a66b980fdcc2e10703c5f16bb26d", null ],
[ "Cy_SmartIO_SetDuTrAll", "group__group__smartio__functions__du.html#gacb4f7bfb6ade46d6edd68f90e7af9f75", null ],
[ "Cy_SmartIO_GetDuData", "group__group__smartio__functions__du.html#ga3bafd4cf984805bf343944e07bf32643", null ],
[ "Cy_SmartIO_SetDuData", "group__group__smartio__functions__du.html#ga40f9d9ba8ffe672324e60a51c04bd804", null ],
[ "Cy_SmartIO_GetDuOpc", "group__group__smartio__functions__du.html#gaefd76726e13bee514024cbf7d4ebb553", null ],
[ "Cy_SmartIO_GetDuSize", "group__group__smartio__functions__du.html#ga3b9caf1e87da8d3872ab2449913efb94", null ],
[ "Cy_SmartIO_SetDuOperation", "group__group__smartio__functions__du.html#ga62b8df937119b494d51ada12398b2551", null ],
[ "Cy_SmartIO_GetDataReg", "group__group__smartio__functions__du.html#gab1340a5e9102399b87eb497c75db9680", null ],
[ "Cy_SmartIO_SetDataReg", "group__group__smartio__functions__du.html#ga392876b5a82279207eef1c5929e6123b", null ]
];
|
function Star(ra, dec, mag, name) {
this.ra = ra;
this.dec = dec;
this.mag = mag;
this.name = name;
if(mag<0) { this.size=4.5; }
else if(mag < 1) { this.size=4; }
else if(mag < 2) { this.size=3.5; }
else if(mag < 3) { this.size=3; }
else if(mag < 4) { this.size=2; }
else if(mag < 5) { this.size=1.5; }
else { this.size=1; };
this.calcHourAngle = function(lst, ra){
this.HourAngle = lst - ra*15;
//Set to between 0 and 360
if(this.HourAngle < 0) {
this.HourAngle += 360;
} else if(this.HourAngle >360) {
this.HourAngle - 360;
}
}
this.calcAltitude = function(dec, lat) {
this.altitude = rad2Deg(Math.asin(Math.sin(deg2Rad(dec))*Math.sin(deg2Rad(lat)) + Math.cos(deg2Rad(dec)) * Math.cos(deg2Rad(lat)) * Math.cos(deg2Rad(this.HourAngle))));
}
this.calcAzimuth = function(alt, dec, lat) {
var a = rad2Deg(Math.acos((Math.sin(deg2Rad(dec)) - Math.sin(deg2Rad(alt))*Math.sin(deg2Rad(lat)))/(Math.cos(deg2Rad(alt))*Math.cos(deg2Rad(lat)))));
if(Math.sin(deg2Rad(this.HourAngle)) <0) {
this.Azimuth = a;
} else {
this.Azimuth = 360-a;
}
}
this.calcAltAz = function(lat,log,lst) {
this.calcHourAngle(lst, this.ra);
this.calcAltitude(this.dec, lat, this.hourAngle);
this.calcAzimuth(this.altitude, this.dec, lat, this.hourAngle);
}
this.calcXY = function(lat,log,lst,r) {
this.calcAltAz(lat,log,lst);
var polarDist = (90 - this.altitude)/90;
var polarAngle = 0;
if(-(this.Azimuth - 90) < 0) { polarAngle = -(this.Azimuth - 90) + 360; }
else { polarAngle = -(this.Azimuth - 90); }
this.x = Math.cos(deg2Rad(polarAngle)) * polarDist * r;
this.y = Math.sin(deg2Rad(polarAngle)) * polarDist * r;
}
}
|
#basit shape detection
# kare ile dikdortgeni ayirt eder
#video uzerinde tespit yapar
import cv2 as cv
cap = cv.VideoCapture('dene.mp4')
ret, frame1 = cap.read()
ret, frame2 = cap.read()
while cap.isOpened() :
gray = cv.cvtColor(frame1, cv.COLOR_BGR2GRAY)
__, thresh = cv.threshold(gray, 110, 255, cv.THRESH_BINARY)
contours, __ = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
for contour in contours:
if cv.contourArea(contour) < 100:
continue
approx = cv.approxPolyDP(contour, 0.01 * cv.arcLength(contour, True), True)
cv.drawContours(frame1, [approx], 0, (0), 3, cv.LINE_4)
x = approx.ravel()[0]
y = approx.ravel()[1]
if len(approx) == 3:
cv.putText(frame1, 'triangle', (x, y - 15), cv.FONT_HERSHEY_SIMPLEX, 1, (0), 2)
elif len(approx) == 4:
(x1, y1, width, height) = cv.boundingRect(contour)
ratio = float(width / height)
if ratio > 0.95 and ratio < 1.1:
cv.putText(frame1, 'square', (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
else:
cv.putText(frame1, 'reqtangle', (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
elif len(approx) == 5:
cv.putText(frame1, 'pentagon', (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
elif len(approx) == 5:
cv.putText(frame1, 'pentagon', (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
elif len(approx) == 6:
cv.putText(frame1, 'hexagon', (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
elif len(approx) == 7:
cv.putText(frame1, 'octav', (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
elif len(approx) == 10:
cv.putText(frame1, 'star', (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0), 2)
else :
cv.putText(frame1, 'cicle', (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0), 2)
cv.imshow('shape_detection', frame1)
frame1 = frame2
ret, frame2 = cap.read()
key = cv.waitKey(40) & 0xFF
if key == 27:
break
cv.destroyAllWindows()
cap.release()
|
class GenericTracker {
static forPhase(game, startingEvent) {
return new GenericTracker(game, startingEvent, 'onPhaseEnded');
}
constructor(game, startingEvent, endingEvent) {
this.events = [];
game.on(startingEvent, event => this.trackEvent(event));
game.on(endingEvent, () => this.clearEvents());
}
trackEvent(event) {
this.events.push(event);
}
clearEvents() {
this.events = [];
}
}
module.exports = GenericTracker;
|
module.exports = {"344":{"id":"344","parentId":"28","name":"\u62c9\u8428"},"345":{"id":"345","parentId":"28","name":"\u963f\u91cc"},"346":{"id":"346","parentId":"28","name":"\u660c\u90fd"},"347":{"id":"347","parentId":"28","name":"\u6797\u829d"},"348":{"id":"348","parentId":"28","name":"\u90a3\u66f2"},"349":{"id":"349","parentId":"28","name":"\u65e5\u5580\u5219"},"350":{"id":"350","parentId":"28","name":"\u5c71\u5357"}};
|
"""Role testing files using testinfra."""
def test_is_postgresql_runnnig_and_enabled(host):
postgresql = host.service('postgresql')
assert postgresql.is_running
assert postgresql.is_enabled
|
module.exports = function(grunt) {
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
compass: {
files: ['public/sass/{,*/}*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer']
},
js: {
files: ['public/js/**', 'app/**/*.js'],
tasks: [],
options: {
livereload: true,
},
},
html: {
files: ['public/views/**'],
options: {
livereload: true,
},
},
css: {
files: ['public/css/**'],
options: {
livereload: true
}
}
},
compass: {
options: {
sassDir: 'public/sass',
cssDir: 'public/css',
generatedImagesDir: '.tmp/img/generated',
imagesDir: 'public/img',
javascriptsDir: 'public/js',
// fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: 'public/lib',
httpImagesPath: '/img',
httpGeneratedImagesPath: '/img/generated',
httpFontsPath: '/styles/fonts',
relativeAssets: false,
assetCacheBuster: false
},
dist: {
options: {
generatedImagesDir: 'dist/img/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
jshint: {
// all: ['gruntfile.js', 'public/js/**/*.js', 'test/**/*.js', 'app/**/*.js']
},
nodemon: {
dev: {
options: {
file: 'app.js',
args: [],
ignoredFiles: ['README.md', 'node_modules/**', '.DS_Store'],
watchedExtensions: ['js'],
watchedFolders: ['app', 'config'],
debug: true,
delayTime: 1,
env: {
PORT: 3000
},
cwd: __dirname
}
}
},
concurrent: {
tasks: ['nodemon', 'watch'],
options: {
logConcurrentOutput: true
}
},
mochaTest: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
},
bower: {
install: {
options: {
targetDir: './public/lib',
layout: 'byComponent',
install: true,
verbose: true,
cleanBowerDir: true
}
}
}
});
//Load NPM tasks
grunt.loadNpmTasks('grunt-contrib-watch');
// grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-bower-task');
//Making grunt default to force in order not to break the project.
grunt.option('force', true);
//Default task(s).
// grunt.registerTask('default', ['jshint', 'concurrent']);
grunt.registerTask('default', ['concurrent']);
//Test task.
grunt.registerTask('test', ['mochaTest']);
//Bower task.
grunt.registerTask('install', ['bower']);
};
|
import { graphql } from "gatsby";
import PropTypes from "prop-types";
import React from "react";
import Loadable from "react-loadable";
import { Col, Container, Row } from "react-bootstrap";
import Footer from "../components/footer";
import Layout from "../components/layout";
import LightNavbar from "../components/light-navbar";
import Spinner from "../components/spinner";
import { GOOGLE_API_KEY } from "../constants";
import "./calendar.scss";
const Calendar = Loadable({
loader: () => import("../components/calendar"),
loading: Spinner
});
const calendars = {
"Holidays in Indonesia": {
googleCalendarId: "en.indonesian#holiday@group.v.calendar.google.com",
color: "#e74c3c"
},
"TOKI - Local Public Contests": {
googleCalendarId: "aiho5jhevjd7je1oqpce8ohbm4@group.calendar.google.com",
color: "#f1c40f"
},
"TOKI - International Public Contests": {
googleCalendarId: "6uqtufomkqj8bqlr5j3ngrli2c@group.calendar.google.com",
color: "#27ae60"
},
"TOKI - Limited Contests": {
googleCalendarId: "i3f3ksivqrhqidai27978nrnlg@group.calendar.google.com",
color: "#8e44ad"
},
"TOKI - 3rd Party Programming Contests": {
googleCalendarId: "tfp6d8ljl4p4pcf6jhcqr7bd48@group.calendar.google.com",
color: "#e67e22"
},
"TOKI - TOKI Events": {
googleCalendarId: "kdfarl1llhmr12dqvuloo2l0hc@group.calendar.google.com",
color: "#3498db"
},
"TOKI - Other Calendars": {
googleCalendarId: "gq33r08ccklumd601pp4ffgdas@group.calendar.google.com",
color: "#34495e"
}
};
const CalendarHeader = ({ name }) => {
const color = calendars[name].color;
const encodedId = encodeURIComponent(calendars[name].googleCalendarId);
return (
<a
href={`https://calendar.google.com/calendar/embed?src=${encodedId}&ctz=Asia%2FSingapore`}
style={{
color,
borderBottomColor: color
}}
className="calendar-header-link"
>
{name}
</a>
);
};
CalendarHeader.propTypes = {
name: PropTypes.string.isRequired
};
const Calendars = props => {
const { location } = props;
return (
<Layout>
<LightNavbar location={location} />
<div className="content offset-navbar mb-5">
<div className="text-bold text-center py-4">
<h3>Kalender TOKI</h3>
</div>
<Container>
<Row className="justify-content-center">
<Col xs={12} md={8} lg={6}>
<Calendar
googleCalendarApiKey={GOOGLE_API_KEY}
eventSources={Object.values(calendars)}
/>
<div className="mt-4">
<p>
<strong>Kalender Tim Olimpiade Komputer Indonesia</strong>.
Kalender ini berisi gabungan dari tujuh kalender berikut:
</p>
<ol>
<li>
<CalendarHeader name="Holidays in Indonesia" />
<ul>
<li>Hari Libur Nasional Indonesia</li>
</ul>
</li>
<li>
<CalendarHeader name="TOKI - Local Public Contests" />
<ul>
<li>
Kontes yang diselenggarakan oleh TOKI dan dapat diikuti
oleh seluruh anggota komunitas Olimpiade Informatika
Indonesia.
</li>
<li>
Soal-soal yang digunakan pada kontes ini mungkin saja
hanya disediakan dalam bahasa Indonesia.
</li>
</ul>
</li>
<li>
<CalendarHeader name="TOKI - International Public Contests" />
<ul>
<li>
Kontes yang diselenggarakan oleh TOKI dan dapat diikuti
oleh seluruh anggota komunitas Olimpiade Informatika di
seluruh dunia.
</li>
<li>
Soal-soal yang digunakan pada kontes ini mungkin saja
juga disediakan dalam bahasa Inggris.
</li>
</ul>
</li>
<li>
<CalendarHeader name="TOKI - Limited Contests" />
<ul>
<li>
Kontes yang diselenggarakan oleh TOKI dan hanya dapat
diikuti dengan pendaftaran khusus, atau kualifikasi
sebelumnya.
</li>
<li>
Beberapa contoh kontes dalam kategori ini mencakup
Olimpiade Sains Nasional, Pelatihan Nasional TOKI, dan
lain lain.
</li>
</ul>
</li>
<li>
<CalendarHeader name="TOKI - 3rd Party Programming Contests" />
<ul>
<li>
Kontes yang bukan diselenggarakan oleh TOKI, namun
secara resmi diketahui dan/atau diikuti oleh TOKI.
</li>
<li>
Beberapa contoh kontes dalam kategori ini mencakup
International Olympiad in Informatics, Asia-Pacific
Olympiad in Informatics, dan lain lain.
</li>
</ul>
</li>
<li>
<CalendarHeader name="TOKI - TOKI Events" />
<ul>
<li>
Kegiatan TOKI atau IA-TOKI yang bukan merupakan kontes
pemrograman.
</li>
<li>
Beberapa contoh kegiatan dalam kategori ini mencakup
TOKI Gathering, IA-TOKI Camp, dan lain lain.
</li>
</ul>
</li>
<li>
<CalendarHeader name="TOKI - Other Calendars" />
<ul>
<li>
Kegiatan-kegiatan lainnya yang tidak termasuk dalam
kalender manapun yang sudah disebutkan di atas.
</li>
</ul>
</li>
</ol>
<p>
Ingin menampilkan acara Anda ke dalam kalender ini? Kirimkan
email ke{" "}
<a href="mailto:scientific+calendar@toki.or.id">
scientific+calendar@toki.or.id
</a>{" "}
dengan cc ke{" "}
<a href="mailto:info@toki.or.id">info@toki.or.id</a>.
</p>
<hr />
</div>
</Col>
</Row>
</Container>
</div>
<Footer />
</Layout>
);
};
export default Calendars;
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
booksBackground: file(relativePath: { eq: "downloadBooks.png" }) {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
archiveBackground: file(relativePath: { eq: "downloadArchive.png" }) {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
newsBackground: file(relativePath: { eq: "downloadTokiNews.png" }) {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
}
`;
|
// Copyright (C) 2021 Igalia S.L. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-Intl.DateTimeFormat.prototype.resolvedOptions
description: >
Tests that Intl.DateTimeFormat.prototype.resolvedOptions calls
OrdinaryHasInstance instead of the instanceof operator which includes a
Symbol.hasInstance lookup and call among other things.
---*/
const dtf = new Intl.DateTimeFormat();
Object.defineProperty(Intl.DateTimeFormat, Symbol.hasInstance, {
get() { throw new Test262Error(); }
});
dtf.format;
|
import AxiosWrapper from '@yandex-cloud/axios-wrapper';
import {backend as BACKEND} from '../store';
import {StorageTypes} from '../store/reducers/storage';
const config = {withCredentials: !window.custom_backend};
const {settingsApi} = window.web_version ? window.systemSettings : {};
export class YdbEmbeddedAPI extends AxiosWrapper {
getPath(path) {
return `${BACKEND}${path}`;
}
getClusterInfo() {
return this.get(this.getPath('/viewer/json/cluster'), {tablets: true});
}
getNodes(path) {
return this.get(this.getPath('/viewer/json/compute?enums=true'), {path});
}
getNodeInfo(id) {
return this.get(this.getPath('/viewer/json/sysinfo?enums=true'), {
node_id: id,
});
}
getTenants() {
return this.get(this.getPath('/viewer/json/tenantinfo'), {
tablets: 1,
storage: 1,
});
}
getTenantInfo({path}) {
return this.get(this.getPath('/viewer/json/tenantinfo'), {
path,
tablets: true,
storage: true,
});
}
getStorageInfo({tenant, filter, nodeId, type}, {concurrentId} = {}) {
return this.get(
this.getPath(
`/viewer/json/${type === StorageTypes.nodes ? 'nodes' : 'storage'}?enums=true`,
),
{
tenant,
node_id: nodeId,
with: filter,
},
{
concurrentId,
},
);
}
getPdiskInfo(nodeId, pdiskId) {
return this.get(this.getPath('/viewer/json/pdiskinfo?enums=true'), {
filter: `(NodeId=${nodeId}${pdiskId ? `;PDiskId=${pdiskId}` : ''})`,
});
}
getVdiskInfo({vdiskId, pdiskId, nodeId}) {
return this.get(this.getPath('/viewer/json/vdiskinfo?enums=true'), {
filter: `(VDiskId=${vdiskId ?? ''};PDiskId=${pdiskId ?? ''};NodeId=${nodeId ?? ''})`,
});
}
getGroupInfo(groupId) {
return this.get(this.getPath('/viewer/json/storage?enums=true'), {
group_id: groupId,
});
}
getHostInfo() {
return this.get(this.getPath('/viewer/json/sysinfo?node_id=.&enums=true'));
}
getTabletsInfo({nodes = [], path}) {
const filter = nodes.length > 0 && `(NodeId=[${nodes.join(',')}])`;
return this.get(this.getPath('/viewer/json/tabletinfo'), {
filter,
path,
enums: true,
});
}
getSchema({path}) {
return this.get(
this.getPath('/viewer/json/describe'),
{
path,
enums: true,
backup: false,
private: false,
partition_config: false,
partition_stats: false,
partitioning_info: false,
},
{concurrentId: `getSchema|${path}`},
);
}
getDescribe({path}) {
return this.get(this.getPath('/viewer/json/describe'), {
path,
enums: true,
});
}
getSchemaAcl({path}) {
return this.get(
this.getPath('/viewer/json/metainfo'),
{
path,
},
{concurrentId: `getSchemaAcl|${path}`},
);
}
getHeatmapData({path}) {
return this.get(this.getPath('/viewer/json/describe'), {
path,
enums: true,
backup: false,
private: false,
children: false,
partition_config: false,
partition_stats: true,
});
}
getNetwork(path) {
return this.get(this.getPath('/viewer/json/netinfo'), {
enums: true,
path,
});
}
getPoolInfo(poolName) {
return this.get(this.getPath('/viewer/json/storage'), {
pool: poolName,
enums: true,
});
}
getTablet({id}) {
return this.get(this.getPath(`/viewer/json/tabletinfo?filter=(TabletId=${id})`), {
enums: true,
});
}
getTabletHistory({id}) {
return this.get(this.getPath(`/viewer/json/tabletinfo?filter=(TabletId=${id})`), {
enums: true,
merge: false,
});
}
getNodesList() {
return this.get(this.getPath('/viewer/json/nodelist'), {enums: true});
}
getTenantsList() {
return this.get(this.getPath('/viewer/json/tenants'), {
enums: true,
state: 0,
});
}
sendQuery(query, database, action, stats) {
return this.post(this.getPath('/viewer/json/query'), {
query,
database,
action,
stats,
});
}
getExplainQuery(query, database) {
return this.post(this.getPath('/viewer/json/query'), {
query,
database,
action: 'explain',
});
}
getExplainQueryAst(query, database) {
return this.post(this.getPath('/viewer/json/query'), {
query,
database,
action: 'explain-ast',
});
}
getHotKeys(path, enableSampling) {
return this.get(this.getPath('/viewer/json/hotkeys'), {
path,
enable_sampling: enableSampling,
});
}
getHealthcheckInfo(database) {
return this.get(this.getPath('/viewer/json/healthcheck'), {
tenant: database,
});
}
killTablet(id) {
return this.get(this.getPath(`/tablets?KillTabletID=${id}`));
}
stopTablet(id, hiveId) {
return this.get(
this.getPath(`/tablets/app?TabletID=${hiveId}&page=StopTablet&tablet=${id}`),
);
}
resumeTablet(id, hiveId) {
return this.get(
this.getPath(`/tablets/app?TabletID=${hiveId}&page=ResumeTablet&tablet=${id}`),
);
}
getTabletDescribe(TenantId) {
return this.get(this.getPath('/viewer/json/describe'), {
schemeshard_id: TenantId.SchemeShard,
path_id: TenantId.PathId,
});
}
postSetting(name, value) {
return this.request({
method: 'PATCH',
url: settingsApi,
data: {[name]: value},
});
}
authenticate(user, password) {
return this.post(this.getPath('/login'), {
user,
password,
});
}
logout() {
return this.post(this.getPath('/logout'), {});
}
whoami() {
return this.get(this.getPath('/viewer/json/whoami'));
}
}
const api = new YdbEmbeddedAPI({config: config});
window.api = api;
|
import os
import sys
from spec import eq_, skip, Spec, ok_, trap
from mock import patch, Mock
from invoke.cli import tasks_from_contexts
from invoke.collection import Collection
from invoke.context import Context
from invoke.parser import Parser
from invoke.tasks import task
import invoke
from _utils import (
_dispatch, _output_eq, IntegrationSpec, cd, expect_exit,
skip_if_windows, mocked_run
)
class CLI(IntegrationSpec):
"Command-line behavior"
class basic_invocation:
@trap
def vanilla(self):
os.chdir('implicit')
_dispatch('inv foo')
eq_(sys.stdout.getvalue(), "Hm\n")
@trap
def vanilla_with_explicit_collection(self):
# Duplicates _output_eq, but this way that can change w/o breaking
# our expectations.
_dispatch('inv -c integration print_foo')
eq_(sys.stdout.getvalue(), "foo\n")
def args(self):
_output_eq('-c integration print_name --name inigo', "inigo\n")
def underscored_args(self):
_output_eq(
'-c integration print_underscored_arg --my-option whatevs',
"whatevs\n",
)
class error_cases:
def missing_collection_yields_useful_error(self):
_output_eq(
'-c huhwhat -l',
stderr="Can't find any collection named 'huhwhat'!\n",
code=1
)
def missing_default_collection_doesnt_say_None(self):
with cd('/'):
_output_eq(
'-l',
stderr="Can't find any collection named 'tasks'!\n",
code=1
)
@trap
def missing_default_task_prints_help(self):
with expect_exit():
_dispatch("inv -c foo")
ok_("Core options:" in sys.stdout.getvalue())
def contextualized_tasks_are_given_parser_context_arg(self):
# go() in contextualized.py just returns its initial arg
retval = list(_dispatch('invoke -c contextualized go').values())[0]
assert isinstance(retval, Context)
class help:
# TODO: On Windows, we don't get a pty, so we don't get a
# guaranteed terminal size of 80x24. Skip for now, but maybe
# a suitable fix would be to just strip all whitespace from the
# returned and expected values before testing. Then terminal
# size is ignored.
@skip_if_windows
def core_help_option_prints_core_help(self):
# TODO: change dynamically based on parser contents?
# e.g. no core args == no [--core-opts],
# no tasks == no task stuff?
# NOTE: test will trigger default pty size of 80x24, so the below
# string is formatted appropriately.
# TODO: add more unit-y tests for specific behaviors:
# * fill terminal w/ columns + spacing
# * line-wrap help text in its own column
expected = """
Usage: inv[oke] [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts]
Core options:
--complete Print tab-completion candidates for given
parse remainder.
--no-dedupe Disable task deduplication.
-c STRING, --collection=STRING Specify collection name to load.
-d, --debug Enable debug output.
-e, --echo Echo executed commands before running.
-f STRING, --config=STRING Runtime configuration file to use.
-h [STRING], --help[=STRING] Show core or per-task help and exit.
-H STRING, --hide=STRING Set default value of run()'s 'hide' kwarg.
-l, --list List available tasks.
-p, --pty Use a pty when executing shell commands.
-r STRING, --root=STRING Change root directory used for finding task
modules.
-V, --version Show version and exit.
-w, --warn-only Warn, instead of failing, when shell
commands fail.
""".lstrip()
for flag in ['-h', '--help']:
_output_eq(flag, expected)
def per_task_help_prints_help_for_task_only(self):
expected = """
Usage: inv[oke] [--core-opts] punch [--options] [other tasks here ...]
Docstring:
none
Options:
-h STRING, --why=STRING Motive
-w STRING, --who=STRING Who to punch
""".lstrip()
for flag in ['-h', '--help']:
_output_eq('-c decorator {0} punch'.format(flag), expected)
def per_task_help_works_for_unparameterized_tasks(self):
expected = """
Usage: inv[oke] [--core-opts] biz [other tasks here ...]
Docstring:
none
Options:
none
""".lstrip()
_output_eq('-c decorator -h biz', expected)
def per_task_help_displays_docstrings_if_given(self):
expected = """
Usage: inv[oke] [--core-opts] foo [other tasks here ...]
Docstring:
Foo the bar.
Options:
none
""".lstrip()
_output_eq('-c decorator -h foo', expected)
def per_task_help_dedents_correctly(self):
expected = """
Usage: inv[oke] [--core-opts] foo2 [other tasks here ...]
Docstring:
Foo the bar:
example code
Added in 1.0
Options:
none
""".lstrip()
_output_eq('-c decorator -h foo2', expected)
def per_task_help_dedents_correctly_for_alt_docstring_style(self):
expected = """
Usage: inv[oke] [--core-opts] foo3 [other tasks here ...]
Docstring:
Foo the other bar:
example code
Added in 1.1
Options:
none
""".lstrip()
_output_eq('-c decorator -h foo3', expected)
def version_info(self):
_output_eq('-V', "Invoke {0}\n".format(invoke.__version__))
@trap
def version_override(self):
with expect_exit():
_dispatch('notinvoke -V', version="nope 1.0")
eq_(sys.stdout.getvalue(), "nope 1.0\n")
class task_list:
"--list"
def _listing(self, lines):
return """
Available tasks:
{0}
""".format('\n'.join(" " + x for x in lines)).lstrip()
def _list_eq(self, collection, listing):
cmd = '-c {0} --list'.format(collection)
_output_eq(cmd, self._listing(listing))
def simple_output(self):
expected = self._listing((
'bar',
'biz',
'boz',
'foo',
'post1',
'post2',
'print_foo',
'print_name',
'print_underscored_arg',
))
for flag in ('-l', '--list'):
_output_eq('-c integration {0}'.format(flag), expected)
def namespacing(self):
self._list_eq('namespacing', (
'toplevel',
'module.mytask',
))
def top_level_tasks_listed_first(self):
self._list_eq('simple_ns_list', (
'z_toplevel',
'a.b.subtask'
))
def subcollections_sorted_in_depth_order(self):
self._list_eq('deeper_ns_list', (
'toplevel',
'a.subtask',
'a.nother.subtask',
))
def aliases_sorted_alphabetically(self):
self._list_eq('alias_sorting', (
'toplevel (a, z)',
))
def default_tasks(self):
# sub-ns default task display as "real.name (collection name)"
self._list_eq('explicit_root', (
'top_level (othertop)',
'sub.sub_task (sub, sub.othersub)',
))
def docstrings_shown_alongside(self):
self._list_eq('docstrings', (
'leading_whitespace foo',
'no_docstring',
'one_line foo',
'two_lines foo',
'with_aliases (a, b) foo',
))
def empty_collections_say_no_tasks(self):
_output_eq(
"-c empty -l",
"No tasks found in collection 'empty'!\n"
)
def debug_flag_activates_logging(self):
# Have to patch our logger to get in before Nose logcapture kicks in.
with patch('invoke.util.debug') as debug:
_dispatch('inv -d -c debugging foo')
debug.assert_called_with('my-sentinel')
class autoprinting:
def defaults_to_off_and_no_output(self):
_output_eq("-c autoprint nope", "")
def prints_return_value_to_stdout_when_on(self):
_output_eq("-c autoprint yup", "It's alive!\n")
def prints_return_value_to_stdout_when_on_and_in_collection(self):
_output_eq("-c autoprint sub.yup", "It's alive!\n")
def does_not_fire_on_pre_tasks(self):
_output_eq("-c autoprint pre_check", "")
def does_not_fire_on_post_tasks(self):
_output_eq("-c autoprint post_check", "")
class run_options:
"run() related CLI flags affect 'run' config values"
def _test_flag(self, flag, key):
with mocked_run():
# The tasks themselves perform the necessary asserts.
_dispatch('invoke {0} -c contextualized check_{1}'.format(
flag, key
))
def warn_only(self):
self._test_flag('-w', 'warn')
def pty(self):
self._test_flag('-p', 'pty')
def hide(self):
self._test_flag('--hide both', 'hide')
def echo(self):
self._test_flag('-e', 'echo')
class configuration:
"Configuration-related concerns"
def per_project_config_files_are_loaded(self):
with cd(os.path.join('configs', 'yaml')):
_dispatch("inv mytask")
def per_project_config_files_load_with_explicit_ns(self):
# Re: #234
with cd(os.path.join('configs', 'yaml')):
_dispatch("inv -c explicit mytask")
def runtime_config_file_honored(self):
with cd('configs'):
_dispatch("inv -c runtime -f yaml/invoke.yaml mytask")
def tasks_dedupe_honors_configuration(self):
# Kinda-sorta duplicates some tests in executor.py, but eh.
with cd('configs'):
# Runtime conf file
_output_eq(
'-c integration -f no-dedupe.yaml biz',
"""
foo
foo
bar
biz
post1
post2
post2
""".lstrip())
# Flag beats runtime
_output_eq(
'-c integration -f dedupe.yaml --no-dedupe biz',
"""
foo
foo
bar
biz
post1
post2
post2
""".lstrip())
# * debug (top level?)
# * hide (run.hide...lol)
# * pty (run.pty)
# * warn (run.warn)
def env_vars_load_with_prefix(self):
os.environ['INVOKE_RUN_ECHO'] = "1"
with mocked_run():
# Task performs the assert
_dispatch('invoke -c contextualized check_echo')
TB_SENTINEL = 'Traceback (most recent call last)'
class HighLevelFailures(Spec):
@trap
def command_failure(self):
"Command failure doesn't show tracebacks"
with patch('sys.exit') as exit:
_dispatch('inv -c fail simple')
assert TB_SENTINEL not in sys.stderr.getvalue()
exit.assert_called_with(1)
class parsing:
@trap
def should_not_show_tracebacks(self):
# Ensure we fall out of dispatch() on missing parser args,
# but are still able to look at stderr to ensure no TB got printed
with patch('sys.exit', Mock(side_effect=SystemExit)):
try:
_dispatch("inv -c fail missing_pos")
except SystemExit:
pass
assert TB_SENTINEL not in sys.stderr.getvalue()
def should_show_core_usage_on_core_failures(self):
skip()
def should_show_context_usage_on_context_failures(self):
skip()
def load_failure(self):
skip()
class CLIParsing(Spec):
"""
High level parsing tests
"""
def setup(self):
@task(positional=[])
def mytask(mystring, s, boolean=False, b=False, v=False,
long_name=False, true_bool=True):
pass
@task(aliases=['mytask27'])
def mytask2():
pass
@task(default=True)
def mytask3(mystring):
pass
@task
def mytask4(clean=False, browse=False):
pass
@task(aliases=['other'], default=True)
def subtask():
pass
subcoll = Collection('sub', subtask)
self.c = Collection(mytask, mytask2, mytask3, mytask4, subcoll)
def _parser(self):
return Parser(self.c.to_contexts())
def _parse(self, argstr):
return self._parser().parse_argv(argstr.split())
def _compare(self, invoke, flagname, value):
invoke = "mytask " + invoke
result = self._parse(invoke)
eq_(result[0].args[flagname].value, value)
def _compare_names(self, given, real):
eq_(self._parse(given)[0].name, real)
def underscored_flags_can_be_given_as_dashed(self):
self._compare('--long-name', 'long_name', True)
def inverse_boolean_flags(self):
self._compare('--no-true-bool', 'true_bool', False)
def namespaced_task(self):
self._compare_names("sub.subtask", "sub.subtask")
def aliases(self):
self._compare_names("mytask27", "mytask2")
def subcollection_aliases(self):
self._compare_names("sub.other", "sub.subtask")
def subcollection_default_tasks(self):
self._compare_names("sub", "sub.subtask")
def loaded_collection_default_task(self):
result = tasks_from_contexts(self._parse(''), self.c)
eq_(len(result), 1)
eq_(result[0][0], 'mytask3')
def boolean_args(self):
"mytask --boolean"
self._compare("--boolean", 'boolean', True)
def flag_then_space_then_value(self):
"mytask --mystring foo"
self._compare("--mystring foo", 'mystring', 'foo')
def flag_then_equals_sign_then_value(self):
"mytask --mystring=foo"
self._compare("--mystring=foo", 'mystring', 'foo')
def short_boolean_flag(self):
"mytask -b"
self._compare("-b", 'b', True)
def short_flag_then_space_then_value(self):
"mytask -s value"
self._compare("-s value", 's', 'value')
def short_flag_then_equals_sign_then_value(self):
"mytask -s=value"
self._compare("-s=value", 's', 'value')
def short_flag_with_adjacent_value(self):
"mytask -svalue"
r = self._parse("mytask -svalue")
eq_(r[0].args.s.value, 'value')
def _flag_value_task(self, value):
r = self._parse("mytask -s {0} mytask2".format(value))
eq_(len(r), 2)
eq_(r[0].name, 'mytask')
eq_(r[0].args.s.value, value)
eq_(r[1].name, 'mytask2')
def flag_value_then_task(self):
"mytask -s value mytask2"
self._flag_value_task('value')
def flag_value_same_as_task_name(self):
"mytask -s mytask2 mytask2"
self._flag_value_task('mytask2')
def three_tasks_with_args(self):
"mytask --boolean mytask3 --mystring foo mytask2"
r = self._parse("mytask --boolean mytask3 --mystring foo mytask2")
eq_(len(r), 3)
eq_([x.name for x in r], ['mytask', 'mytask3', 'mytask2'])
eq_(r[0].args.boolean.value, True)
eq_(r[1].args.mystring.value, 'foo')
def tasks_with_duplicately_named_kwargs(self):
"mytask --mystring foo mytask3 --mystring bar"
r = self._parse("mytask --mystring foo mytask3 --mystring bar")
eq_(r[0].name, 'mytask')
eq_(r[0].args.mystring.value, 'foo')
eq_(r[1].name, 'mytask3')
eq_(r[1].args.mystring.value, 'bar')
def multiple_short_flags_adjacent(self):
"mytask -bv (and inverse)"
for args in ('-bv', '-vb'):
r = self._parse("mytask {0}".format(args))
a = r[0].args
eq_(a.b.value, True)
eq_(a.v.value, True)
|
/* Copyright (C) 2016 NooBaa */
/** @typedef {typeof import('../sdk/nb')} nb */
'use strict';
const config = require('../../config');
const postgres_client = require('./postgres_client');
const mongo_client = require('./mongo_client');
const dbg = require('./debug_module')(__filename);
/**
* @returns { nb.DBClient }
*/
function instance() {
switch (config.DB_TYPE) {
case 'postgres':
return postgres_client.instance();
case 'mongodb':
return mongo_client.instance();
default: {
const str = `NON SUPPORTED DB_TYPE ${config.DB_TYPE}`;
dbg.error(str);
throw new Error(str);
}
}
}
// EXPORTS
exports.instance = instance;
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'maximize', 'lv', {
maximize: 'Maksimizēt',
minimize: 'Minimizēt'
} );
|
import subprocess
def get_drive_letter():
return subprocess.getoutput('echo %CD%').split(':')[0]
def get_user_name():
return subprocess.getoutput('whoami').split('\\')[1]
|
// WebWorker.js
export default class WebWorker {
constructor(worker) {
let code = worker.toString();
code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));
const blob = new Blob([code], { type: "application/javascript" });
return new Worker(URL.createObjectURL(blob));
}
}
|
/*============================================================================================
File Name: form-typeahead.js
Description: The Typeahead plugin from Twitter's Bootstrap 2 ready to use with Bootstrap 4
------------------------------------------------------------------------------------------
Item Name: Stack - Responsive Admin Theme
Version: 2.1
Author: Pixinvent
Author URL: hhttp://www.themeforest.net/user/pixinvent
==============================================================================================*/
(function(window, document, $) {
'use strict';
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('.typeahead-basic').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
// constructs the suggestion engine Bloodhound
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: states
});
$('.typeahead-bloodhound').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: states
});
// Prefetch Data
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
// url points to a json file that contains an array of country names, see
// https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json
prefetch: 'app-assets/data/countries.json'
});
// passing in `null` for the `options` arguments will result in the default
// options being used
$('.typeahead-prefetch').typeahead(null, {
name: 'countries',
source: countries
});
// Remote Data
var bestPictures = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'app-assets/data/films/post_1960.json',
remote: {
url: 'app-assets/data/films/queries/%QUERY.json',
wildcard: '%QUERY'
}
});
$('.typeahead-remote').typeahead(null, {
name: 'best-pictures',
display: 'value',
source: bestPictures
});
// Custom Templates
$('.custom-template').typeahead(null, {
name: 'best-pictures',
display: 'value',
source: bestPictures,
templates: {
empty: [
'<div class="empty-message">',
'Unable to find any Best Picture winners that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div><strong>{{value}}</strong> – <em>{{year}}</em></div>')
}
});
// Default Suggestions
var nflTeams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) { return obj.team; },
prefetch: 'app-assets/data/nfl.json'
});
function nflTeamsWithDefaults(q, sync) {
if (q === '') {
sync(nflTeams.get('Detroit Lions', 'Green Bay Packers', 'Chicago Bears'));
}
else {
nflTeams.search(q, sync);
}
}
$('.default-suggestions').typeahead({
minLength: 0,
highlight: true
},
{
name: 'nfl-teams',
display: 'team',
source: nflTeamsWithDefaults
});
// Multiple Datasets
var nbaTeams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'app-assets/data/nba.json'
});
var nhlTeams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'app-assets/data/nhl.json'
});
$('.multiple-datasets').typeahead({
highlight: true
},
{
name: 'nba-teams',
display: 'team',
source: nbaTeams,
templates: {
header: '<h3 class="league-name">NBA Teams</h3>'
}
},
{
name: 'nhl-teams',
display: 'team',
source: nhlTeams,
templates: {
header: '<h3 class="league-name">NHL Teams</h3>'
}
});
// Scrollable Dropdown Menu
$('.scrollable-dropdown-menu').typeahead(null, {
name: 'countries',
limit: 10,
source: countries
});
// RTL Support
var statePhrases = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: states
});
$('.rtl-support').typeahead({
hint: false
},
{
name: 'States',
source: statePhrases
});
// Scrollable Dropdown Menu
$('.add-item').typeahead(null, {
name: 'countries',
source: countries,
addItem: true,
});
})(window, document, jQuery);
|
/**
* adds implementation phase components in the graph
* @todo needs refactoring
*
* @param {Object} cy cytoscape instance
* @param {Object} event captured mouse event
* @param {number} nodeCounter id counter for nodes
*/
module.exports = function addDgnComponent (cy, event, nodeCounter) {
// get mouse position on click
// display new node on the left of the menu
let posX = event.x + 50
let posY = event.y - 30
// get the selected concept
let component = event.target.textContent
switch (component) {
case 'actor':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
actorType: '',
concept: 'actor'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'device':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
concept: 'device'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'information':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
concept: 'information'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'data center':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
dcType: '',
concept: 'data center'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'vnf':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
vnfType: '',
concept: 'vnf'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'constraint':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
constraintType: '',
concept: 'constraint'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'asset':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
concept: 'asset'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'threat':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
threatType: '',
concept: 'threat'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
case 'malicious actor':
cy.add({
group: 'nodes',
data: {
id: `n${nodeCounter}`,
label: `${component}`,
asto: {
description: '',
concept: 'malicious actor'
}
},
renderedPosition: {
x: posX,
y: posY
}
})
break
default:
console.error('error in addDgnComponent.js')
}
}
|
'use strict';
var exec = require('child_process').exec;
var chalk = require('chalk');
module.exports = function (grunt) {
grunt.registerMultiTask('shell', 'Run shell commands', function () {
var cb = this.async();
var options = this.options({
stdout: true,
stderr: true,
stdin: true,
failOnError: true
});
var cmd = this.data.command;
if (cmd === undefined) {
throw new Error('`command` required');
}
cmd = grunt.template.process(typeof cmd === 'function' ? cmd.apply(grunt, arguments) : cmd);
var cp = exec(cmd, options.execOptions, function (err, stdout, stderr) {
if (typeof options.callback === 'function') {
options.callback.call(this, err, stdout, stderr, cb);
} else {
if (err && options.failOnError) {
grunt.warn(err);
}
cb();
}
}.bind(this));
var captureOutput = function (child, output) {
if (grunt.option('color') === false) {
child.on('data', function (data) {
output.write(chalk.stripColor(data));
});
} else {
child.pipe(output);
}
};
grunt.verbose.writeln('Command:', chalk.yellow(cmd));
if (options.stdout || grunt.option('verbose')) {
captureOutput(cp.stdout, process.stdout);
}
if (options.stderr || grunt.option('verbose')) {
captureOutput(cp.stderr, process.stderr);
}
if (options.stdin) {
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.pipe(cp.stdin);
}
});
};
|
import React from "react"
import { Item } from "semantic-ui-react"
import { OutboundLink } from "gatsby-plugin-google-analytics"
const Press = ({ articles }) => (
<Item.Group>
{articles.map(article => {
return (
<Item key={article.id}>
<Item.Content>
<Item.Header
as={OutboundLink}
href={article.url}
target="_blank"
rel="noopener"
>
{article.title}
</Item.Header>
<Item.Meta>
{article.source},{" "}
<time datetime={article.date}>{article.formattedDate}</time>
</Item.Meta>
</Item.Content>
</Item>
)
})}
</Item.Group>
)
export default Press
|
/**
* Created by 健勤 on 2016/7/9.
*/
$(function(){
var filmId = $.getUrlParam("filmId");
//为空或者不为数字时默认跳转主页
if( !filmId || (filmId && !/^\d+$/.test(filmId)) ){
window.location.href = "index.html";
}
$.ajax({
url: "/user/query/getFilmInfo.do",
data: {filmId: filmId},
dataType: "json",
type: "post",
async: true,
success: function(data){
if(data.state == 1){
$("#pricture").attr("src", data.pricturePath);
$("#filmName").append(data.filmName);
$("#kind").append("类型: " + data.kind);
$("#releaseDate").append("上映时间: " + data.releaseDate);
$("#description").append("简介: " + data.description);
$("#duration").append("时长: " + data.duration + "分钟");
var actorsStr = "演员:";
$.each(data.actors, function (index) {
if(index != data.actors.length - 1){
actorsStr += data.actors[index].actorName + ",";
}
else{
actorsStr += data.actors[index].actorName;
}
});
$("#actors").append(actorsStr);
$("#showSession").attr("onclick", "getFilmSession(" + filmId + ")");
}
},
error: function(err){
alert("系统管理员已记录错误操作,正为你马上解决问题,请你耐心等候!");
return err;
}
});
});
|
import React from 'react';
import { TabBar } from 'antd-mobile';
import { observer } from 'mobx-react';
// 静态数据
import { tabInfo } from './data';
// mobx数据
import state from './state';
// less样式
import './index.less';
// tab
@observer
class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'redTab'
};
}
componentDidMount() {
state.productNumData();
}
// icon样式
styleImage = (url) => {
return (
<div style={{
width: '22px',
height: '22px',
background: `url(${url}) center center / 21px 21px no-repeat`
}} />
);
}
render() {
const { history={}, location={} } = this.props;
const { productNum } = state;
return (
<div className='dm_FooterCopyright' >
<TabBar
unselectedTintColor="#949494"
tintColor="#33A3F4"
barTintColor="white"
>
{
tabInfo && tabInfo.map(item => {
return (
<TabBar.Item
title={ item.title }
key={ item.key }
icon={ this.styleImage(item.icon) }
selectedIcon={ this.styleImage(item.selectedIcon) }
selected={ location.pathname === item.path }
badge={ item.isBadge ? productNum : null }
onPress={() => {
history && history.push( item.path );
}}
/>
);
})
}
</TabBar>
</div>
);
}
}
export default Index;
|
function fishingBoat(arg1, arg2, arg3) {
let groupBudget = Number(arg1);
let season = arg2;
let countFishers = Number(arg3);
let boatPrice = 0;
switch (season) {
case "Spring":
boatPrice = 3000;
if (countFishers <= 6) {
boatPrice = boatPrice * 0.90;
} else if (countFishers >= 7 && countFishers <= 11) {
boatPrice = boatPrice * 0.85;
} else if (countFishers >= 12) {
boatPrice = boatPrice * 0.75;
}
break;
case "Summer":
boatPrice = 4200;
if (countFishers <= 6) {
boatPrice = boatPrice * 0.90;
} else if (countFishers >= 7 && countFishers <= 11) {
boatPrice = boatPrice * 0.85;
} else if (countFishers >= 12) {
boatPrice = boatPrice * 0.75;
}
break;
case "Autumn":
boatPrice = 4200;
if (countFishers <= 6) {
boatPrice = boatPrice * 0.90;
} else if (countFishers >= 7 && countFishers <= 11) {
boatPrice = boatPrice * 0.85;
} else if (countFishers >= 12) {
boatPrice = boatPrice * 0.75;
}
break;
case "Winter":
boatPrice = 2600;
if (countFishers <= 6) {
boatPrice = boatPrice * 0.90;
} else if (countFishers >= 7 && countFishers <= 11) {
boatPrice = boatPrice * 0.85;
} else if (countFishers >= 12) {
boatPrice = boatPrice * 0.75;
}
break;
}
if (countFishers % 2 === 0 && season !== "Autumn") {
boatPrice = boatPrice * 0.95;
}
if (boatPrice > groupBudget) {
console.log(`Not enough money! You need ${(boatPrice - groupBudget).toFixed(2)} leva.`);
} else {
console.log(`Yes! You have ${(groupBudget - boatPrice).toFixed(2)} leva left.`);
}
}
fishingBoat("2000", "Winter", "13")
|
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors.
// The BDT project is supported by the GeekChain Foundation.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the BDT 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.
'use strict';
const net = require('net');
const os = require('os');
const assert = require('assert');
const Crypto = require('crypto');
/**
* Simple object check.
* @param item
* @returns {boolean}
*/
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
const EndPoint = {
PROTOCOL: {
udp: 'u',
tcp: 't',
},
FAMILY: {
IPv4: 'IPv4',
IPv6: 'IPv6',
},
CONST_IP: {
zeroIPv4: ['0.0.0.0'],
zeroIPv6: ['::', '0:0:0:0:0:0:0:0'],
loopbackIPv4: ['127.0.0.1'],
loopbackIPv6: ['::1', '0:0:0:0:0:0:0:1'],
},
toString(address, protocol) {
let ipv = 0;
if (address.family === EndPoint.FAMILY.IPv6) {
ipv = 6;
} else if (address.family === EndPoint.FAMILY.IPv4) {
ipv = 4;
}
assert(protocol || address.protocol);
return `${ipv}@${address.address}@${address.port}@${protocol || address.protocol || EndPoint.PROTOCOL.udp}`;
},
toAddress(epString) {
let el = epString.split('@');
if (el.length >= 4) {
let addr = {};
if (net.isIPv4(el[1])) {
addr.family = EndPoint.FAMILY.IPv4;
} else if (net.isIPv6(el[1])) {
addr.family = EndPoint.FAMILY.IPv6;
} else {
if (el[0] === '4') {
addr.family = EndPoint.FAMILY.IPv4;
} else if (el[0] === '6') {
addr.family = EndPoint.FAMILY.IPv6;
}
}
addr.address = el[1];
addr.port = parseInt(el[2]);
addr.protocol = EndPoint.PROTOCOL.udp;
addr.protocol = el[3];
return addr;
} else {
return null;
}
},
isZero(address) {
if (typeof address === 'string') {
address = EndPoint.toAddress(address);
}
if (address.family === EndPoint.FAMILY.IPv4) {
assert(EndPoint.CONST_IP.zeroIPv4.length === 1);
return address.address === EndPoint.CONST_IP.zeroIPv4[0];
} else {
assert(EndPoint.CONST_IP.zeroIPv6.length === 2);
return address.address === EndPoint.CONST_IP.zeroIPv6[0] ||
address.address === EndPoint.CONST_IP.zeroIPv6[1];
}
},
isLoopback(address) {
if (typeof address === 'string') {
const str = address;
address = EndPoint.toAddress(str);
assert(address, str);
}
if (address.family === EndPoint.FAMILY.IPv4) {
assert(EndPoint.CONST_IP.loopbackIPv4.length === 1);
return address.address === EndPoint.CONST_IP.loopbackIPv4[0];
} else {
assert(EndPoint.CONST_IP.loopbackIPv6.length === 2);
return address.address === EndPoint.CONST_IP.loopbackIPv6[0] || address.address === EndPoint.CONST_IP.loopbackIPv6[1];
}
},
isNAT(address) {
if (typeof address === 'string') {
address = EndPoint.toAddress(address);
}
if (EndPoint.isZero(address) || EndPoint.isLoopback(address)) {
return true;
}
// 暂时认为IPv6地址都是公网地址
if (!address.family || address.family == EndPoint.FAMILY.IPv4) {
let el = address.address.split('.');
if (el.length === 4) {
let el1 = parseInt(el[1]);
switch(el[0]) {
case '10': return true;
case '172': return el1 >= 0 && el1 <= 31;
case '192': return el1 === 168;
}
}
}
return false;
},
zero(family) {
return family === EndPoint.FAMILY.IPv4? EndPoint.CONST_IP.zeroIPv4[0] : EndPoint.CONST_IP.zeroIPv6[0];
},
loopback(family) {
return family === EndPoint.FAMILY.IPv4? EndPoint.CONST_IP.loopbackIPv4[0] : EndPoint.CONST_IP.loopbackIPv6[0];
},
// 猜测一个内网监听地址的公网访问地址
// 如果一个endpoint的ip是0地址或者内网ip
// 并且这个endpoint的协议是tcp协议,
// 就返回一个判断结果和NAT的ip:port( 公网ip:声明时的监听端口 )
// @return [bool 是否达成NAT条件, string 可能的公网访问endpoint]
// 比如:监听TCP '0.0.0.0:1234',并把端口映射到公网;从本地向外发起连接,通过对方反馈可发现自己的公网IP 'a.b.c.d';
// 这时可以猜测其他peer可能可以通过'a.b.c.d:1234'连接进来,当然也可能连不进来;
// 同样的,也可能从本地对局域网内peer发起连接发现自己的局域网IP,然后猜测自己的地址。
conjectureEndPoint(endpoint, internetAddress) {
// make endpoint to be an object
if ( typeof endpoint == 'string' ) {
endpoint = EndPoint.toAddress(endpoint);
} else if ( Array.isArray(endpoint) ) {
endpoint = EndPoint.toAddress(endpoint.join('@'));
}
if (endpoint.family !== internetAddress.family) {
return [false, ''];
}
const isNAT = EndPoint.isNAT(endpoint);
const isZero = EndPoint.isZero(endpoint);
const isTCP = EndPoint.PROTOCOL.tcp == endpoint.protocol;
if ( ( isNAT || isZero ) && isTCP ) {
let tcpListenerAddress = {
family: internetAddress.family,
address: internetAddress.address,
port: endpoint.port,
protocol: endpoint.protocol,
};
// 拼接公网ip和绑定端口
const newEp = EndPoint.toString(tcpListenerAddress);
return [true, newEp];
}
return [false, ''];
}
};
// 高阶函数, 生成检查protocol的check函数
// @param 用作检查的类型
// @return function 检查函数
function generateProtocolCheck(protocol) {
return function(address) {
if ( address != null && typeof address === 'object' ) {
// 如果address是对象,直接比较protocol即可
return address.protocol === protocol;
} else if ( typeof address === 'string' ) {
// 如果address 是 'u' 或者 't'
// 直接比较即可
// 如果address 字符串形式的endpoint, 则需要转化
if ( address.length == 1 ) {
return address === protocol;
} else {
return EndPoint.toAddress(address).protocol === protocol;
}
}
return false;
}
}
EndPoint.isTCP = generateProtocolCheck(EndPoint.PROTOCOL.tcp);
EndPoint.isUDP = generateProtocolCheck(EndPoint.PROTOCOL.udp);
const NetHelper = {
getLocalIPs(withInternal) {
let ips = [];
let netInterface = os.networkInterfaces();
for (let name of Object.keys(netInterface)) {
netInterface[name].forEach(info => {
// 127.0.0.1和::1是回环地址,由参数指定是否过滤
if (withInternal || !info.internal) {
if (info.family === EndPoint.FAMILY.IPv4) {
let el = info.address.split('.');
// 去掉0.x.x.x和169.254.x.x
if (el.length !== 4 ||
parseInt(el[0]) === 0 ||
(parseInt(el[0]) === 169 && parseInt(el[1]) === 254)) {
return;
}
} else if (info.family === EndPoint.FAMILY.IPv6) {
let el = info.address.split(':');
if (el.length === 0 ||
parseInt(el[0], 16) === 0xfe80) {
return;
}
}
ips.push(info.address);
}
});
}
return ips;
},
getLocalIPV4(withInternal) {
return NetHelper.getLocalIPs(withInternal).filter(ip => net.isIPv4(ip))
}
}
const algorithm = {
/**
* Deep merge two objects.
* @param target
* @param ...sources
*/
mergeDeep(target, ...sources) {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
algorithm.mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return algorithm.mergeDeep(target, ...sources);
},
binarySearch(target, arr, compare, low, count) {
if (!compare) {
compare = (target, cursor) => target - cursor;
}
if (!low) {
low = 0;
}
if (!count && count !== 0) {
count = arr.length - low;
}
if (count < 0 || low < 0) {
assert(false, `arg error:low=${low},count=${count}`);
return [-1, -1];
}
if (count === 0) {
return [-1, low];
}
const search = (low, high) => {
if (low <= high) {
let sub = compare(target, arr[low]);
if (sub < 0) {
return [-1, low];
} else if (sub === 0) {
return [low, low + 1];
}
sub = compare(target, arr[high]);
if (sub > 0) {
return [-1, high + 1];
} else if (sub === 0) {
return [high, high + 1];
}
let mid = (high + low) >> 1;
sub = compare(target, arr[mid]);
if (sub === 0) {
return [mid, mid + 1];
} else if (sub > 0) {
return search(mid + 1, high);
} else {
return search(low, mid - 1);
}
}
return [-1, low];
}
return search(low, low + count - 1);
},
UInt(n) {
return n >>> 0;
}
}
const TimeHelper = {
uptimeMS() {
return Math.round(process.uptime() * 1000);
},
}
/**
* 用于计算两个KEY(STRING)之间距离的HASH
* HASH长度暂时只取MD5的32位;便于计算,同时按距离分组时数量也不会太多
* 考虑到以后可能需要扩展到更多位数,不可以把HASH值直接当作32位整数处理(如:比较,位运算等);
* 需要任何运算时要在HashDistance类中添加函数;
* 如果真要扩展,已经使用的HASH应该放在最高位,或者直接顺着MD5值往后启用更多位,这样不会影响旧版本中两个距离远近比较和分组
*/
const HashDistance = {
calcDistance(key1, key2) {
return HashDistance.calcDistanceByHash(HashDistance.checkHash(key1), HashDistance.checkHash(key2));
},
hash(key, bitCount = HashDistance.HASH_BIT_COUNT) {
assert(typeof key === 'string' && (bitCount === 32 || bitCount === 16), `The key(${key}) must be a string.and bitCount(${bitCount}) must be 16 or 32.`);
let md5 = Crypto.createHash('md5');
md5.update(key);
let md5Hash = md5.digest();
if (bitCount === 32) {
let hash = md5Hash.readUInt32BE(0);
return algorithm.UInt(hash & (~HashDistance.HIGH_BIT_MASK));
} else {
let hash = md5Hash.readUInt16BE(0);
return algorithm.UInt(hash & (~HashDistance.HIGH_BIT_MASK16));
}
},
checkHash(key) {
if (typeof key === 'number') {
return key;
} else {
return HashDistance.hash(key);
}
},
calcDistanceByHash(hash1, hash2) {
return algorithm.UInt(hash1 ^ hash2);
},
firstDifferentBit(hash1, hash2) {
if (hash1 === hash2) {
return HashDistance.HASH_BIT_COUNT;
}
let bits = 0;
let xor = hash1 ^ hash2;
let highBitMask = HashDistance.HIGH_BIT_MASK;
while ((xor & (highBitMask >>> bits)) == 0) { // +-0
bits++;
}
return bits;
},
hashBit(hash, bitPos, bitCount = 1) {
// value << 32 == value?
if (bitCount == 0 || bitPos >= HashDistance.HASH_BIT_COUNT) {
return 0;
}
if (bitCount > HashDistance.HASH_BIT_COUNT - bitPos) {
bitCount = HashDistance.HASH_BIT_COUNT - bitPos;
}
// mask = 0x1111111000000
// |(bitCount)
let mask = (HashDistance.HASH_MASK << (HashDistance.HASH_BIT_COUNT - bitCount));
// mask = 0x0000111000000
// | |(bitPos+bitCount)
// |bitPos
mask = (mask >>> bitPos);
return algorithm.UInt(hash & mask);
},
or(hash1, hash2) {
return algorithm.UInt(hash1 | hash2);
},
and(hash1, hash2) {
return algorithm.UInt(hash1 & hash2);
},
xor(hash1, hash2) {
return algorithm.UInt(hash1 ^ hash2);
},
moveRight(hash, bitCount) {
return hash >>> bitCount;
},
moveLeft(hash, bitCount) {
return algorithm.UInt(hash << bitCount);
},
max(hash1, hash2) {
if (HashDistance.compareHash(hash1, hash2) >= 0) {
return hash1;
}
return hash2;
},
min(hash1, hash2) {
if (HashDistance.compareHash(hash1, hash2) <= 0) {
return hash1;
}
return hash2;
},
isBitSet(hash, bitPos) {
return !!HashDistance.hashBit(hash, bitPos);
},
// 仅仅用于在网络上得到两个理论上应该相等的hash值,这时候不检查最高位
checkEqualHash(hash1, hash2) {
if (typeof hash1 !== 'number' || typeof hash2 !== 'number') {
return false;
}
return ((hash1 ^ hash2) & (~HashDistance.HIGH_BIT_MASK)) == 0; // +-0
},
compareHash(hash1, hash2) {
return hash1 - hash2;
},
// 按照到targetHashObj距离从近到远排列
sortByDistance(hashObjArray, targetHashObj) {
let targetHash = targetHashObj.hash || HashDistance.checkHash(targetHashObj.peerid);
hashObjArray.sort((obj1, obj2) => {
let distance1 = HashDistance.calcDistance(targetHash, obj1.hash || HashDistance.checkHash(obj1.peerid));
let distance2 = HashDistance.calcDistance(targetHash, obj2.hash || HashDistance.checkHash(obj2.peerid));
let compare = HashDistance.compareHash(distance1, distance2);
if (compare === 0) {
if (!obj1.peerid) {
return 1;
} else if (!obj2.peerid) {
return -1;
}
if (obj1.peerid > obj2.peerid) {
return 1;
}
return -1;
}
return compare;
});
// <TODO> 删除测试代码
let lastDistance = 0;
hashObjArray.forEach(obj => {
let distance = HashDistance.calcDistance(targetHash, obj.hash || HashDistance.checkHash(obj.peerid));
assert(distance >= lastDistance);
lastDistance = distance;
});
},
HASH_BIT_COUNT: 32,
HASH_MASK: 0xFFFFFFFF,//((1 << HASH_BIT_COUNT) - 1);
HIGH_BIT_MASK: 0x80000000,//(1 << (HASH_BIT_COUNT - 1));
HIGH_BIT_MASK16: 0x8000,//(1 << (HASH_BIT_COUNT - 1));
MAX_HASH: 0xFFFFFFFF, // HASH_MASK
};
// 32位序列号,解决序列号递增溢出问题,溢出后归0,并且在跟之前序列号比较时+0xFFFFFFFF还原
// 前置条件:不会短时间内产生溢出导致新序列号归0后再次追上旧的还生效的序列号
const SequenceU32 = {
random() {
return Math.floor(((Date.now() + Math.random() * 20160809) % 0xED89) * 32768);
},
compare(seq1, seq2) {
return SequenceU32.delta(seq1, seq2);
},
add(seq, delta) {
seq += delta;
return seq % 0xFFFFFFFF;
},
sub(seq, delta) {
seq -= delta;
return seq < 0? seq + 0xFFFFFFFF : seq;
},
delta(seq1, seq2) {
let delta = seq1 - seq2;
if (delta > 0x80000000) {
return delta - 0xFFFFFFFF;
} else if (delta < -0x80000000) {
return delta + 0xFFFFFFFF;
}
return delta;
},
}
module.exports.EndPoint = EndPoint;
module.exports.NetHelper = NetHelper;
module.exports.algorithm = algorithm;
module.exports.TimeHelper = TimeHelper;
module.exports.HashDistance = HashDistance;
module.exports.SequenceU32 = SequenceU32;
if (require.main === module) {
console.log(NetHelper.getLocalIPs(false));
let arr = [{a:3}, {a:5}, {a:6}, {a:7}, {a:9}, {a:12}, {a:15}];
let compare = (target, cursor) => target - cursor.a;
console.log(algorithm.binarySearch(12, arr, compare));
console.log(algorithm.binarySearch(15, arr, compare));
console.log(algorithm.binarySearch(3, arr, compare));
console.log(algorithm.binarySearch(1, arr, compare));
console.log(algorithm.binarySearch(17, arr, compare));
}
|
const urlToFetch = "https://cfw-takehome.developers.workers.dev/api/variants";
let urls = [];
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
/**
* Respond with hello worker text
* @param {Request} request
*/
async function handleRequest(request) {
let option = {
method: 'GET'
};
fetch(urlToFetch, option)
.then(res => {
console.log(res);
})
//return urls;
});
}
|
const path = require('path')
const fs = require('fs')
const cp = require('child_process')
let bookmarksDataCache = null
function getBookmarks (dataDir, browser) {
const profiles = ['Default', 'Profile 3', 'Profile 2', 'Profile 1']
const profile = profiles.find(profile => fs.existsSync(path.join(dataDir, profile, 'Bookmarks')))
if (!profile) return []
const bookmarkPath = path.join(dataDir, profile, 'Bookmarks')
const bookmarksData = []
const icon = browser + '.png'
try {
const data = JSON.parse(fs.readFileSync(bookmarkPath, 'utf-8'))
const getUrlData = (item, folder) => {
if (!item || !Array.isArray(item.children)) return
item.children.forEach(c => {
if (c.type === 'url') {
bookmarksData.push({
addAt: parseInt(c.date_added),
title: c.name || '',
description: (folder ? '「' + folder + '」' : '') + c.url,
url: c.url,
browser,
icon
})
} else if (c.type === 'folder') {
getUrlData(c, folder ? folder + ' - ' + c.name : c.name)
}
})
}
getUrlData(data.roots.bookmark_bar, '')
getUrlData(data.roots.other, '')
getUrlData(data.roots.synced, '')
} catch (e) {}
return bookmarksData
}
function openUrlByChrome (url) {
if (process.platform === 'win32') {
const suffix = `${path.sep}Google${path.sep}Chrome${path.sep}Application${path.sep}chrome.exe`
const prefixes = [process.env['PROGRAMFILES(X86)'], process.env.PROGRAMFILES, process.env.LOCALAPPDATA].filter(Boolean)
const prefix = prefixes.find(prefix => fs.existsSync(path.join(prefix, suffix)))
const chromeApp = path.join(prefix, suffix)
if (chromeApp) {
cp.spawn(chromeApp, [url], { detached: true })
} else {
window.utools.shellOpenExternal(url)
}
return
}
if (process.platform === 'darwin') {
const chromeApp = '/Applications/Google Chrome.app'
if (fs.existsSync(chromeApp)) {
cp.spawn('open', ['-a', chromeApp, url], { detached: true })
} else {
window.utools.shellOpenExternal(url)
}
}
}
function openUrlByEdge (url) {
if (process.platform === 'win32') {
const args = ['shell:AppsFolder\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge']
args.push(url)
cp.spawn('start', args, { shell: 'cmd.exe', detached: true }).once('error', () => {
window.utools.shellOpenExternal(url)
})
return
}
if (process.platform === 'darwin') {
const edgeApp = '/Applications/Microsoft Edge.app'
if (fs.existsSync(edgeApp)) {
cp.spawn('open', ['-a', edgeApp, url], { detached: true })
} else {
window.utools.shellOpenExternal(url)
}
}
}
window.exports = {
'bookmarks-search': {
mode: 'list',
args: {
enter: (action, callbackSetList) => {
bookmarksDataCache = []
let chromeDataDir
let edgeDataDir
if (process.platform === 'win32') {
chromeDataDir = path.join(process.env.LOCALAPPDATA, 'Google/Chrome/User Data')
edgeDataDir = path.join(process.env.LOCALAPPDATA, 'Microsoft/Edge/User Data')
} else if (process.platform === 'darwin') {
chromeDataDir = path.join(window.utools.getPath('appData'), 'Google/Chrome')
edgeDataDir = path.join(window.utools.getPath('appData'), 'Microsoft Edge')
} else { return }
if (fs.existsSync(chromeDataDir)) {
bookmarksDataCache.push(...getBookmarks(chromeDataDir, 'chrome'))
}
if (fs.existsSync(edgeDataDir)) {
bookmarksDataCache.push(...getBookmarks(edgeDataDir, 'edge'))
}
if (bookmarksDataCache.length > 0) {
bookmarksDataCache = bookmarksDataCache.sort((a, b) => a.addAt - b.addAt)
}
},
search: (action, searchWord, callbackSetList) => {
searchWord = searchWord.trim()
if (!searchWord) return callbackSetList()
if (/\S\s+\S/.test(searchWord)) {
const regexTexts = searchWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').split(/\s+/)
const searchRegexs = regexTexts.map(rt => new RegExp(rt, 'i'))
return callbackSetList(bookmarksDataCache.filter(x => (
!searchRegexs.find(r => x.title.search(r) === -1) || !searchRegexs.find(r => x.description.search(r) === -1)
)))
} else {
const regexText = searchWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const searchRegex = new RegExp(regexText, 'i')
return callbackSetList(bookmarksDataCache.filter(x => (
x.title.search(searchRegex) !== -1 || x.description.search(searchRegex) !== -1
)))
}
},
select: (action, itemData) => {
window.utools.hideMainWindow(false)
if (itemData.browser === 'chrome') {
openUrlByChrome(itemData.url)
} else {
openUrlByEdge(itemData.url)
}
window.utools.outPlugin()
}
}
}
}
|
define(function (require, exports, module) {/** @jsx React.DOM */
var React = require('react');
var classSet = require('./utils/classSet');
var BootstrapMixin = require('./BootstrapMixin');
var Alert = React.createClass({displayName: 'Alert',
mixins: [BootstrapMixin],
propTypes: {
onDismiss: React.PropTypes.func,
dismissAfter: React.PropTypes.number
},
getDefaultProps: function () {
return {
bsClass: 'alert',
bsStyle: 'info'
};
},
renderDismissButton: function () {
return (
React.DOM.button(
{type:"button",
className:"close",
onClick:this.props.onDismiss,
'aria-hidden':"true"},
" × "
)
);
},
render: function () {
var classes = this.getBsClassSet();
var isDismissable = !!this.props.onDismiss;
classes['alert-dismissable'] = isDismissable;
return this.transferPropsTo(
React.DOM.div( {className:classSet(classes)},
isDismissable ? this.renderDismissButton() : null,
this.props.children
)
);
},
componentDidMount: function() {
if (this.props.dismissAfter && this.props.onDismiss) {
this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter);
}
},
componentWillUnmount: function() {
clearTimeout(this.dismissTimer);
}
});
module.exports = Alert;
});
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvLayer(nn.Module):
def __init__(self, c_in):
super(ConvLayer, self).__init__()
padding = 1 if torch.__version__ >= '1.5.0' else 2
self.downConv = nn.Conv1d(in_channels=c_in,
out_channels=c_in,
kernel_size=3,
padding=padding,
padding_mode='circular')
self.norm = nn.BatchNorm1d(c_in)
self.activation = nn.ELU()
self.maxPool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)
def forward(self, x):
x = self.downConv(x.permute(0, 2, 1))
x = self.norm(x)
x = self.activation(x)
x = self.maxPool(x)
x = x.transpose(1, 2)
return x
class EncoderLayer(nn.Module):
def __init__(self, attention, d_model, d_ff=None, dropout=0.1, activation="relu"):
super(EncoderLayer, self).__init__()
d_ff = d_ff or 4 * d_model
self.attention = attention
self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1)
self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
self.activation = F.relu if activation == "relu" else F.gelu
def forward(self, x, attn_mask=None):
# x [B, L, D]
# x = x + self.dropout(self.attention(
# x, x, x,
# attn_mask = attn_mask
# ))
new_x, attn = self.attention(
x, x, x,
attn_mask=attn_mask
)
x = x + self.dropout(new_x)
y = x = self.norm1(x)
y = self.dropout(self.activation(self.conv1(y.transpose(-1, 1))))
y = self.dropout(self.conv2(y).transpose(-1, 1))
return self.norm2(x + y), attn
class Encoder(nn.Module):
def __init__(self, attn_layers, conv_layers=None, norm_layer=None):
super(Encoder, self).__init__()
self.attn_layers = nn.ModuleList(attn_layers)
self.conv_layers = nn.ModuleList(conv_layers) if conv_layers is not None else None
self.norm = norm_layer
def forward(self, x, attn_mask=None):
# x [B, L, D]
attns = []
if self.conv_layers is not None:
for attn_layer, conv_layer in zip(self.attn_layers, self.conv_layers):
x, attn = attn_layer(x, attn_mask=attn_mask)
x = conv_layer(x)
attns.append(attn)
x, attn = self.attn_layers[-1](x, attn_mask=attn_mask)
attns.append(attn)
else:
for attn_layer in self.attn_layers:
x, attn = attn_layer(x, attn_mask=attn_mask)
attns.append(attn)
if self.norm is not None:
x = self.norm(x)
return x, attns
class EncoderStack(nn.Module):
def __init__(self, encoders, inp_lens):
super(EncoderStack, self).__init__()
self.encoders = nn.ModuleList(encoders)
self.inp_lens = inp_lens
def forward(self, x, attn_mask=None):
# x [B, L, D]
x_stack = [];
attns = []
for i_len, encoder in zip(self.inp_lens, self.encoders):
inp_len = x.shape[1] // (2 ** i_len)
x_s, attn = encoder(x[:, -inp_len:, :])
x_stack.append(x_s);
attns.append(attn)
x_stack = torch.cat(x_stack, -2)
return x_stack, attns
|
import Transaction from '../../transaction';
import inherits from 'inherits';
const debug = require('debug')('knex:tx')
import * as helpers from '../../helpers';
import { assign } from 'lodash'
function Transaction_MySQL2() {
Transaction.apply(this, arguments)
}
inherits(Transaction_MySQL2, Transaction)
assign(Transaction_MySQL2.prototype, {
query(conn, sql, status, value) {
const t = this
const q = this.trxClient.query(conn, sql)
.catch(err => err.code === 'ER_SP_DOES_NOT_EXIST', function() {
helpers.warn(
'Transaction was implicitly committed, do not mix transactions and' +
'DDL with MySQL (#805)'
)
})
.catch(function(err) {
status = 2
value = err
t._completed = true
debug('%s error running transaction query', t.txid)
})
.tap(function() {
if (status === 1) t._resolver(value)
if (status === 2) t._rejecter(value)
})
if (status === 1 || status === 2) {
t._completed = true
}
return q;
}
})
export default Transaction_MySQL2
|
/* Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government retains certain rights in this software. */
import d3 from "d3";
import "jquery-ui";
$.widget("slycat.colorswitcher",
{
options:
{
colormap : "day",
},
_create: function()
{
var self = this;
this.color_maps =
{
"night":
{
"label": "Night",
"background": d3.rgb(128, 128, 128),
"null_color": "rgb(75,75,75)",
"opacity": "0.5",
"colors":
[
d3.rgb( 59, 76, 192),
d3.rgb( 68, 90, 204),
d3.rgb( 77, 104, 215),
d3.rgb( 87, 117, 225),
d3.rgb( 98, 130, 234),
d3.rgb(108, 142, 241),
d3.rgb(119, 154, 247),
d3.rgb(130, 165, 251),
d3.rgb(141, 176, 254),
d3.rgb(152, 185, 255),
d3.rgb(163, 194, 255),
d3.rgb(174, 201, 253),
d3.rgb(184, 208, 249),
d3.rgb(194, 213, 244),
d3.rgb(204, 217, 238),
d3.rgb(213, 219, 230),
d3.rgb(221, 221, 221),
d3.rgb(229, 216, 209),
d3.rgb(236, 211, 197),
d3.rgb(241, 204, 185),
d3.rgb(245, 196, 173),
d3.rgb(247, 187, 160),
d3.rgb(247, 177, 148),
d3.rgb(247, 166, 135),
d3.rgb(244, 154, 123),
d3.rgb(241, 141, 111),
d3.rgb(236, 127, 99),
d3.rgb(229, 112, 88),
d3.rgb(222, 96, 77),
d3.rgb(213, 80, 66),
d3.rgb(203, 62, 56),
d3.rgb(192, 40, 47),
d3.rgb(180, 4, 38),
]
},
"day":
{
"label": "Day",
"background": d3.rgb(255, 255, 255),
"null_color": "gray",
"opacity": "0.7",
"colors":
[
d3.rgb(100, 108, 234),
d3.rgb(115, 118, 240),
d3.rgb(128, 128, 244),
d3.rgb(140, 138, 248),
d3.rgb(151, 147, 250),
d3.rgb(161, 155, 251),
d3.rgb(169, 163, 251),
d3.rgb(177, 170, 250),
d3.rgb(184, 177, 248),
d3.rgb(189, 182, 245),
d3.rgb(193, 187, 241),
d3.rgb(197, 191, 236),
d3.rgb(199, 194, 230),
d3.rgb(200, 196, 224),
d3.rgb(201, 198, 216),
d3.rgb(200, 199, 208),
d3.rgb(198, 198, 198),
d3.rgb(210, 197, 195),
d3.rgb(220, 194, 192),
d3.rgb(229, 191, 187),
d3.rgb(236, 186, 181),
d3.rgb(243, 181, 175),
d3.rgb(248, 175, 168),
d3.rgb(251, 168, 160),
d3.rgb(254, 159, 152),
d3.rgb(255, 150, 143),
d3.rgb(255, 140, 133),
d3.rgb(253, 129, 123),
d3.rgb(250, 117, 112),
d3.rgb(246, 105, 101),
d3.rgb(240, 91, 90),
d3.rgb(233, 75, 78),
d3.rgb(225, 57, 66),
]
},
"rainbow":
{
"label": "Rainbow Night",
"background": d3.rgb(128, 128, 128),
"null_color": "rgb(75,75,75)",
"opacity": "0.6",
"colors":
[
d3.rgb(0, 0, 255),
d3.rgb(0, 255, 255),
d3.rgb(255, 255, 0),
d3.rgb(255, 0, 0),
]
},
"rainbow_day":
{
"label": "Rainbow Day",
"background": d3.rgb(255, 255, 255),
"null_color": "gray",
"opacity": "0.7",
"colors":
[
d3.rgb(0, 0, 255),
d3.rgb(0, 255, 255),
d3.rgb(255, 255, 0),
d3.rgb(255, 0, 0),
]
},
};
this.container = $("<div>")
.appendTo(this.element)
.append('<span class="label">Colors: </span>')
;
$.each(this.color_maps, function(key, value)
{
var button = $("<span>")
.addClass("color")
.toggleClass("selected", key == self.options.colormap)
.appendTo(self.container)
.attr("data-colormap", key)
.html(value.label)
.click(function()
{
if($(this).hasClass("selected"))
return;
self.options.colormap = this.getAttribute("data-colormap");
self.container.find(".color").removeClass("selected");
$(this).addClass("selected");
self.element.trigger("colormap-changed", [self.options.colormap]);
})
;
});
},
_setOption: function(key, value)
{
//console.log("slycat.colorswitcher._setOption()", key, value);
this.options[key] = value;
if(key == "colormap")
{
this.container.find(".color").removeClass("selected");
this.container.find("[data-colormap='" + this.options.colormap + "']").addClass("selected");
}
},
// Return a d3 rgb object with the suggested background color for the given color map.
get_background: function(name)
{
if(name === undefined)
name = this.options.colormap;
return this.color_maps[name].background;
},
// Return the null color value for the given color map.
get_null_color: function(name)
{
if(name === undefined)
name = this.options.colormap;
return this.color_maps[name]["null_color"];
},
// Return the suggested opacity value for the given color map.
get_opacity: function(name)
{
if(name === undefined)
name = this.options.colormap;
return this.color_maps[name].opacity;
},
// Return a d3 linear color scale with the current color map for the domain [0, 1].
// Callers should modify the domain by passing a min and max to suit their own needs.
get_color_scale: function(name, min, max)
{
if(name === undefined)
name = this.options.colormap;
if(min === undefined)
min = 0.0;
if(max === undefined)
max = 1.0;
var domain = []
var domain_scale = d3.scale.linear()
.domain([0, this.color_maps[name].colors.length-1])
.range([min, max]);
for(var i in this.color_maps[name].colors)
domain.push(domain_scale(i));
return d3.scale.linear().domain(domain).range(this.color_maps[name].colors);
},
// Deprecated
get_color_map: function(name, min, max)
{
return this.get_color_scale(name, min, max);
},
// Return a d3 ordinal color scale with the current color map for the domain [0, 1].
// Callers should modify the domain by passing an array of values to suit their own needs.
get_color_scale_ordinal: function(name, values)
{
if(name === undefined)
name = this.options.colormap;
if(values === undefined)
values = [0, 1];
var tempOrdinal = d3.scale.ordinal().domain(values).rangePoints([0, 100], 0);
var tempColorscale = this.get_color_scale(name, 0, 100);
var rgbRange = [];
for(var i=0; i<values.length; i++)
{
rgbRange.push( tempColorscale( tempOrdinal(values[i]) ) );
}
return d3.scale.ordinal().domain(values).range(rgbRange);
},
// Deprecated
get_color_map_ordinal: function(name, values)
{
return this.get_color_scale_ordinal(name, values);
},
get_gradient_data: function(name)
{
var self = this;
if(name === undefined)
name = this.options.colormap;
var colors = self.color_maps[name]["colors"];
var length = colors.length;
var data = [];
for(var i=0; i < length; i++){
data.push({offset: i*(100/(length-1)), color: colors[length-1-i],});
}
return data;
},
setUpColorMapsForAllColumns: function(name, columns)
{
for(var j = 0; j != columns.length; ++j)
{
columns[j].colorMap = this.get_color_scale(name, columns[j].columnMin, columns[j].columnMax);
}
}
});
|
export const endpoint = `http://localhost:3000/api/graphql`;
export const prodEndpoint = `https://burgers-menu.herokuapp.com/api/graphql`;
|
#!/usr/bin/env python
from lxml import etree
import urllib2
import re
import json
class Instance(object):
def __init__(self):
self.vpc = None
self.arch = ['x86_64']
self.ECU = 0
self.linux_virtualization_types = []
self.ebs_throughput = 0
self.ebs_iops = 0
self.max_bandwidth = 0
def to_dict(self):
d = dict(family=self.family,
instance_type=self.instance_type,
arch=self.arch,
vCPU=self.vCPU,
ECU=self.ECU,
memory=self.memory,
ebs_optimized=self.ebs_optimized,
ebs_throughput=self.ebs_throughput,
ebs_iops=self.ebs_iops,
max_bandwidth=self.max_bandwidth,
network_performance=self.network_performance,
enhanced_networking=self.enhanced_networking,
pricing=self.pricing,
vpc=self.vpc,
linux_virtualization_types=self.linux_virtualization_types,
generation=self.generation)
if self.ebs_only:
d['storage'] = None
else:
d['storage'] = dict(ssd=self.ssd,
devices=self.num_drives,
size=self.drive_size)
return d
def totext(elt):
s = etree.tostring(elt, method='text', encoding='unicode').strip()
return re.sub(r'\*\d$', '', s)
def parse_prev_generation_instance(tr):
i = Instance()
cols = tr.xpath('td')
assert len(cols) == 8, "Expected 8 columns in the table, but got %d" % len(cols)
i.family = totext(cols[0])
i.instance_type = totext(cols[1])
archs = totext(cols[2])
i.arch = []
if '32-bit' in archs:
i.arch.append('i386')
if '64-bit' in archs:
i.arch.append('x86_64')
assert i.arch, "No archs detected: %s" % (archs,)
i.vCPU = int(totext(cols[3]))
i.memory = float(totext(cols[4]))
storage = totext(cols[5])
m = re.search(r'(\d+)\s*x\s*([0-9,]+)?', storage)
i.ssd = False
if m:
i.ebs_only = False
i.num_drives = int(m.group(1))
i.drive_size = int(m.group(2).replace(',', ''))
i.ssd = 'SSD' in totext(cols[5])
else:
assert storage == 'EBS Only', "Unrecognized storage spec: %s" % (storage,)
i.ebs_only = True
i.ebs_optimized = totext(cols[6]).lower() == 'yes'
i.network_performance = totext(cols[7])
i.enhanced_networking = False
i.generation = 'previous'
# print "Parsed %s..." % (i.instance_type)
return i
def parse_instance(tr, inst2family):
i = Instance()
cols = tr.xpath('td')
assert len(cols) == 12, "Expected 12 columns in the table, but got %d" % len(cols)
i.instance_type = totext(cols[0])
i.family = inst2family.get(i.instance_type, "Unknown")
# Some t2 instances support 32-bit arch
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html#resize-limitations
if i.instance_type in ('t2.micro', 't2.small'):
i.arch.append('i386')
i.vCPU = int(totext(cols[1]))
i.memory = float(totext(cols[2]))
storage = totext(cols[3])
m = re.search(r'(\d+)\s*x\s*([0-9,]+)?', storage)
i.ssd = False
if m:
i.ebs_only = False
i.num_drives = int(m.group(1))
i.drive_size = int(m.group(2).replace(',', ''))
i.ssd = 'SSD' in totext(cols[3])
else:
assert storage == 'EBS Only', "Unrecognized storage spec: %s" % (storage,)
i.ebs_only = True
i.ebs_optimized = totext(cols[10]).lower() == 'yes'
i.network_performance = totext(cols[4])
i.enhanced_networking = totext(cols[11]).lower() == 'yes'
i.generation = 'current'
# print "Parsed %s..." % (i.instance_type)
return i
def _rindex_family(inst2family, details):
rows = details.xpath('tbody/tr')[0:]
for r in rows:
cols = r.xpath('td')
for i in totext(cols[1]).split('|'):
i = i.strip()
inst2family[i] = totext(cols[0])
def scrape_families():
inst2family = dict()
tree = etree.parse(urllib2.urlopen("http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html"), etree.HTMLParser())
details = tree.xpath('//div[@class="informaltable"]//table')[0]
hdrs = details.xpath('thead/tr')[0]
if totext(hdrs[0]).lower() == 'instance family' and 'current generation' in totext(hdrs[1]).lower():
_rindex_family(inst2family, details)
details = tree.xpath('//div[@class="informaltable"]//table')[1]
hdrs = details.xpath('thead/tr')[0]
if totext(hdrs[0]).lower() == 'instance family' and 'previous generation' in totext(hdrs[1]).lower():
_rindex_family(inst2family, details)
assert len(inst2family) > 0, "Failed to find instance family info"
return inst2family
def scrape_instances():
inst2family = scrape_families()
tree = etree.parse(urllib2.urlopen("http://aws.amazon.com/ec2/instance-types/"), etree.HTMLParser())
details = tree.xpath('//table')[9]
rows = details.xpath('tbody/tr')[1:]
assert len(rows) > 0, "Didn't find any table rows."
current_gen = [parse_instance(r, inst2family) for r in rows]
tree = etree.parse(urllib2.urlopen("http://aws.amazon.com/ec2/previous-generation/"), etree.HTMLParser())
details = tree.xpath('//table')[6]
rows = details.xpath('tbody/tr')[1:]
assert len(rows) > 0, "Didn't find any table rows."
prev_gen = [parse_prev_generation_instance(r) for r in rows]
return prev_gen + current_gen
def transform_size(size):
if size == 'u':
return 'micro'
if size == 'sm':
return 'small'
if size == 'med':
return 'medium'
m = re.search('^(x+)l$', size)
if m:
xs = len(m.group(1))
if xs == 1:
return 'xlarge'
else:
return str(xs) + 'xlarge'
assert size == 'lg', "Unable to parse size: %s" % (size,)
return 'large'
def transform_region(reg):
region_map = {
'eu-ireland': 'eu-west-1',
'eu-frankfurt': 'eu-central-1',
'apac-sin': 'ap-southeast-1',
'apac-syd': 'ap-southeast-2',
'apac-tokyo': 'ap-northeast-1'}
if reg in region_map:
return region_map[reg]
m = re.search(r'^([^0-9]*)(-(\d))?$', reg)
assert m, "Can't parse region: %s" % (reg,)
base = m.group(1)
num = m.group(3) or '1'
return base + "-" + num
def add_pricing(imap, data, platform, pricing_mode):
if pricing_mode == 'od':
add_ondemand_pricing(imap, data, platform)
elif pricing_mode == 'ri':
add_reserved_pricing(imap, data, platform)
def add_ondemand_pricing(imap, data, platform):
for region_spec in data['config']['regions']:
region = transform_region(region_spec['region'])
for t_spec in region_spec['instanceTypes']:
typename = t_spec['type']
for i_spec in t_spec['sizes']:
i_type = i_spec['size']
# As best I can tell, this type doesn't exist, but is
# in the pricing charts anyways.
if i_type == 'cc2.4xlarge':
continue
assert i_type in imap, "Unknown instance size: %s" % (i_type, )
inst = imap[i_type]
inst.pricing.setdefault(region, {})
# print "%s/%s" % (region, i_type)
inst.pricing[region].setdefault(platform, {})
for col in i_spec['valueColumns']:
inst.pricing[region][platform]['ondemand'] = col['prices']['USD']
# ECU is only available here
ecu = i_spec['ECU']
if ecu == 'variable':
inst.ECU = 0
else:
inst.ECU = float(ecu)
def add_reserved_pricing(imap, data, platform):
for region_spec in data['config']['regions']:
region = transform_region(region_spec['region'])
for t_spec in region_spec['instanceTypes']:
i_type = t_spec['type']
# As best I can tell, this type doesn't exist, but is
# in the pricing charts anyways.
if i_type == 'cc2.4xlarge':
continue
assert i_type in imap, "Unknown instance size: %s" % (i_type, )
inst = imap[i_type]
inst.pricing.setdefault(region, {})
# print "%s/%s" % (region, i_type)
inst.pricing[region].setdefault(platform, {})
inst.pricing[region][platform].setdefault('reserved', {})
termPricing = {}
for term in t_spec['terms']:
for po in term['purchaseOptions']:
for value in po['valueColumns']:
if value['name'] == 'effectiveHourly':
termPricing[term['term'] + '.' + po['purchaseOption']] = value['prices']['USD']
inst.pricing[region][platform]['reserved'] = termPricing
def add_pricing_info(instances):
pricing_modes = ['ri', 'od']
reserved_name_map = {
'linux': 'linux-unix-shared',
'mswin': 'windows-shared',
'mswinSQL': 'windows-with-sql-server-standard-shared',
'mswinSQLWeb': 'windows-with-sql-server-web-shared'
}
for i in instances:
i.pricing = {}
by_type = {i.instance_type: i for i in instances}
for platform in ['linux', 'mswin', 'mswinSQL', 'mswinSQLWeb']:
for pricing_mode in pricing_modes:
# current generation
if pricing_mode == 'od':
pricing_url = 'https://a0.awsstatic.com/pricing/1/deprecated/ec2/%s-od.json' % (platform,)
else:
pricing_url = 'http://a0.awsstatic.com/pricing/1/ec2/ri-v2/%s.min.js' % (reserved_name_map[platform],)
pricing = fetch_data(pricing_url)
add_pricing(by_type, pricing, platform, pricing_mode)
# previous generation
if pricing_mode == 'od':
pricing_url = 'http://a0.awsstatic.com/pricing/1/ec2/previous-generation/%s-od.min.js' % (platform,)
else:
pricing_url = 'http://a0.awsstatic.com/pricing/1/ec2/previous-generation/ri-v2/%s.min.js' % (reserved_name_map[platform],)
pricing = fetch_data(pricing_url)
add_pricing(by_type, pricing, platform, pricing_mode)
def fetch_data(url):
content = urllib2.urlopen(url).read()
try:
pricing = json.loads(content)
except ValueError:
# if the data isn't compatiable JSON, try to parse as jsonP
json_string = re.sub(r"(\w+):", r'"\1":', content[content.index('callback(') + 9 : -2]) # convert into valid json
pricing = json.loads(json_string)
return pricing
def add_eni_info(instances):
eni_url = "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html"
tree = etree.parse(urllib2.urlopen(eni_url), etree.HTMLParser())
table = tree.xpath('//div[@class="informaltable"]//table')[0]
rows = table.xpath('.//tr[./td]')
by_type = {i.instance_type: i for i in instances}
for r in rows:
instance_type = etree.tostring(r[0], method='text').strip()
max_enis = int(etree.tostring(r[1], method='text').strip())
ip_per_eni = int(etree.tostring(r[2], method='text').strip())
if instance_type not in by_type:
print "Unknown instance type: " + instance_type
continue
by_type[instance_type].vpc = {
'max_enis': max_enis,
'ips_per_eni': ip_per_eni}
def add_ebs_info(instances):
ebs_url = "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html"
tree = etree.parse(urllib2.urlopen(ebs_url), etree.HTMLParser())
table = tree.xpath('//div[@class="informaltable"]//table')[0]
rows = table.xpath('tbody/tr')
by_type = {i.instance_type: i for i in instances}
for row in rows:
cols = row.xpath('td')
instance_type = totext(cols[0]).split(' ')[0]
ebs_optimized_by_default = totext(cols[1]) == 'Yes'
ebs_throughput = int(totext(cols[2]).strip().replace(',', ''))
ebs_iops = int(totext(cols[3]).strip().replace(',', ''))
max_bandwidth = float(totext(cols[4]).strip().replace(',', ''))
if instance_type not in by_type:
print "Unknown instance type: " + instance_type
continue
by_type[instance_type].ebs_optimized_by_default = ebs_optimized_by_default
by_type[instance_type].ebs_throughput = ebs_throughput
by_type[instance_type].ebs_iops = ebs_iops
by_type[instance_type].max_bandwidth = max_bandwidth
def add_linux_ami_info(instances):
"""Add information about which virtualization options are supported.
Note that only HVM is supported for Windows instances so that info is not
given its own column.
"""
checkmark_char = u'\u2713'
url = "http://aws.amazon.com/amazon-linux-ami/instance-type-matrix/"
tree = etree.parse(urllib2.urlopen(url), etree.HTMLParser())
table = tree.xpath('//div[@class="aws-table "]/table')[0]
rows = table.xpath('.//tr[./td]')[1:] # ignore header
for r in rows:
supported_types = []
family_id = totext(r[0]).lower()
if not family_id:
continue
# We only check the primary EBS-backed values here since the 'storage'
# column will already be able to tell users whether or not the instance
# they're looking at can use EBS and/or instance-store AMIs.
if totext(r[1]) == checkmark_char:
supported_types.append('HVM')
if totext(r[3]) == checkmark_char:
supported_types.append('PV')
# Apply types for this instance family to all matching instances
for i in instances:
i_family_id = i.instance_type.split('.')[0]
if i_family_id == family_id:
i.linux_virtualization_types = supported_types
def scrape(data_file):
"""Scrape AWS to get instance data"""
print "Parsing instance types..."
all_instances = scrape_instances()
print "Parsing pricing info..."
add_pricing_info(all_instances)
print "Parsing ENI info..."
add_eni_info(all_instances)
print "Parsing EBS info..."
add_ebs_info(all_instances)
print "Parsing Linux AMI info..."
add_linux_ami_info(all_instances)
with open(data_file, 'w') as f:
json.dump([i.to_dict() for i in all_instances],
f,
indent=2,
separators=(',', ': '))
if __name__ == '__main__':
scrape('www/instances.json')
|
const express = require('express');
const moment = require('moment');
const nodemailer = require('nodemailer');
const router = express.Router();
const passport = require('passport');
const User = require('../models/user');
// index route
moment.locale();
router.get('/', (req, res) => {
res.render('index', { currentUser: req.user });
});
// show register form
router.get('/register', (req, res) => {
res.render('index/register', { errors: req.session.errors });
});
// handle sign up logic
router.post('/register', (req, res) => {
req.check('username', 'Username must contain between 3 and 20 letters.').matches(/^[a-z ]+$/i).notEmpty().isLength({ min: 3, max: 20 });
req.check('password', 'Password must be at least 6 characters long.').notEmpty().isLength({ min: 6 });
const errors = req.validationErrors();
if (errors) {
res.render('index/register', {
errors: errors,
});
} else {
User.register(new User({ username: req.body.username }), req.body.password, (err) => {
if (err) {
req.flash('error', `${err.message}`);
res.render('index/register', { errors: errors });
}
passport.authenticate('local')(req, res, () => {
req.flash('success', `Successfully signed up! Nice to meet you ${req.body.username}!`);
res.redirect('/');
});
});
}
});
// show login form
router.get('/login', (req, res) => {
res.render('index/login', { page: 'login' });
});
// handling login logic
router.post('/login', passport.authenticate('local',
{
successRedirect: '/posts/new',
failureRedirect: '/login',
failureFlash: true,
successFlash: 'Welcome to Work or Home!',
}), () => {
});
// logout route
router.get('/logout', (req, res) => {
req.logout();
req.flash('success', 'See you later!');
res.redirect('back');
});
// index route
router.get('/', (req, res) => {
res.render('index', { currentUser: req.user });
});
// contact page
router.get('/contact', (req, res) => {
res.render('index/contact');
});
const EMAIL_USER = process.env.EMAIL_USER;
const EMAIL_API_KEY = process.env.EMAIL_API_KEY;
router.post('/contact/send', (req, res) => {
const output = `
<h1>You have a new contact request</h1>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
nodemailer.createTestAccount(() => {
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
host: 'smtp.sendgrid.net',
port: 465,
auth: {
user: EMAIL_USER,
pass: EMAIL_API_KEY,
},
});
// setup email data with unicode symbols
const mailOptions = {
from: "'Work or Home' <workorhome@mail.com>", // sender address
to: 'ionitamihnea97@gmail.com', // list of receivers
subject: 'Work or Home - Contact Request', // Subject line
html: output, // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error) => {
if (error) {
req.flash('error', `${error.message}`);
res.render('back', { error: error.message });
}
req.flash('success', 'Successfully sent a mail! I will get back to you as soon as possible!');
res.redirect('/contact');
});
});
});
module.exports = router;
|
import React, {Component} from 'react';
const Home = React.createClass({
render() {
return (
<div className="#" style={{textAlign:"center"}}>
<h2>Search by GitHub UserName above</h2>
</div>
);
}
});
export default Home;
|
import React from 'react';
import CapsulingProfileProgressBar from '../../../../src/client/js/components/CapsulingProfileProgressBar';
import ReactTestUtils from 'react-testutils-additions';
describe('CapsulingProfileProgressBar', function () {
var instance;
describe('#render', function () {
beforeEach(function () {
instance = ReactTestUtils.renderIntoDocument(<CapsulingProfileProgressBar currentStep={2} />);
});
it('render 2 completed steps if current step is 3 out of 5 steps', function () {
expect(ReactTestUtils.find(instance, '.progress-scale .scale-entries .completed').length).toBe(2);
});
it('render 2 incomplete steps if current step is 3 out of 5 steps', function () {
expect(ReactTestUtils.find(instance, '.progress-scale .scale-entries .incomplete').length).toBe(2);
});
});
});
|
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-flow',
'@babel/preset-react'
],
plugins: [
'flow-react-proptypes'
]
}
|
import cv2
import numpy as np
import math
class PossibleChar:
def __init__(self, _contour):
self.contour = _contour
self.boundingRect = cv2.boundingRect(self.contour)
[intX, intY, intWidth, intHeight] = self.boundingRect
self.intBoundingRectX = intX
self.intBoundingRectY = intY
self.intBoundingRectWidth = intWidth
self.intBoundingRectHeight = intHeight
self.intBoundingRectArea = self.intBoundingRectWidth * self.intBoundingRectHeight
self.intCenterX = (self.intBoundingRectX + self.intBoundingRectX + self.intBoundingRectWidth) / 2
self.intCenterY = (self.intBoundingRectY + self.intBoundingRectY + self.intBoundingRectHeight) / 2
self.fltDiagonalSize = math.sqrt((self.intBoundingRectWidth ** 2) + (self.intBoundingRectHeight ** 2))
self.fltAspectRatio = float(self.intBoundingRectWidth) / float(self.intBoundingRectHeight)
|
'use strict';
class Logger {
constructor(verbose) {
this.verbose = 3 - verbose;
const levels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
// normalize verbose level
if (this.verbose < 0 ) this.verbose = 0;
if (this.verbose >= levels.length ) this.verbose = levels.length - 1;
//
const log4js = require('log4js');
log4js.configure({
appenders: { /*logfile: { type: 'file', filename: '/tmp/tln.log' }, */console: { type: 'stdout' } },
categories: { default: { appenders: [/*'logfile',*/ 'console'], level: levels[this.verbose] } }
});
this.logger = log4js.getLogger();
}
trace(...args) { this.logger.trace.apply(this.logger, args); }
debug(...args) { this.logger.debug.apply(this.logger, args); }
info(...args) { this.logger.info.apply(this.logger, args); }
warn(...args) { this.logger.warn.apply(this.logger, args); }
error(...args) { this.logger.error.apply(this.logger, args); }
fatal(...args) { this.logger.fatal.apply(this.logger, args); }
con(...args) { console.log.apply(console, args); }
}
module.exports.create = (verbose) => {
return new Logger(verbose);
}
|
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var BellTwoTone = { "icon": function render(primaryColor, secondaryColor) { return { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M512 220c-55.6 0-107.8 21.6-147.1 60.9S304 372.4 304 428v340h416V428c0-55.6-21.6-107.8-60.9-147.1S567.6 220 512 220zm280 208c0-141.1-104.3-257.8-240-277.2v.1c135.7 19.4 240 136 240 277.1zM472 150.9v-.1C336.3 170.2 232 286.9 232 428c0-141.1 104.3-257.7 240-277.1z", "fill": secondaryColor } }, { "tag": "path", "attrs": { "d": "M816 768h-24V428c0-141.1-104.3-257.7-240-277.1V112c0-22.1-17.9-40-40-40s-40 17.9-40 40v38.9c-135.7 19.4-240 136-240 277.1v340h-24c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h216c0 61.8 50.2 112 112 112s112-50.2 112-112h216c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM512 888c-26.5 0-48-21.5-48-48h96c0 26.5-21.5 48-48 48zm208-120H304V428c0-55.6 21.6-107.8 60.9-147.1S456.4 220 512 220c55.6 0 107.8 21.6 147.1 60.9S720 372.4 720 428v340z", "fill": primaryColor } }] }; }, "name": "bell", "theme": "twotone" };
exports.default = BellTwoTone;
|
import styled from 'styled-components/native';
export const Container = styled.View`
background-color: black;
align-items: center;
justify-content: center;
flex: 1;
`;
export const Img = styled.Image`
width: 100%;
min-height: 100%;
resize-mode: contain;
`;
|
'use strict';
requireApp('homescreen/test/unit/mock_xmlhttprequest.js');
requireApp('homescreen/test/unit/mock_homescreen.js');
requireApp('homescreen/test/unit/mock_iccHelper.js');
require('/shared/test/unit/mocks/mock_navigator_moz_settings.js');
// Unit tests for configurator library
requireApp('homescreen/js/configurator.js');
var mocksHelperForConfigurator = new MocksHelper([
'IccHelper',
'XMLHttpRequest',
'Homescreen'
]);
mocksHelperForConfigurator.init();
suite('configurator.js >', function() {
const KEY_SIM_ON_1ST_RUN = 'ftu.simPresentOnFirstBoot';
var SAVE_STATE_WAIT_TIMEOUT = 200;
var mocksHelper = mocksHelperForConfigurator;
var realSettings;
suiteSetup(function() {
mocksHelper.suiteSetup();
realSettings = navigator.mozSettings;
navigator.mozSettings = MockNavigatorSettings;
});
suiteTeardown(function() {
mocksHelper.suiteTeardown();
navigator.mozSettings = realSettings;
realSettings = null;
});
setup(function() {
mocksHelper.setup();
Configurator.load();
// We set up a wrong landing page index in order to check what its value
// will be 0 or 1 depending on different situations dealt by this suite
Homescreen.landingPage = -1;
IccHelper = MockIccHelper;
});
teardown(function() {
mocksHelper.teardown();
navigator.mozSettings.mTeardown();
});
function sendResponseText(text) {
MockXMLHttpRequest.mSendOnLoad({
responseText: text
});
}
function assertHomescreen(number) {
assert.equal(Homescreen.landingPage, number);
}
// helper to change single key-value of mozSettings
function changeSettings(key, value) {
var cset = {};
cset[key] = value;
navigator.mozSettings.createLock().set(cset);
}
/*
* It tests the public method "getSection" getting properties/values
*/
test('Sections >', function() {
sendResponseText('{ "search_page":{ "provider": "em","enabled": false },' +
'"tap_threshold": 10,' +
'"swipe": { "threshold": 0.4, "friction": 0.1,' +
'"transition_duration": 300 } }');
// These sections should be available
var searchPage = Configurator.getSection('search_page');
assert.equal(searchPage.provider, 'em');
assert.isFalse(searchPage.enabled);
assert.equal(Object.keys(searchPage).length, 2);
var tapThreshold = Configurator.getSection('tap_threshold');
assert.equal(tapThreshold, 10);
var swipe = Configurator.getSection('swipe');
assert.equal(swipe.threshold, 0.4);
assert.equal(swipe.friction, 0.1);
assert.equal(swipe.transition_duration, 300);
// This section should be undefined
assert.isUndefined(Configurator.getSection('petecan'));
});
/*
* It tests the public method "getSingleVariantApps" getting properties/values
*/
test('getSingleVariantApps >', function() {
sendResponseText('{ "search_page":{ "provider": "em","enabled": false },' +
'"tap_threshold": 10,' +
'"swipe": { "threshold": 0.4, "friction": 0.1,' +
'"transition_duration": 300 } }');
MockIccHelper.fireEvent('iccinfochange', '214', '007');
sendResponseText('{"214-007": [{"screen": 2,' +
'"manifestURL": "https://aHost/aMan1",' +
'"location": 15},' +
'{"screen": 2,' +
'"manifestURL": "https://aHost/aMan2",' +
'"location": 6},' +
'{"screen": 2,' +
'"manifestURL": "https://aHost/aMan3",' +
'"location": 3}],' +
'"214-006": [{"screen": 2,' +
'"manifestURL": "https://aHost/aMan4",' +
'"location": 3}]}');
var singleVariantApps = Configurator.getSingleVariantApps();
assert.isDefined(singleVariantApps['https://aHost/aMan3']);
assert.equal(singleVariantApps['https://aHost/aMan3'].screen, 2);
assert.equal(singleVariantApps['https://aHost/aMan3'].manifestURL,
'https://aHost/aMan3');
assert.equal(singleVariantApps['https://aHost/aMan3'].location, 3);
assert.equal(singleVariantApps['https://aHost/aManNoExist'], undefined);
assert.equal(singleVariantApps['https://aHost/aMan4'], undefined);
});
/*
* It checks what happens when there is an error parsing the SingleVariant
* configuration file
*/
test('SV - Error parsing configuration >', function() {
sendResponseText('{ "search_page":{ "provider": "em","enabled": false },');
MockIccHelper.fireEvent('iccinfochange', '214', '007');
sendResponseText('{Something that is wrong{');
var singleVariantApps = Configurator.getSingleVariantApps();
assert.equal(Object.keys(singleVariantApps).length, 0);
});
/*
* Checks isSimPresentOnFirstBoot function
*/
var testCases = [
{
'preValSet': undefined,
'expecValSet': true,
'title': KEY_SIM_ON_1ST_RUN +
'setting value is undefined - isSimPresentOnFirstBoot is true'
},
{
'preValSet': false,
'expecValSet': false,
'title': KEY_SIM_ON_1ST_RUN +
'setting value is false - isSimPresentOnFirstBoot is false'
},
{
'preValSet': true,
'expecValSet': true,
'title': KEY_SIM_ON_1ST_RUN +
'setting value is true - isSimPresentOnFirstBoot is true'
}
];
testCases.forEach(function(testCase) {
test(testCase.title, function(done) {
changeSettings(KEY_SIM_ON_1ST_RUN, testCase.preValSet);
Configurator.loadSettingSIMPresent();
setTimeout(function() {
assert.equal(Configurator.isSimPresentOnFirstBoot,
testCase.expecValSet);
done();
}, SAVE_STATE_WAIT_TIMEOUT);
});
});
/*
* It checks the conditions when there is NOT a search provider
*/
test('Search provider disabled >', function() {
sendResponseText('{ "search_page":{ "provider": "xx","enabled": false } }');
assertHomescreen(0);
});
/*
* It checks the conditions when there is a search provider and enable search
*/
test('Search provider enabled >', function() {
sendResponseText('{ "search_page":{ "provider": "em","enabled": true } }');
assert.isTrue(document.body.classList.contains('searchPageEnabled'));
assertHomescreen(0);
});
/*
* It checks what happens when there is an error parsing the configuration
*/
test('Error parsing configuration >', function() {
sendResponseText('{ merengue {');
assertHomescreen(0);
});
/*
* It checks what happens when there is an error loading the configuration
*/
test('Error loading configuration >', function() {
MockXMLHttpRequest.mSendError();
assertHomescreen(0);
});
});
|
/**
* @module
* @description
* Provides API for working with Angular views.
*/
//# sourceMappingURL=view.js.map
|
/*
* MainFooter Messages
*
* This contains all the text for the MainFooter component.
*/
import { defineMessages } from 'react-intl';
export const scope = 'app.components.MainFooter';
export default defineMessages({
header: {
id: `${scope}.header`,
defaultMessage: 'This is the MainFooter component!',
},
});
|