text
stringlengths 3
1.05M
|
---|
/**
* TESTE EPICS - TripAdvisor Parser
*
* @author Alexandre de Freitas Caetano <https://github.com/aledefreitas>
*/
/**
* Classe de data structure que faz um pool das conexões ativas
*
* @return {void}
*/
function ConnectionPool() {
/**
* Map contendo todas as conexões ativas
*
* @var {Map}
*/
this.connections = new Map();
};
/**
* Adiciona o socket da conexão do usuário identificado pelo session_id
*
* @param {string} session_id
* @param {socket} socket
*
* @return {boolean}
*/
ConnectionPool.prototype.add = function(session_id, socket) {
return this.connections.set(session_id, socket);
};
/**
* Retorna o socket do usuário selecionado
*
* @param {string} session_id
*
* @return {boolean} | {WebSocket.Socket}
*/
ConnectionPool.prototype.get = function(session_id) {
if(!session_id) return false;
return this.connections.get(session_id);
};
/**
* Deleta da Pool o socket de acordo com o session_id
*
* @param {string} session_id
*
* @return {boolean}
*/
ConnectionPool.prototype.delete = function(session_id) {
return this.connections.delete(session_id);
};
module.exports = new ConnectionPool();
|
#!/bin/env python3
import sys
def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs)
import os
import json
import ast
import re
from ARAX_response import ARAXResponse
from query_graph_info import QueryGraphInfo
class KnowledgeGraphInfo:
#### Constructor
def __init__(self):
self.response = None
self.message = None
self.n_nodes = None
self.n_edges = None
self.query_graph_id_node_status = None
self.query_graph_id_edge_status = None
self.node_map = {}
self.edge_map = {}
#### Top level decision maker for applying filters
def check_for_query_graph_tags(self, message, query_graph_info):
#### Define a default response
response = ARAXResponse()
self.response = response
self.message = message
response.debug(f"Checking KnowledgeGraph for QueryGraph tags")
#### Get shorter handles
knowledge_graph = message.knowledge_graph
nodes = knowledge_graph.nodes
edges = knowledge_graph.edges
#### Store number of nodes and edges
self.n_nodes = len(nodes)
self.n_edges = len(edges)
response.debug(f"Found {self.n_nodes} nodes and {self.n_edges} edges")
#### Clear the maps
self.node_map = { 'by_qnode_id': {} }
self.edge_map = { 'by_qedge_id': {} }
#### Loop through nodes computing some stats
n_nodes_with_query_graph_ids = 0
for key,node in nodes.items():
if node.qnode_id is None:
continue
n_nodes_with_query_graph_ids += 1
#### Place an entry in the node_map
if node.qnode_id not in self.node_map['by_qnode_id']:
self.node_map['by_qnode_id'][node.qnode_id] = {}
self.node_map['by_qnode_id'][node.qnode_id][key] = 1
#### Tally the stats
if n_nodes_with_query_graph_ids == self.n_nodes:
self.query_graph_id_node_status = 'all nodes have query_graph_ids'
elif n_nodes_with_query_graph_ids == 0:
self.query_graph_id_node_status = 'no nodes have query_graph_ids'
else:
self.query_graph_id_node_status = 'only some nodes have query_graph_ids'
response.info(f"In the KnowledgeGraph, {self.query_graph_id_node_status}")
#### Loop through edges computing some stats
n_edges_with_query_graph_ids = 0
for key,edge in edges.items():
if edge.qedge_id is None:
continue
n_edges_with_query_graph_ids += 1
#### Place an entry in the edge_map
if edge.qedge_id not in self.edge_map['by_qedge_id']:
self.edge_map['by_qedge_id'][edge.qedge_id] = {}
self.edge_map['by_qedge_id'][edge.qedge_id][key] = 1
if n_edges_with_query_graph_ids == self.n_edges:
self.query_graph_id_edge_status = 'all edges have query_graph_ids'
elif n_edges_with_query_graph_ids == 0:
self.query_graph_id_edge_status = 'no edges have query_graph_ids'
else:
self.query_graph_id_edge_status = 'only some edges have query_graph_ids'
response.info(f"In the KnowledgeGraph, {self.query_graph_id_edge_status}")
#### Return the response
return response
#### Top level decision maker for applying filters
def add_query_graph_tags(self, message, query_graph_info):
#### Define a default response
response = ARAXResponse()
self.response = response
self.message = message
response.debug(f"Adding temporary QueryGraph ids to KnowledgeGraph")
#### Get shorter handles
knowedge_graph = message.knowledge_graph
nodes = knowedge_graph.nodes
edges = knowedge_graph.edges
#### Loop through nodes adding qnode_ids
for key,node in nodes.items():
#### If there is not qnode_id, then determine what it should be and add it
if node.qnode_id is None:
categorys = node.category
#### Find a matching category in the QueryGraph for this node
if categorys is None:
response.error(f"KnowledgeGraph node {key} does not have a category. This should never be", error_code="NodeMissingCategory")
return response
n_found_categorys = 0
found_category = None
for node_category in categorys:
if node_category in query_graph_info.node_category_map:
n_found_categorys += 1
found_category = node_category
#### If we did not find exactly one matching category, error out
if n_found_categorys == 0:
response.error(f"Tried to find categorys '{categorys}' for KnowledgeGraph node {key} in query_graph_info, but did not find it", error_code="NodeCategoryMissingInQueryGraph")
return response
elif n_found_categorys > 1:
response.error(f"Tried to find categorys '{categorys}' for KnowledgeGraph node {key} in query_graph_info, and found multiple matches. This is ambiguous", error_code="MultipleNodeCategorysInQueryGraph")
return response
#### Else add it
node.qnode_id = query_graph_info.node_category_map[found_category]
#### Loop through the edges adding qedge_ids
for key,edge in edges.items():
#### Check to see if there is already a qedge_id attribute on the edge
if edge.qedge_id is None:
#### If there isn't a predicate or can't find it in the query_graph, error out
if edge.predicate is None:
response.error(f"KnowledgeGraph edge {key} does not have a predicate. This should never be", error_code="EdgeMissingPredicate")
return response
if edge.predicate not in query_graph_info.edge_predicate_map:
response.error(f"Tried to find predicate '{edge.predicate}' for KnowledgeGraph node {key} in query_graph_info, but did not find it", error_code="EdgePredicateMissingInQueryGraph")
return response
#### Else add it
edge.qedge_id = query_graph_info.edge_predicate_map[edge.predicate]
#### Return the response
return response
##########################################################################################
def main():
#### Create a response object
response = ARAXResponse()
#### Create an ActionsParser object
from actions_parser import ActionsParser
actions_parser = ActionsParser()
#### Set a simple list of actions
actions_list = [
"filter(start_node=1, maximum_results=10, minimum_confidence=0.5)",
"return(message=true,store=false)"
]
#### Parse the action_list and print the result
result = actions_parser.parse(actions_list)
response.merge(result)
if result.status != 'OK':
print(response.show(level=ARAXResponse.DEBUG))
return response
actions = result.data['actions']
#### Read message #2 from the database. This should be the acetaminophen proteins query result message
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../UI/Feedback")
from RTXFeedback import RTXFeedback
araxdb = RTXFeedback()
message_dict = araxdb.getMessage(2)
#### The stored message comes back as a dict. Transform it to objects
from ARAX_messenger import ARAXMessenger
message = ARAXMessenger().from_dict(message_dict)
#### Asses some information about the QueryGraph
query_graph_info = QueryGraphInfo()
result = query_graph_info.assess(message)
response.merge(result)
if result.status != 'OK':
print(response.show(level=ARAXResponse.DEBUG))
return response
#print(json.dumps(ast.literal_eval(repr(query_graph_info.node_order)),sort_keys=True,indent=2))
#### Assess some information about the KnowledgeGraph
knowledge_graph_info = KnowledgeGraphInfo()
result = knowledge_graph_info.check_for_query_graph_tags(message,query_graph_info)
response.merge(result)
if result.status != 'OK':
print(response.show(level=ARAXResponse.DEBUG))
return response
#### Try to add query_graph_ids to the KnowledgeGraph
result = knowledge_graph_info.add_query_graph_tags(message,query_graph_info)
response.merge(result)
if result.status != 'OK':
print(response.show(level=ARAXResponse.DEBUG))
return response
#### Reassess some information about the KnowledgeGraph
result = knowledge_graph_info.check_for_query_graph_tags(message,query_graph_info)
response.merge(result)
if result.status != 'OK':
print(response.show(level=ARAXResponse.DEBUG))
return response
print(response.show(level=ARAXResponse.DEBUG))
tmp = { 'query_graph_id_node_status': knowledge_graph_info.query_graph_id_node_status, 'query_graph_id_edge_status': knowledge_graph_info.query_graph_id_edge_status,
'n_nodes': knowledge_graph_info.n_nodes, 'n_edges': knowledge_graph_info.n_edges }
#print(json.dumps(message.to_dict(),sort_keys=True,indent=2))
print(json.dumps(ast.literal_eval(repr(tmp)),sort_keys=True,indent=2))
if __name__ == "__main__": main()
|
// messageReactionAdd.js
// Triggers every time a reaction is added on the server. This one specifically
// triggers on a reaction added to the topics message.
const topicsOp = require("../lib/topic.js");
module.exports = async (client, reaction, user) => {
// Get the message and channel this reaction is from.
const msg = reaction.message;
const channel = msg.channel;
// Only process the reaction if this is the topics message and it's a user reaction.
if (!user.bot && topicsOp.isTopicsMessage(msg)) {
// Get respective role for emoji.
const emoji = reaction.emoji.name;
const roleName = client.emojiToRole[emoji];
let role = channel.guild.roles.cache.find(role => role.name === roleName);
// If role doesn't exist, create the role.
if (!role) {
role = await channel.guild.roles.create({
data: {
name: roleName
}});
}
// Add role to user.
channel.guild.members.cache.get(user.id).roles.add(role);
}
}
|
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataAwsMskCluster = void 0;
const JSII_RTTI_SYMBOL_1 = Symbol.for("jsii.rtti");
const cdktf = require("cdktf");
/**
* Represents a {@link https://www.terraform.io/docs/providers/aws/d/msk_cluster.html aws_msk_cluster}.
*
* @stability stable
*/
class DataAwsMskCluster extends cdktf.TerraformDataSource {
// ===========
// INITIALIZER
// ===========
/**
* Create a new {@link https://www.terraform.io/docs/providers/aws/d/msk_cluster.html aws_msk_cluster} Data Source.
*
* @param scope The scope in which to define this construct.
* @param id The scoped construct ID.
* @stability stable
*/
constructor(scope, id, config) {
super(scope, id, {
terraformResourceType: 'aws_msk_cluster',
terraformGeneratorMetadata: {
providerName: 'aws'
},
provider: config.provider,
dependsOn: config.dependsOn,
count: config.count,
lifecycle: config.lifecycle
});
this._clusterName = config.clusterName;
this._tags = config.tags;
}
// ==========
// ATTRIBUTES
// ==========
// arn - computed: true, optional: false, required: false
/**
* @stability stable
*/
get arn() {
return this.getStringAttribute('arn');
}
// bootstrap_brokers - computed: true, optional: false, required: false
/**
* @stability stable
*/
get bootstrapBrokers() {
return this.getStringAttribute('bootstrap_brokers');
}
// bootstrap_brokers_sasl_iam - computed: true, optional: false, required: false
/**
* @stability stable
*/
get bootstrapBrokersSaslIam() {
return this.getStringAttribute('bootstrap_brokers_sasl_iam');
}
// bootstrap_brokers_sasl_scram - computed: true, optional: false, required: false
/**
* @stability stable
*/
get bootstrapBrokersSaslScram() {
return this.getStringAttribute('bootstrap_brokers_sasl_scram');
}
// bootstrap_brokers_tls - computed: true, optional: false, required: false
/**
* @stability stable
*/
get bootstrapBrokersTls() {
return this.getStringAttribute('bootstrap_brokers_tls');
}
/**
* @stability stable
*/
get clusterName() {
return this.getStringAttribute('cluster_name');
}
/**
* @stability stable
*/
set clusterName(value) {
this._clusterName = value;
}
// Temporarily expose input value. Use with caution.
/**
* @stability stable
*/
get clusterNameInput() {
return this._clusterName;
}
// id - computed: true, optional: true, required: false
/**
* @stability stable
*/
get id() {
return this.getStringAttribute('id');
}
// kafka_version - computed: true, optional: false, required: false
/**
* @stability stable
*/
get kafkaVersion() {
return this.getStringAttribute('kafka_version');
}
// number_of_broker_nodes - computed: true, optional: false, required: false
/**
* @stability stable
*/
get numberOfBrokerNodes() {
return this.getNumberAttribute('number_of_broker_nodes');
}
/**
* @stability stable
*/
get tags() {
// Getting the computed value is not yet implemented
return this.interpolationForAttribute('tags');
}
/**
* @stability stable
*/
set tags(value) {
this._tags = value;
}
/**
* @stability stable
*/
resetTags() {
this._tags = undefined;
}
// Temporarily expose input value. Use with caution.
/**
* @stability stable
*/
get tagsInput() {
return this._tags;
}
// zookeeper_connect_string - computed: true, optional: false, required: false
/**
* @stability stable
*/
get zookeeperConnectString() {
return this.getStringAttribute('zookeeper_connect_string');
}
// =========
// SYNTHESIS
// =========
/**
* @stability stable
*/
synthesizeAttributes() {
return {
cluster_name: cdktf.stringToTerraform(this._clusterName),
tags: cdktf.hashMapper(cdktf.anyToTerraform)(this._tags),
};
}
}
exports.DataAwsMskCluster = DataAwsMskCluster;
_a = JSII_RTTI_SYMBOL_1;
DataAwsMskCluster[_a] = { fqn: "@cdktf/provider-aws.msk.DataAwsMskCluster", version: "3.0.1" };
// =================
// STATIC PROPERTIES
// =================
/**
* @stability stable
*/
DataAwsMskCluster.tfResourceType = "aws_msk_cluster";
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGF0YS1hd3MtbXNrLWNsdXN0ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbXNrL2RhdGEtYXdzLW1zay1jbHVzdGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBR0EsK0JBQStCOzs7Ozs7QUFXL0IsTUFBYSxpQkFBa0IsU0FBUSxLQUFLLENBQUMsbUJBQW1CO0lBTzlELGNBQWM7SUFDZCxjQUFjO0lBQ2QsY0FBYzs7Ozs7Ozs7SUFHZCxZQUFtQixLQUFnQixFQUFFLEVBQVUsRUFBRSxNQUErQjtRQUM5RSxLQUFLLENBQUMsS0FBSyxFQUFFLEVBQUUsRUFBRTtZQUNmLHFCQUFxQixFQUFFLGlCQUFpQjtZQUN4QywwQkFBMEIsRUFBRTtnQkFDMUIsWUFBWSxFQUFFLEtBQUs7YUFDcEI7WUFDRCxRQUFRLEVBQUUsTUFBTSxDQUFDLFFBQVE7WUFDekIsU0FBUyxFQUFFLE1BQU0sQ0FBQyxTQUFTO1lBQzNCLEtBQUssRUFBRSxNQUFNLENBQUMsS0FBSztZQUNuQixTQUFTLEVBQUUsTUFBTSxDQUFDLFNBQVM7U0FDNUIsQ0FBQyxDQUFDO1FBQ0gsSUFBSSxDQUFDLFlBQVksR0FBRyxNQUFNLENBQUMsV0FBVyxDQUFDO1FBQ3ZDLElBQUksQ0FBQyxLQUFLLEdBQUcsTUFBTSxDQUFDLElBQUksQ0FBQztJQUMzQixDQUFDO0lBRUQsYUFBYTtJQUNiLGFBQWE7SUFDYixhQUFhO0lBRWIseURBQXlEOzs7O0lBQ3pELElBQVcsR0FBRztRQUNaLE9BQU8sSUFBSSxDQUFDLGtCQUFrQixDQUFDLEtBQUssQ0FBQyxDQUFDO0lBQ3hDLENBQUM7SUFFRCx1RUFBdUU7Ozs7SUFDdkUsSUFBVyxnQkFBZ0I7UUFDekIsT0FBTyxJQUFJLENBQUMsa0JBQWtCLENBQUMsbUJBQW1CLENBQUMsQ0FBQztJQUN0RCxDQUFDO0lBRUQsZ0ZBQWdGOzs7O0lBQ2hGLElBQVcsdUJBQXVCO1FBQ2hDLE9BQU8sSUFBSSxDQUFDLGtCQUFrQixDQUFDLDRCQUE0QixDQUFDLENBQUM7SUFDL0QsQ0FBQztJQUVELGtGQUFrRjs7OztJQUNsRixJQUFXLHlCQUF5QjtRQUNsQyxPQUFPLElBQUksQ0FBQyxrQkFBa0IsQ0FBQyw4QkFBOEIsQ0FBQyxDQUFDO0lBQ2pFLENBQUM7SUFFRCwyRUFBMkU7Ozs7SUFDM0UsSUFBVyxtQkFBbUI7UUFDNUIsT0FBTyxJQUFJLENBQUMsa0JBQWtCLENBQUMsdUJBQXVCLENBQUMsQ0FBQztJQUMxRCxDQUFDOzs7O0lBSUQsSUFBVyxXQUFXO1FBQ3BCLE9BQU8sSUFBSSxDQUFDLGtCQUFrQixDQUFDLGNBQWMsQ0FBQyxDQUFDO0lBQ2pELENBQUM7Ozs7SUFDRCxJQUFXLFdBQVcsQ0FBQyxLQUFhO1FBQ2xDLElBQUksQ0FBQyxZQUFZLEdBQUcsS0FBSyxDQUFDO0lBQzVCLENBQUM7SUFDRCxvREFBb0Q7Ozs7SUFDcEQsSUFBVyxnQkFBZ0I7UUFDekIsT0FBTyxJQUFJLENBQUMsWUFBWSxDQUFDO0lBQzNCLENBQUM7SUFFRCx1REFBdUQ7Ozs7SUFDdkQsSUFBVyxFQUFFO1FBQ1gsT0FBTyxJQUFJLENBQUMsa0JBQWtCLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDdkMsQ0FBQztJQUVELG1FQUFtRTs7OztJQUNuRSxJQUFXLFlBQVk7UUFDckIsT0FBTyxJQUFJLENBQUMsa0JBQWtCLENBQUMsZUFBZSxDQUFDLENBQUM7SUFDbEQsQ0FBQztJQUVELDRFQUE0RTs7OztJQUM1RSxJQUFXLG1CQUFtQjtRQUM1QixPQUFPLElBQUksQ0FBQyxrQkFBa0IsQ0FBQyx3QkFBd0IsQ0FBQyxDQUFDO0lBQzNELENBQUM7Ozs7SUFJRCxJQUFXLElBQUk7UUFDYixvREFBb0Q7UUFDcEQsT0FBTyxJQUFJLENBQUMseUJBQXlCLENBQUMsTUFBTSxDQUFRLENBQUM7SUFDdkQsQ0FBQzs7OztJQUNELElBQVcsSUFBSSxDQUFDLEtBQW9EO1FBQ2xFLElBQUksQ0FBQyxLQUFLLEdBQUcsS0FBSyxDQUFDO0lBQ3JCLENBQUM7Ozs7SUFDTSxTQUFTO1FBQ2QsSUFBSSxDQUFDLEtBQUssR0FBRyxTQUFTLENBQUM7SUFDekIsQ0FBQztJQUNELG9EQUFvRDs7OztJQUNwRCxJQUFXLFNBQVM7UUFDbEIsT0FBTyxJQUFJLENBQUMsS0FBSyxDQUFDO0lBQ3BCLENBQUM7SUFFRCw4RUFBOEU7Ozs7SUFDOUUsSUFBVyxzQkFBc0I7UUFDL0IsT0FBTyxJQUFJLENBQUMsa0JBQWtCLENBQUMsMEJBQTBCLENBQUMsQ0FBQztJQUM3RCxDQUFDO0lBRUQsWUFBWTtJQUNaLFlBQVk7SUFDWixZQUFZOzs7O0lBRUYsb0JBQW9CO1FBQzVCLE9BQU87WUFDTCxZQUFZLEVBQUUsS0FBSyxDQUFDLGlCQUFpQixDQUFDLElBQUksQ0FBQyxZQUFZLENBQUM7WUFDeEQsSUFBSSxFQUFFLEtBQUssQ0FBQyxVQUFVLENBQUMsS0FBSyxDQUFDLGNBQWMsQ0FBQyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUM7U0FDekQsQ0FBQztJQUNKLENBQUM7O0FBbkhILDhDQW9IQzs7O0FBbEhDLG9CQUFvQjtBQUNwQixvQkFBb0I7QUFDcEIsb0JBQW9COzs7O0FBQ0csZ0NBQWMsR0FBVyxpQkFBaUIsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8vIGdlbmVyYXRlZCBmcm9tIHRlcnJhZm9ybSByZXNvdXJjZSBzY2hlbWFcblxuaW1wb3J0IHsgQ29uc3RydWN0IH0gZnJvbSAnY29uc3RydWN0cyc7XG5pbXBvcnQgKiBhcyBjZGt0ZiBmcm9tICdjZGt0Zic7XG5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcbmV4cG9ydCBpbnRlcmZhY2UgRGF0YUF3c01za0NsdXN0ZXJDb25maWcgZXh0ZW5kcyBjZGt0Zi5UZXJyYWZvcm1NZXRhQXJndW1lbnRzIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcbiAgcmVhZG9ubHkgY2x1c3Rlck5hbWU6IHN0cmluZztcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFxuICByZWFkb25seSB0YWdzPzogeyBba2V5OiBzdHJpbmddOiBzdHJpbmcgfSB8IGNka3RmLklSZXNvbHZhYmxlO1xufVxuXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcbmV4cG9ydCBjbGFzcyBEYXRhQXdzTXNrQ2x1c3RlciBleHRlbmRzIGNka3RmLlRlcnJhZm9ybURhdGFTb3VyY2Uge1xuXG4gIC8vID09PT09PT09PT09PT09PT09XG4gIC8vIFNUQVRJQyBQUk9QRVJUSUVTXG4gIC8vID09PT09PT09PT09PT09PT09XG4gIHB1YmxpYyBzdGF0aWMgcmVhZG9ubHkgdGZSZXNvdXJjZVR5cGU6IHN0cmluZyA9IFwiYXdzX21za19jbHVzdGVyXCI7XG5cbiAgLy8gPT09PT09PT09PT1cbiAgLy8gSU5JVElBTElaRVJcbiAgLy8gPT09PT09PT09PT1cblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcbiAgcHVibGljIGNvbnN0cnVjdG9yKHNjb3BlOiBDb25zdHJ1Y3QsIGlkOiBzdHJpbmcsIGNvbmZpZzogRGF0YUF3c01za0NsdXN0ZXJDb25maWcpIHtcbiAgICBzdXBlcihzY29wZSwgaWQsIHtcbiAgICAgIHRlcnJhZm9ybVJlc291cmNlVHlwZTogJ2F3c19tc2tfY2x1c3RlcicsXG4gICAgICB0ZXJyYWZvcm1HZW5lcmF0b3JNZXRhZGF0YToge1xuICAgICAgICBwcm92aWRlck5hbWU6ICdhd3MnXG4gICAgICB9LFxuICAgICAgcHJvdmlkZXI6IGNvbmZpZy5wcm92aWRlcixcbiAgICAgIGRlcGVuZHNPbjogY29uZmlnLmRlcGVuZHNPbixcbiAgICAgIGNvdW50OiBjb25maWcuY291bnQsXG4gICAgICBsaWZlY3ljbGU6IGNvbmZpZy5saWZlY3ljbGVcbiAgICB9KTtcbiAgICB0aGlzLl9jbHVzdGVyTmFtZSA9IGNvbmZpZy5jbHVzdGVyTmFtZTtcbiAgICB0aGlzLl90YWdzID0gY29uZmlnLnRhZ3M7XG4gIH1cblxuICAvLyA9PT09PT09PT09XG4gIC8vIEFUVFJJQlVURVNcbiAgLy8gPT09PT09PT09PVxuXG4gIC8vIGFybiAtIGNvbXB1dGVkOiB0cnVlLCBvcHRpb25hbDogZmFsc2UsIHJlcXVpcmVkOiBmYWxzZVxuICBwdWJsaWMgZ2V0IGFybigpIHtcbiAgICByZXR1cm4gdGhpcy5nZXRTdHJpbmdBdHRyaWJ1dGUoJ2FybicpO1xuICB9XG5cbiAgLy8gYm9vdHN0cmFwX2Jyb2tlcnMgLSBjb21wdXRlZDogdHJ1ZSwgb3B0aW9uYWw6IGZhbHNlLCByZXF1aXJlZDogZmFsc2VcbiAgcHVibGljIGdldCBib290c3RyYXBCcm9rZXJzKCkge1xuICAgIHJldHVybiB0aGlzLmdldFN0cmluZ0F0dHJpYnV0ZSgnYm9vdHN0cmFwX2Jyb2tlcnMnKTtcbiAgfVxuXG4gIC8vIGJvb3RzdHJhcF9icm9rZXJzX3Nhc2xfaWFtIC0gY29tcHV0ZWQ6IHRydWUsIG9wdGlvbmFsOiBmYWxzZSwgcmVxdWlyZWQ6IGZhbHNlXG4gIHB1YmxpYyBnZXQgYm9vdHN0cmFwQnJva2Vyc1Nhc2xJYW0oKSB7XG4gICAgcmV0dXJuIHRoaXMuZ2V0U3RyaW5nQXR0cmlidXRlKCdib290c3RyYXBfYnJva2Vyc19zYXNsX2lhbScpO1xuICB9XG5cbiAgLy8gYm9vdHN0cmFwX2Jyb2tlcnNfc2FzbF9zY3JhbSAtIGNvbXB1dGVkOiB0cnVlLCBvcHRpb25hbDogZmFsc2UsIHJlcXVpcmVkOiBmYWxzZVxuICBwdWJsaWMgZ2V0IGJvb3RzdHJhcEJyb2tlcnNTYXNsU2NyYW0oKSB7XG4gICAgcmV0dXJuIHRoaXMuZ2V0U3RyaW5nQXR0cmlidXRlKCdib290c3RyYXBfYnJva2Vyc19zYXNsX3NjcmFtJyk7XG4gIH1cblxuICAvLyBib290c3RyYXBfYnJva2Vyc190bHMgLSBjb21wdXRlZDogdHJ1ZSwgb3B0aW9uYWw6IGZhbHNlLCByZXF1aXJlZDogZmFsc2VcbiAgcHVibGljIGdldCBib290c3RyYXBCcm9rZXJzVGxzKCkge1xuICAgIHJldHVybiB0aGlzLmdldFN0cmluZ0F0dHJpYnV0ZSgnYm9vdHN0cmFwX2Jyb2tlcnNfdGxzJyk7XG4gIH1cblxuICAvLyBjbHVzdGVyX25hbWUgLSBjb21wdXRlZDogZmFsc2UsIG9wdGlvbmFsOiBmYWxzZSwgcmVxdWlyZWQ6IHRydWVcbiAgcHJpdmF0ZSBfY2x1c3Rlck5hbWU/OiBzdHJpbmc7IFxuICBwdWJsaWMgZ2V0IGNsdXN0ZXJOYW1lKCkge1xuICAgIHJldHVybiB0aGlzLmdldFN0cmluZ0F0dHJpYnV0ZSgnY2x1c3Rlcl9uYW1lJyk7XG4gIH1cbiAgcHVibGljIHNldCBjbHVzdGVyTmFtZSh2YWx1ZTogc3RyaW5nKSB7XG4gICAgdGhpcy5fY2x1c3Rlck5hbWUgPSB2YWx1ZTtcbiAgfVxuICAvLyBUZW1wb3JhcmlseSBleHBvc2UgaW5wdXQgdmFsdWUuIFVzZSB3aXRoIGNhdXRpb24uXG4gIHB1YmxpYyBnZXQgY2x1c3Rlck5hbWVJbnB1dCgpIHtcbiAgICByZXR1cm4gdGhpcy5fY2x1c3Rlck5hbWU7XG4gIH1cblxuICAvLyBpZCAtIGNvbXB1dGVkOiB0cnVlLCBvcHRpb25hbDogdHJ1ZSwgcmVxdWlyZWQ6IGZhbHNlXG4gIHB1YmxpYyBnZXQgaWQoKSB7XG4gICAgcmV0dXJuIHRoaXMuZ2V0U3RyaW5nQXR0cmlidXRlKCdpZCcpO1xuICB9XG5cbiAgLy8ga2Fma2FfdmVyc2lvbiAtIGNvbXB1dGVkOiB0cnVlLCBvcHRpb25hbDogZmFsc2UsIHJlcXVpcmVkOiBmYWxzZVxuICBwdWJsaWMgZ2V0IGthZmthVmVyc2lvbigpIHtcbiAgICByZXR1cm4gdGhpcy5nZXRTdHJpbmdBdHRyaWJ1dGUoJ2thZmthX3ZlcnNpb24nKTtcbiAgfVxuXG4gIC8vIG51bWJlcl9vZl9icm9rZXJfbm9kZXMgLSBjb21wdXRlZDogdHJ1ZSwgb3B0aW9uYWw6IGZhbHNlLCByZXF1aXJlZDogZmFsc2VcbiAgcHVibGljIGdldCBudW1iZXJPZkJyb2tlck5vZGVzKCkge1xuICAgIHJldHVybiB0aGlzLmdldE51bWJlckF0dHJpYnV0ZSgnbnVtYmVyX29mX2Jyb2tlcl9ub2RlcycpO1xuICB9XG5cbiAgLy8gdGFncyAtIGNvbXB1dGVkOiB0cnVlLCBvcHRpb25hbDogdHJ1ZSwgcmVxdWlyZWQ6IGZhbHNlXG4gIHByaXZhdGUgX3RhZ3M/OiB7IFtrZXk6IHN0cmluZ106IHN0cmluZyB9IHwgY2RrdGYuSVJlc29sdmFibGU7IFxuICBwdWJsaWMgZ2V0IHRhZ3MoKSB7XG4gICAgLy8gR2V0dGluZyB0aGUgY29tcHV0ZWQgdmFsdWUgaXMgbm90IHlldCBpbXBsZW1lbnRlZFxuICAgIHJldHVybiB0aGlzLmludGVycG9sYXRpb25Gb3JBdHRyaWJ1dGUoJ3RhZ3MnKSBhcyBhbnk7XG4gIH1cbiAgcHVibGljIHNldCB0YWdzKHZhbHVlOiB7IFtrZXk6IHN0cmluZ106IHN0cmluZyB9IHwgY2RrdGYuSVJlc29sdmFibGUpIHtcbiAgICB0aGlzLl90YWdzID0gdmFsdWU7XG4gIH1cbiAgcHVibGljIHJlc2V0VGFncygpIHtcbiAgICB0aGlzLl90YWdzID0gdW5kZWZpbmVkO1xuICB9XG4gIC8vIFRlbXBvcmFyaWx5IGV4cG9zZSBpbnB1dCB2YWx1ZS4gVXNlIHdpdGggY2F1dGlvbi5cbiAgcHVibGljIGdldCB0YWdzSW5wdXQoKSB7XG4gICAgcmV0dXJuIHRoaXMuX3RhZ3M7XG4gIH1cblxuICAvLyB6b29rZWVwZXJfY29ubmVjdF9zdHJpbmcgLSBjb21wdXRlZDogdHJ1ZSwgb3B0aW9uYWw6IGZhbHNlLCByZXF1aXJlZDogZmFsc2VcbiAgcHVibGljIGdldCB6b29rZWVwZXJDb25uZWN0U3RyaW5nKCkge1xuICAgIHJldHVybiB0aGlzLmdldFN0cmluZ0F0dHJpYnV0ZSgnem9va2VlcGVyX2Nvbm5lY3Rfc3RyaW5nJyk7XG4gIH1cblxuICAvLyA9PT09PT09PT1cbiAgLy8gU1lOVEhFU0lTXG4gIC8vID09PT09PT09PVxuXG4gIHByb3RlY3RlZCBzeW50aGVzaXplQXR0cmlidXRlcygpOiB7IFtuYW1lOiBzdHJpbmddOiBhbnkgfSB7XG4gICAgcmV0dXJuIHtcbiAgICAgIGNsdXN0ZXJfbmFtZTogY2RrdGYuc3RyaW5nVG9UZXJyYWZvcm0odGhpcy5fY2x1c3Rlck5hbWUpLFxuICAgICAgdGFnczogY2RrdGYuaGFzaE1hcHBlcihjZGt0Zi5hbnlUb1RlcnJhZm9ybSkodGhpcy5fdGFncyksXG4gICAgfTtcbiAgfVxufVxuIl19 |
#!/usr/bin/env python3
import sys
import os
import tempfile
from pathlib import Path
from subprocess import check_output, run, CalledProcessError, DEVNULL
from contextlib import contextmanager
from collections import defaultdict
from itertools import zip_longest
# https://stackoverflow.com/questions/431684/how-do-i-change-directory-cd-in-python
@contextmanager
def changedir(dir):
prevdir = os.getcwd()
try:
os.chdir(os.path.expanduser(str(dir)))
yield
finally:
os.chdir(prevdir)
def extract_jar_all(jar, tofolder):
run(["unzip", "-nqqq", str(jar), "-d", str(tofolder)], stderr=DEVNULL)
def extract_jar(jar, tofolder, files=[]):
run(["unzip", "-nqqq", str(jar), "-d", str(tofolder)] + [f for f in files if f], stderr=DEVNULL)
def deleteFile(tofolder, nam):
run(["rm", str(tofolder)+'/'+str(nam)], stderr=DEVNULL)
def deleteDir(tofolder, nam):
if len(os.listdir(str(tofolder)+'/'+nam)) == 0:
run(["rm", str(tofolder)+'/'+str(nam)], stderr=DEVNULL)
def make_jar(absjar, fromfolder):
with changedir(fromfolder):
run(["jar", "cf", str(absjar), "."])
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def main():
"""Given a list of jars print a list of files join the files in one jar
These two commands are adjoint.
$ unjar.py join app+lib.jar app.jar lib.jar > files.txt
$ unjar.py split app+lib.jar app.jar lib.jar < files.text
"""
_, cmd, target, *args = sys.argv
if cmd == "join":
with tempfile.TemporaryDirectory() as stage_folder:
files = set()
for jar in args:
extract_jar(jar, stage_folder)
added = set(a.relative_to(stage_folder) for a in Path(stage_folder).rglob("**/*")) - files
for a in added:
print(jar, a)
files |= added
make_jar(os.path.realpath(target), stage_folder)
elif cmd == "split":
dist = defaultdict(set)
for line in sys.stdin.readlines():
jarname, filename = line.split()
dist[jarname].add(filename)
for n in args:
if(n=='app.jar'):
with tempfile.TemporaryDirectory() as stage_folder:
extract_jar_all(target, stage_folder)
for x in reversed(sorted(dist['lib.jar'])):
if os.path.isdir(str(stage_folder)+'/'+x):
deleteDir(stage_folder, x)
else:
deleteFile(stage_folder, x)
make_jar(os.path.realpath(n), stage_folder)
if(n=='lib.jar'):
with tempfile.TemporaryDirectory() as stage_folder:
for x in grouper(sorted(dist[n]), 10, ""):
extract_jar(target, stage_folder, files=x)
make_jar(os.path.realpath(n), stage_folder)
else:
sys.stderr.write("Expected 'join' or 'split' as initial command.\n")
if __name__ == "__main__":
main()
|
/*global describe:true, it:true, before:true, after:true */
var
demand = require('must'),
fivebeans = require('../index'),
fs = require('fs'),
util = require('util')
;
//-------------------------------------------------------------
describe('FiveBeansRunner', function()
{
describe('constructor', function()
{
it('throws when not given an id', function()
{
function shouldThrow()
{
var r = new fivebeans.runner();
}
shouldThrow.must.throw(Error);
});
it('throws when not given a config path', function()
{
function shouldThrow()
{
var r = new fivebeans.runner('test');
}
shouldThrow.must.throw(Error);
});
it('throws if given a config path that does not exist', function()
{
function shouldThrow()
{
var r = new fivebeans.runner('test', '/not/a/real/path.yml');
}
shouldThrow.must.throw(Error);
});
it('creates a runner when given valid options', function()
{
var r = new fivebeans.runner('test', 'test/fixtures/runner.yml');
r.must.have.property('worker');
r.id.must.equal('test');
r.configpath.must.equal(__dirname + '/fixtures/runner.yml');
});
});
describe('readConfiguration()', function()
{
it('throws when the config requires non-existing handlers', function()
{
var r = new fivebeans.runner('test', 'test/fixtures/badconfig.yml');
function shouldThrow()
{
var config = r.readConfiguration();
}
shouldThrow.must.throw(Error);
});
it('returns a config object for a good config', function()
{
var r = new fivebeans.runner('test', 'test/fixtures/runner.yml');
var config = r.readConfiguration();
config.must.be.an.object();
config.must.have.property('beanstalkd');
config.beanstalkd.host.must.equal('localhost');
config.watch.must.be.an.array();
config.ignoreDefault.must.equal(true);
});
});
describe('createWorker()', function()
{
var worker;
it('returns a worker', function()
{
var r = new fivebeans.runner('test', 'test/fixtures/runner.yml');
worker = r.createWorker();
worker.must.exist();
worker.must.be.an.object();
(worker instanceof fivebeans.worker).must.equal(true);
});
it('started the worker', function(done)
{
worker.stopped.must.equal(false);
worker.client.must.exist();
worker.on('stopped', done);
worker.stop();
})
});
describe('go()', function()
{
it('creates and starts a worker', function(done)
{
var r = new fivebeans.runner('test', 'test/fixtures/runner.yml');
r.go();
r.worker.must.exist();
r.worker.client.must.exist();
r.worker.on('stopped', done);
r.worker.stop();
});
});
});
|
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import TimePicker from '@/components/myComponents/TimePicker'
import {
Form,
Input,
DatePicker,
Select,
Button,
message,
Card,
InputNumber,
Radio,
Icon,
Tooltip,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../Forms/style.less';
import { router } from 'umi';
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
@connect(({ loading }) => ({
submitting: loading.effects['activitysend/add'],
}))
@Form.create()
class BasicForms extends PureComponent {
handleSubmit = e => {
const { dispatch, form } = this.props;
e.preventDefault();
form.validateFieldsAndScroll((err, values) => {
if (!err) {
dispatch({
type: 'activitysend/add',
payload: values,
});
message.success('添加成功');
router.push(`/profile/tagmanager`)
}
});
};
render() {
const { submitting } = this.props;
console.log(submitting);
const {
form: { getFieldDecorator, getFieldValue },
} = this.props;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 7 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 12 },
md: { span: 10 },
},
};
const submitFormLayout = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 10, offset: 7 },
},
};
return (
<PageHeaderWrapper title="新增标签">
<Card bordered={false}>
<Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
<FormItem {...formItemLayout} label="标签名称">
{getFieldDecorator('name', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.comname.required' }),
},
],
})(<Input placeholder={formatMessage({ id: 'form.title.placeholder' })} />)}
</FormItem>
<FormItem {...formItemLayout} label="标签说明">
{getFieldDecorator('detail', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.bannername.required' }),
},
],
})(<Input placeholder={formatMessage({ id: 'form.title.placeholder' })} />)}
</FormItem>
{/* <FormItem {...formItemLayout} label={<FormattedMessage id="是否展示" />}>
{getFieldDecorator('type', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.bannertype.required' }),
},
],
})(
<Select placeholder="请选择" style={{ width: '100%' }}>
<Option value="1">是</Option>
<Option value="2">否</Option>
</Select>
)}
</FormItem> */}
<FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
<Button type="primary" htmlType="submit" loading={submitting}>
提交
</Button>
</FormItem>
</Form>
</Card>
</PageHeaderWrapper>
);
}
}
export default BasicForms;
|
/* jshint expr:true */
import { expect } from 'chai';
import {
describeModule,
it
} from 'ember-mocha';
import Ember from 'ember';
describeModule(
'service:config',
'Unit: Service: config',
{
// Specify the other units that are required for this test.
// needs: ['service:foo']
},
function () {
// Replace this with your real tests.
it('exists', function () {
const service = this.subject();
expect(service).to.be.ok;
});
it('correctly parses a client secret', function () {
Ember.$('<meta>').attr('name', 'env-clientSecret')
.attr('content', '23e435234423')
.appendTo('head');
const service = this.subject();
expect(service.get('clientSecret')).to.equal('23e435234423');
});
}
);
|
import React from 'react';
import classnames from 'classnames';
import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import styles from './styles.module.css';
function Home() {
const context = useDocusaurusContext();
const { siteConfig = {} } = context;
return (
<Layout
title={`Hello from ${siteConfig.title}`}
description="Description will go into a meta tag in <head />"
>
<header
className={classnames('hero hero--primary', styles.heroBanner)}
>
<div className="container">
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
className={classnames(
'button button--outline button--secondary button--lg',
styles.getStarted
)}
to={useBaseUrl('docs/overview')}
>
Get Started
</Link>
</div>
</div>
</header>
<main>
<section className={styles.features}>
<div className="container" style={{ textAlign: 'center' }}>
<h3>
⚠️ Work in progress. Expect some updates the next
days!
</h3>
</div>
</section>
</main>
</Layout>
);
}
export default Home;
|
// ============================================================
// NoovolariOutRun: copyright 2019 Alessandro Gaggia - beSharp
// objects: class objects that can be spawned in the map.
// ============================================================
/**
* Line is an object that represent a line of the road,
* ideally with its outside border object.
**/
class Line {
constructor() {
this.x = 0;
this.y = 0;
this.z = 0;
this.X = 0;
this.Y = 0;
this.W = 0;
this.curve = 0; // this value is used for curving the road
this.scale = 0; // this is used to simulate perspective
this.ltree = true;
this.rtree = true;
this.lpanel = true;
this.rpanel = true;
this.fuelorcar = false;
this.elements = []; // elements inside the lines, like trees, you, the cars...
this.special = null;
}
// This is a little complex, after we have defined a 'camera view'
// we use the matrix values to change the scale
// And the viewing frustrum end in the viewmatrix
project(camX, camY, camZ) {
this.scale = camD / (this.z - camZ); // the scale is given by the dimension of the forward vector in relation to camera dimension
this.X = (1 + this.scale * (this.x - camX)) * halfWidth;
this.Y = Math.ceil( (1 - this.scale * (this.y - camY)) * height / 2 );
this.W = this.scale * roadW * halfWidth;
}
// We 'clean' all the elements child of line!
clearSprites() {
for(let e of this.elements)
e.style.background = 'transparent';
}
// We draw the road
drawSprite(depth, layer, sprite, offset, offsetY) {
let destX = this.X + this.scale * halfWidth * offset;
let destY = this.Y + 4;
if(offsetY !== undefined) { destY += offsetY; }
let destW = sprite.width * this.W / 265;
let destH = sprite.height * this.W / 265;
destX += destW * offset;
destY += destH * -1;
// Draw the quad, note that we use basic css properties to do that
let obj = (layer instanceof Element) ? layer : this.elements[layer + 6];
obj.style.background = `url('${sprite.src}') no-repeat`;
obj.style.backgroundSize = `${destW}px ${destH}px`;
obj.style.left = destX + `px`;
obj.style.top = destY + `px`;
obj.style.width = destW + `px`;
obj.style.height = destH + `px`;
obj.style.zIndex = depth;
}
}
/** A simple car object */
class Car {
constructor(pos, type, lane) {
this.pos = pos; // its position
this.type = type; // the sprite of car
this.lane = lane; // the lane we want the car to appear in
var element = document.createElement('div'); // we hold the car in a div
road.appendChild(element); // road is a global object
this.element = element; // we set element as part of the object
}
}
/** A simple fuel object */
class Fuel {
constructor(pos, type, lane) {
this.pos = pos; // its position
this.type = type; // the sprite of fuel
this.lane = lane; // the lane we want the car to appear in
var element = document.createElement('div'); // we hold the car in a div
road.appendChild(element); // road is a global object
this.element = element; // we set element as part of the object
}
getFuel() {
return tankBonus; // is global
}
}
/** Audio CLass for managing audio in the game, very simple */
class Audio {
constructor(mapName) {
this.audioCtx = new AudioContext();
this.mapName = mapName;
// volume
this.destination = this.audioCtx.createGain();
this.volume = 1;
this.destination.connect( this.audioCtx.destination );
this.files = {};
let _self = this;
this.load(noovolariOutRun.ASSETS.AUDIO[this.mapName].theme, `theme-${mapName}`, function(key) {
// We create a sound buffer for our theme song
let source = _self.audioCtx.createBufferSource();
source.buffer = _self.files[key];
// We set common sound properties, note that this is pretty standard, so feel free to note and copy/paste anytime you need it
let gainNode = _self.audioCtx.createGain();
gainNode.gain.value = .6;
source.connect(gainNode);
gainNode.connect(_self.destination);
// ...aaaand we loop the theme
source.loop = true;
source.start(0);
});
}
// Volume levels
get volume() { return this.destination.gain.value; }
set volume(level) { this.destination.gain.value = level; }
// Stop Audio
stop() {
this.audioCtx.close();
}
// Play audio
play(key, pitch) {
if (this.files[key]) {
let source = this.audioCtx.createBufferSource();
source.buffer = this.files[key];
source.connect(this.destination);
if(pitch)
source.detune.value = pitch;
source.start(0);
} else
this.load(key, () => this.play(key));
}
// Load an audio file and call a callback when ready
load(src, key, callback) {
let _self = this;
let request = new XMLHttpRequest();
request.open('GET', src, true);
request.responseType = 'arraybuffer';
request.onload = function() {
_self.audioCtx.decodeAudioData(request.response, function(beatportBuffer) {
_self.files[key] = beatportBuffer;
callback(key);
}, function() {})
}
request.send();
}
} |
import os
import warnings
from dataclasses import dataclass
from pathlib import Path
from typing import (
Any,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Tuple,
overload,
)
from typing_extensions import Literal
from yarl import URL
from .config import Config
from .parsing_utils import LocalImage, RemoteImage, TagOption, _ImageNameParser
from .url_utils import _check_scheme, _extract_path, _normalize_uri, uri_from_cli
from .utils import NoPublicConstructor
@dataclass(frozen=True)
class SecretFile:
secret_uri: URL
container_path: str
@dataclass(frozen=True)
class Volume:
storage_uri: URL
container_path: str
read_only: bool = False
@dataclass(frozen=True)
class DiskVolume:
disk_uri: URL
container_path: str
read_only: bool = False
@dataclass(frozen=True)
class VolumeParseResult:
volumes: Sequence[Volume]
secret_files: Sequence[SecretFile]
disk_volumes: Sequence[DiskVolume]
# backward compatibility
def __len__(self) -> int:
warnings.warn(
"tuple-like access to client.parse.volumes() result is deprecated "
"and scheduled for removal in future Neuro CLI release. "
"Please access by attribute names) instead, "
"e.g. client.parse.volumes().secret_files",
DeprecationWarning,
stacklevel=2,
)
return 2
@overload
def __getitem__(self, idx: Literal[0]) -> Sequence[Volume]:
pass
@overload
def __getitem__(self, idx: Literal[1]) -> Sequence[SecretFile]:
pass
def __getitem__(self, idx: Any) -> Any:
warnings.warn(
"tuple-like access to client.parse.volumes() result is deprecated "
"and scheduled for removal in future Neuro CLI release. "
"Please access by attribute names) instead, "
"e.g. client.parse.volumes().secret_files",
DeprecationWarning,
stacklevel=2,
)
if idx == 0:
return self.volumes
elif idx == 1:
return self.secret_files
else:
raise IndexError(idx)
@dataclass(frozen=True)
class EnvParseResult:
env: Dict[str, str]
secret_env: Dict[str, URL]
class Parser(metaclass=NoPublicConstructor):
def __init__(self, config: Config) -> None:
self._config = config
def _parse_generic_volume(
self, volume: str, allow_rw_spec: bool = True, resource_name: str = "volume"
) -> Tuple[str, str, bool]:
parts = volume.split(":")
read_only = False
if allow_rw_spec and len(parts) == 4:
if parts[-1] not in ["ro", "rw"]:
raise ValueError(f"Wrong ReadWrite/ReadOnly mode spec for '{volume}'")
read_only = parts.pop() == "ro"
elif len(parts) != 3:
raise ValueError(f"Invalid {resource_name} specification '{volume}'")
container_path = parts.pop()
raw_uri = ":".join(parts)
return raw_uri, container_path, read_only
def volume(self, volume: str, cluster_name: Optional[str] = None) -> Volume:
raw_uri, container_path, read_only = self._parse_generic_volume(volume)
storage_uri = uri_from_cli(
raw_uri,
self._config.username,
cluster_name or self._config.cluster_name,
allowed_schemes=("storage",),
)
return Volume(
storage_uri=storage_uri, container_path=container_path, read_only=read_only
)
def _build_volumes(
self, input_volumes: List[str], cluster_name: Optional[str] = None
) -> List[Volume]:
if "HOME" in input_volumes:
raise ValueError("--volume=HOME no longer supported")
if "ALL" in input_volumes:
raise ValueError("--volume=ALL no longer supported")
return [self.volume(vol, cluster_name) for vol in input_volumes]
def _build_secret_files(
self, input_volumes: List[str], cluster_name: Optional[str] = None
) -> List[SecretFile]:
secret_files: List[SecretFile] = []
for volume in input_volumes:
raw_uri, container_path, _ = self._parse_generic_volume(
volume, allow_rw_spec=False, resource_name="secret file"
)
secret_uri = self._parse_secret_resource(raw_uri, cluster_name)
secret_files.append(SecretFile(secret_uri, container_path))
return secret_files
def _parse_secret_resource(
self, uri: str, cluster_name: Optional[str] = None
) -> URL:
return uri_from_cli(
uri,
self._config.username,
cluster_name or self._config.cluster_name,
allowed_schemes=("secret",),
)
def _build_disk_volumes(
self, input_volumes: List[str], cluster_name: Optional[str] = None
) -> List[DiskVolume]:
disk_volumes: List[DiskVolume] = []
for volume in input_volumes:
raw_uri, container_path, read_only = self._parse_generic_volume(
volume, allow_rw_spec=True, resource_name="disk volume"
)
disk_uri = self._parse_disk_resource(raw_uri, cluster_name)
disk_volumes.append(DiskVolume(disk_uri, container_path, read_only))
return disk_volumes
def _parse_disk_resource(self, uri: str, cluster_name: Optional[str] = None) -> URL:
return uri_from_cli(
uri,
self._config.username,
cluster_name or self._config.cluster_name,
allowed_schemes=("disk",),
)
def _get_image_parser(self, cluster_name: Optional[str] = None) -> _ImageNameParser:
registry = {
cluster.name: cluster.registry_url
for cluster in self._config.clusters.values()
}
return _ImageNameParser(
self._config.username, cluster_name or self._config.cluster_name, registry
)
def local_image(self, image: str) -> LocalImage:
return self._get_image_parser().parse_as_local_image(image)
def remote_image(
self,
image: str,
*,
tag_option: TagOption = TagOption.DEFAULT,
cluster_name: Optional[str] = None,
) -> RemoteImage:
return self._get_image_parser(cluster_name).parse_remote(
image, tag_option=tag_option
)
def _local_to_remote_image(
self, image: LocalImage, cluster_name: Optional[str] = None
) -> RemoteImage:
return self._get_image_parser(cluster_name).convert_to_neuro_image(image)
def _remote_to_local_image(self, image: RemoteImage) -> LocalImage:
return self._get_image_parser().convert_to_local_image(image)
def env(
self, env: Sequence[str], env_file: Sequence[str] = ()
) -> Tuple[Dict[str, str], Dict[str, URL]]:
warnings.warn(
"client.parse.env() method is deprecated and scheduled for removal "
"in future Neuro CLI release, please use client.parse.envs() instead",
DeprecationWarning,
stacklevel=2,
)
ret = self.envs(env, env_file)
return ret.env, ret.secret_env
def envs(
self,
env: Sequence[str],
env_file: Sequence[str] = (),
cluster_name: Optional[str] = None,
) -> EnvParseResult:
env_dict = self._build_env(env, env_file)
secret_env_dict = self._extract_secret_env(env_dict, cluster_name)
return EnvParseResult(
env=env_dict,
secret_env=secret_env_dict,
)
def _build_env(
self, env: Sequence[str], env_file: Sequence[str] = ()
) -> Dict[str, str]:
lines: List[str] = []
for filename in env_file:
lines.extend(_read_lines(filename))
lines.extend(env)
env_dict = {}
for line in lines:
splitted = line.split("=", 1)
name = splitted[0]
if len(splitted) == 1:
val = os.environ.get(splitted[0], "")
else:
val = splitted[1]
env_dict[name] = val
return env_dict
def _extract_secret_env(
self, env_dict: Dict[str, str], cluster_name: Optional[str] = None
) -> Dict[str, URL]:
secret_env_dict = {}
for name, val in env_dict.copy().items():
if val.startswith("secret:"):
secret_env_dict[name] = self._parse_secret_resource(val, cluster_name)
del env_dict[name]
return secret_env_dict
def volumes(
self, volume: Sequence[str], cluster_name: Optional[str] = None
) -> VolumeParseResult:
# N.B. Preserve volumes order when splitting the whole 'volumes' sequence.
secret_files = []
disk_volumes = []
volumes = []
for vol in volume:
if vol.startswith("secret:"):
secret_files.append(vol)
elif vol.startswith("disk:"):
disk_volumes.append(vol)
else:
volumes.append(vol)
return VolumeParseResult(
volumes=self._build_volumes(volumes, cluster_name),
secret_files=self._build_secret_files(secret_files, cluster_name),
disk_volumes=self._build_disk_volumes(disk_volumes, cluster_name),
)
def uri_to_str(self, uri: URL) -> str:
return str(uri)
def str_to_uri(
self,
uri: str,
*,
allowed_schemes: Iterable[str] = (),
cluster_name: Optional[str] = None,
short: bool = False,
) -> URL:
ret = uri_from_cli(
uri,
self._config.username,
cluster_name or self._config.cluster_name,
allowed_schemes=allowed_schemes,
)
if short:
ret = self._short(ret)
return ret
def uri_to_path(self, uri: URL) -> Path:
if uri.scheme != "file":
raise ValueError(
f"Invalid scheme '{uri.scheme}:' (only 'file:' is allowed)"
)
return _extract_path(uri)
def path_to_uri(
self,
path: Path,
) -> URL:
return uri_from_cli(
str(path),
self._config.username,
self._config.cluster_name,
allowed_schemes=("file",),
)
def normalize_uri(
self,
uri: URL,
*,
allowed_schemes: Iterable[str] = (),
cluster_name: Optional[str] = None,
short: bool = False,
) -> URL:
_check_scheme(uri.scheme, allowed_schemes)
ret = _normalize_uri(
uri,
self._config.username,
cluster_name or self._config.cluster_name,
)
if short:
ret = self._short(ret)
return ret
def _short(self, uri: URL) -> URL:
ret = uri
if uri.scheme != "file":
if ret.host == self._config.cluster_name and ret.parts[:2] == (
"/",
self._config.username,
):
ret = URL.build(
scheme=ret.scheme, host="", path="/".join(ret.parts[2:])
)
else:
# file scheme doesn't support relative URLs.
pass
while ret.path.endswith("/") and ret.path != "/":
# drop trailing slashes if any
ret = URL.build(scheme=ret.scheme, host=ret.host or "", path=ret.path[:-1])
return ret
def split_blob_uri(self, uri: URL) -> Tuple[str, str, str]:
uri = self.normalize_uri(uri)
cluster_name = uri.host
assert cluster_name
parts = uri.path.lstrip("/").split("/", 2)
if len(parts) == 1:
raise ValueError(f"Blob uri doesn't contain bucket name: {uri}")
if len(parts) == 3:
_, bucket_id, key = parts
else:
_, bucket_id = parts
key = ""
return cluster_name, bucket_id, key
def _read_lines(env_file: str) -> Iterator[str]:
with open(env_file, encoding="utf-8-sig") as ef:
lines = ef.read().splitlines()
for line in lines:
line = line.lstrip()
if line and not line.startswith("#"):
yield line
|
# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the LICENSE
# file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from mcrouter.test.McrouterTestCase import McrouterTestCase
class TestNoReplyBase(McrouterTestCase):
config = './mcrouter/test/test_noreply.json'
def setUp(self):
# The order here must corresponds to the order of hosts in the .json
self.mc = self.add_server(self.make_memcached())
def get_mcrouter(self):
return self.add_mcrouter(self.config)
class TestNoReply(TestNoReplyBase):
def test_set_noreply(self):
mcrouter = self.get_mcrouter()
self.assertTrue(mcrouter.set("key", "value", noreply=True))
self.assertTrue(self.eventually_get(key="key", expVal="value"))
def test_add_replace_noreply(self):
mcrouter = self.get_mcrouter()
self.assertTrue(mcrouter.add("key", "value", noreply=True))
self.assertTrue(self.eventually_get(key="key", expVal="value"))
self.assertTrue(mcrouter.replace("key", "value1", noreply=True))
self.assertTrue(self.eventually_get(key="key", expVal="value1"))
def test_delete_noreply(self):
mcrouter = self.get_mcrouter()
self.assertTrue(mcrouter.set("key", "value"))
self.assertTrue(self.eventually_get(key="key", expVal="value"))
self.assertTrue(mcrouter.delete("key", noreply=True))
self.assertFalse(self.mc.get("key"))
def test_touch_noreply(self):
mcrouter = self.get_mcrouter()
self.assertTrue(mcrouter.set("key", "value"))
self.assertTrue(self.eventually_get(key="key", expVal="value"))
self.assertTrue(mcrouter.touch("key", 100, noreply=True))
self.assertTrue(self.eventually_get(key="key", expVal="value"))
def test_arith_noreply(self):
mcrouter = self.get_mcrouter()
self.assertTrue(mcrouter.set("arith", "1"))
self.assertTrue(self.eventually_get(key="arith", expVal="1"))
self.assertTrue(mcrouter.incr("arith", noreply=True))
self.assertTrue(self.eventually_get(key="arith", expVal="2"))
self.assertTrue(mcrouter.decr("arith", noreply=True))
self.assertTrue(self.eventually_get(key="arith", expVal="1"))
class TestNoReplyAppendPrepend(TestNoReplyBase):
def __init__(self, *args, **kwargs):
super(TestNoReplyAppendPrepend, self).__init__(*args, **kwargs)
self.use_mock_mc = True
def test_affix_noreply(self):
mcrouter = self.get_mcrouter()
self.assertTrue(mcrouter.set("key", "value"))
self.assertTrue(self.eventually_get(key="key", expVal="value"))
self.assertTrue(mcrouter.append("key", "123", noreply=True))
self.assertTrue(self.eventually_get(key="key", expVal="value123"))
self.assertTrue(mcrouter.prepend("key", "456", noreply=True))
self.assertTrue(self.eventually_get(key="key", expVal="456value123"))
|
/*!
* TableSorter QUnit Testing - filter widget
*/
/*jshint unused: false */
/*
Filter widget tested parts
========================
OPTIONS:
filter_defaultAttrib, filter_ignoreCase, filter_startsWith,
filter_selectSource, filter_functions (set, not functionality)
CLASSES:
filter-false, filter-match, filter-parsed
METHODS:
filterReset, search (false), setFilters
EVENTS:
filterInit, filterEnd
Not yet tested
=========================
OPTIONS:
filter_childRows, filter_columnFilters, filter_cssFilter, filter_external,
filter_filteredRow, filter_formatter, filter_hideEmpty,
filter_hideEmpty, filter_liveSearch, filter_onlyAvail, filter_placeholder,
filter_reset, filter_saveFilters, filter_searchDelay,
filter_serversideFiltering, filter_useParsedData
CLASSES:
filter-select, filter-select-nosort, filter-onlyAvail
METHODS:
search (array), getFilters, external filters
EVENTS:
filterStart
*/
jQuery(function($){
QUnit.module('Widgets', {
beforeEach: function(assert) {
this.ts = $.tablesorter;
// filter widget table
this.$table = $('#testblock').html('<table class="tablesorter">' +
'<thead><tr>' +
'<th class="rank">Rank</th>' +
'<th class="first filter-match">First Name</th>' +
'<th class="last">Last Name</th>' +
'<th data-value="<20">Age</th>' +
'<th class="total">Total</th>' +
'<th>Discount</th>' +
'<th>Date</th>' +
'<th class="last2">Last Name2</th>' +
'</tr></thead><tbody>' +
'<tr><td>1</td><td>Philip Aaron Wong</td><td>Johnson Sr Esq</td><td>25</td><td>$5.95</td><td>22%</td><td>Jun 26, 2004 7:22 AM</td><td>Johnson Sr Esq</td></tr>' +
'<tr><td>11</td><td>Aaron</td><td>Hibert</td><td>12</td><td>$2.99</td><td>5%</td><td>Aug 21, 2009 12:21 PM</td><td>Hibert</td></tr>' +
'<tr><td>12</td><td>Brandon Clark</td><td>Henry Jr</td><td>51</td><td>$42.29</td><td>18%</td><td>Oct 13, 2000 1:15 PM</td><td>Henry Jr</td></tr>' +
'<tr><td>111</td><td>Peter</td><td>Parker</td><td>28</td><td>$9.99</td><td>20%</td><td>Jul 6, 2006 8:14 AM</td><td>Parker</td></tr>' +
'<tr><td>21</td><td>John</td><td>Hood</td><td>33</td><td>$19.99</td><td>25%</td><td>Dec 10, 2002 5:14 AM</td><td>Hood</td></tr>' +
'<tr><td>013</td><td>Clark</td><td>Kent Sr.</td><td>18</td><td>$15.89</td><td>44%</td><td>Jan 12, 2003 11:14 AM</td><td>Kent Sr.</td></tr>' +
'<tr><td>005</td><td>Bruce</td><td>Almighty Esq</td><td>45</td><td>$153.19</td><td>44%</td><td>Jan 18, 2021 9:12 AM</td><td>Almighty Esq</td></tr>' +
'<tr><td>10</td><td>Alex</td><td>Dumass</td><td>13</td><td>$5.29</td><td>4%</td><td>Jan 8, 2012 5:11 PM</td><td>Dumass</td></tr>' +
'<tr><td>16</td><td>Jim</td><td>Franco</td><td>24</td><td>$14.19</td><td>14%</td><td>Jan 14, 2004 11:23 AM</td><td>Franco</td></tr>' +
'<tr><td>166</td><td>Bruce Lee</td><td>Evans</td><td>22</td><td>$13.19</td><td>11%</td><td>Jan 18, 2007 9:12 AM</td><td>Evans</td></tr>' +
'<tr><td>100</td><td>Brenda Dexter</td><td>McMasters</td><td>18</td><td>$55.20</td><td>15%</td><td>Feb 12, 2010 7:23 PM</td><td>McMasters</td></tr>' +
'<tr><td>55</td><td>Dennis</td><td>Bronson</td><td>65</td><td>$123.00</td><td></td><td>Jan 20, 2001 1:12 PM</td><td>Bronson</td></tr>' +
'<tr><td>9</td><td>Martha</td><td>delFuego</td><td>25</td><td>$22.09</td><td>17%</td><td>Jun 11, 2011 10:55 AM</td><td>delFuego</td></tr>' +
'</tbody></table>').find('table');
this.table = this.$table[0];
this.init = false;
var self = this;
var initTablesort = function(){
self.$table.tablesorter({
ignoreCase: false,
widgets: ['zebra', 'filter'],
headers: {
'.rank' : { filter: false }
},
widgetOptions: {
filter_functions : {
'.last2' : true,
'.rank' : {
"< 10" : function(e, n) { return n <= 10; },
"> 10" : function(e, n) { return n > 10; }
}
},
filter_selectSource : {
// Alphanumeric match (prefix only)
// added as select2 options (you could also use select2 data option)
'.last2' : function(table, column) {
return ['abc', 'def', 'zyx'];
}
}
}
});
};
var onEventCallback = function(){
self.init = true;
self.c = self.table.config,
self.wo = self.c.widgetOptions;
};
return QUnit.SequentialRunner().next(
QUnit.assertOnEvent(
self.$table,
'filterInit',
initTablesort,
onEventCallback
)
).promise();
},
afterEach: function(assert) {
var done = assert.async();
this.$table.trigger('destroy', [false, done]);
}
});
/************************************************
Filter widget
************************************************/
QUnit.test( 'Filter: init', function(assert) {
expect(6);
assert.equal( this.init, true, 'Init event' );
assert.equal( this.$table.hasClass('hasFilters'), true, '`hasFilters` class applied' );
assert.equal( this.ts.filter.regex.child.test( this.c.cssChildRow ), true, 'child row regex check' );
assert.equal( this.ts.filter.regex.filtered.test( this.wo.filter_filteredRow ), true, 'filtered row regex check' );
// this includes check of headers option & referencing column by class
assert.equal ( this.c.$table.find('.tablesorter-filter').eq(0).hasClass('disabled'), true, 'filter disabled & headers class name working' );
assert.cacheCompare( this.table, 3, [ 12, 18, 13, 18 ], 'starting filter value on age column', true );
});
QUnit.test( 'Filter searches', function(assert) {
var ts = this.ts,
c = this.c,
wo = this.wo,
$table = this.$table,
table = this.table;
expect(33);
return QUnit.SequentialRunner(
function(actions, assertions) {
return QUnit.assertOnEvent($table, 'filterEnd', actions, assertions);
}
).nextTask(
function(){ ts.setFilters( table, ['', 'e'], true ); },
function(){ assert.cacheCompare( table, 1, ['Peter', 'Bruce', 'Alex', 'Bruce Lee', 'Brenda Dexter', 'Dennis'], 'search regular', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '~bee'], true ); },
function(){ assert.cacheCompare( table, 1, ['Bruce Lee', 'Brenda Dexter'], 'search fuzzy', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '~piano'], true ); },
function(){ assert.cacheCompare( table, 1, ['Philip Aaron Wong'], 'search fuzzy2', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', 'john='], true ); },
function(){ assert.cacheCompare( table, 1, ['John'], 'search exact', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', 'a?s'], true ); },
function(){ assert.cacheCompare( table, 2, ['Dumass', 'Evans'], 'search wildcard, one character (?)', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', 'a*s'], true ); },
function(){ assert.cacheCompare( table, 2, ['Dumass', 'Evans', 'McMasters'], 'search wildcard, multiple characters (*)', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '/r$/'], true ); },
function(){ assert.cacheCompare( table, 1, ['Peter', 'Brenda Dexter'], 'search regex', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '>10'], true ); },
function(){ assert.cacheCompare( table, 4, [42.29, 19.99, 15.89, 153.19, 14.19, 13.19, 55.2, 123, 22.09], 'search operator (>10)', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '>100'], true ); },
function(){ assert.cacheCompare( table, 4, [153.19, 123], 'search operator (>100); ensure search filtered gets cleared', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '', '>=20'], true ); },
function(){ assert.cacheCompare( table, 5, [22, 20, 25, 44, 44], 'search operator (>=)', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '', '<10'], true ); },
function(){ assert.cacheCompare( table, 5, [5, 4], 'search operator (<10)', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '', '<100'], true ); },
function(){ assert.cacheCompare( table, 5, [22, 5, 18, 20, 25, 44, 44, 4, 14, 11, 15, 17], 'search operator (<100); ensure search filtered gets cleared', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '', '<=20'], true ); },
function(){ assert.cacheCompare( table, 5, [5, 18, 20, 4, 14, 11, 15, 17], 'search operator (<=)', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '!a'], true ); },
function(){ assert.cacheCompare( table, 1, ['Peter', 'John', 'Bruce', 'Jim', 'Bruce Lee', 'Dennis'], 'search not match', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '!aa'], true ); },
function(){ assert.cacheCompare( table, 1, ['Brandon Clark', 'Peter', 'John', 'Clark', 'Bruce', 'Alex', 'Jim', 'Bruce Lee', 'Brenda Dexter', 'Dennis', 'Martha'], 'search not match; ensure search filtered gets cleared', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', 'br && c'], true ); },
function(){ assert.cacheCompare( table, 1, ['Brandon Clark', 'Bruce', 'Bruce Lee'], 'search and match', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', 'br && cl'], true ); },
function(){ assert.cacheCompare( table, 1, ['Brandon Clark'], 'search and match; ensure search filtered gets cleared', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', 'c* && l && a'], true ); },
function(){ assert.cacheCompare( table, 1, ['Brandon Clark', 'Clark'], 'search "c* && l && a"', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', 'a && !o'], true ); },
function(){ assert.cacheCompare( table, 1, ['Clark', 'Alex', 'Brenda Dexter', 'Martha'], 'search "a && !o"', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '' , '>20 && <40'], true ); },
function(){ assert.cacheCompare( table, 3, [25, 28, 33, 24, 22, 25], 'search ">20 && <40"', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '' , '<10 or >40'], true ); },
function(){ assert.cacheCompare( table, 3, [51, 45, 65], 'search "<10 or >40"', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', 'alex|br*'], true ); },
function(){ assert.cacheCompare( table, 1, ['Brandon Clark', 'Bruce', 'Alex', 'Bruce Lee', 'Brenda Dexter'], 'search OR match', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '/(Alex|Aar'], true ); },
function(){ assert.cacheCompare( table, 1, [], 'Partial OR match, but invalid regex', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '/(Alex && '], true ); },
function(){ assert.cacheCompare( table, 1, [], 'Partial AND match, and way messed up regex', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '5 - 10'], true ); },
function(){ assert.cacheCompare( table, 4, [5.95, 9.99, 5.29], 'search range', true ); }
).nextTask(
function(){ ts.setFilters( table, ['', '', '', '', '5 - 100'], true ); },
function(){ assert.cacheCompare( table, 4, [5.95, 42.29, 9.99, 19.99, 15.89, 5.29, 14.19, 13.19, 55.2, 22.09], 'search range; ensure search filtered gets cleared', true ); }
).nextTask( // test filter_startsWith (false by default)
function(){
wo.filter_startsWith = false;
ts.setFilters( table, ['', 'aa'], true );
},
function(){ assert.cacheCompare( table, 1, ['Philip Aaron Wong', 'Aaron'], 'search - filter_startsWith : false', true ); }
).nextTask( // test filter_startsWith (false by default)
function(){
wo.filter_startsWith = true;
c.$table.trigger('search', false);
},
function(){
assert.cacheCompare( table, 1, ['Aaron'], 'search - filter_startsWith : true', true );
wo.filter_startsWith = false;
}
).nextTask( // test filter_ignoreCase (true by default)
function(){
wo.filter_ignoreCase = false;
c.$table.trigger('search', false);
},
function(){
assert.cacheCompare( table, 1, [], 'search - filter_ignoreCase : false', true );
wo.filter_ignoreCase = true;
}
).nextTask( // test filter-match class (added in the example code)
function(){ ts.setFilters( table, ['', 'alex|br*|c'], true ); },
function(){ assert.cacheCompare( table, 1, ['Brandon Clark', 'Clark', 'Bruce', 'Alex', 'Bruce Lee', 'Brenda Dexter'], 'search - filter-match', true ); }
).nextTask( // test filter-match class
function(){
c.$table.find('.tablesorter-header').eq(1).removeClass('filter-match');
c.$table.trigger('search', false);
},
function(){ assert.cacheCompare( table, 1, ['Bruce', 'Alex'], 'search - filter-match removed', true ); }
).nextTask( // filter reset
function(){ c.$table.trigger('filterReset'); },
function(){ assert.cacheCompare( table, 5, [22, 5, 18, 20, 25, 44, 44, 4, 14, 11, 15, '', 17], 'filterReset', true ); }
).nextTask( // filter parsed class
function(){
wo.filter_startsWith = false;
ts.setFilters( table, ['', '', '', '', '', '', '< 1/1/2001'], true );
},
function(){ assert.cacheCompare( table, 6, [ new Date('Oct 13, 2000 1:15 PM').getTime() ], 'search - filter-parsed', true ); }
).promise();
});
QUnit.test( 'Filter: function & selectSource', function(assert) {
expect(3);
var $t, opts = [];
$t = this.c.$table.find('.tablesorter-filter-row select:last');
assert.equal ( $t.length !== 0, true, 'filter_functions: true working' );
this.c.$table.find('.tablesorter-filter-row select:first option').each(function(){
opts.push( $.trim( $(this).text() ) );
});
assert.equal ( opts.length === 3 && opts.join('') === '< 10> 10', true, 'filter_functions set' );
opts = [];
$t.find('option').each(function(){
opts.push( $.trim( $(this).text() ) );
});
assert.equal ( opts.length === 4 && opts.join('') === 'abcdefzyx', true, 'filter_selectSource set' );
});
});
|
//~ name a248
alert(a248);
//~ component a249.js
|
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 9662:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isCallable = __webpack_require__(614);
var tryToString = __webpack_require__(6330);
var TypeError = global.TypeError;
// `Assert: IsCallable(argument) is true`
module.exports = function (argument) {
if (isCallable(argument)) return argument;
throw TypeError(tryToString(argument) + ' is not a function');
};
/***/ }),
/***/ 6077:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isCallable = __webpack_require__(614);
var String = global.String;
var TypeError = global.TypeError;
module.exports = function (argument) {
if (typeof argument == 'object' || isCallable(argument)) return argument;
throw TypeError("Can't set " + String(argument) + ' as a prototype');
};
/***/ }),
/***/ 1223:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(5112);
var create = __webpack_require__(30);
var definePropertyModule = __webpack_require__(3070);
var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] == undefined) {
definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {
configurable: true,
value: create(null)
});
}
// add a key to Array.prototype[@@unscopables]
module.exports = function (key) {
ArrayPrototype[UNSCOPABLES][key] = true;
};
/***/ }),
/***/ 5787:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isPrototypeOf = __webpack_require__(7976);
var TypeError = global.TypeError;
module.exports = function (it, Prototype) {
if (isPrototypeOf(Prototype, it)) return it;
throw TypeError('Incorrect invocation');
};
/***/ }),
/***/ 9670:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isObject = __webpack_require__(111);
var String = global.String;
var TypeError = global.TypeError;
// `Assert: Type(argument) is Object`
module.exports = function (argument) {
if (isObject(argument)) return argument;
throw TypeError(String(argument) + ' is not an object');
};
/***/ }),
/***/ 1318:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var toIndexedObject = __webpack_require__(5656);
var toAbsoluteIndex = __webpack_require__(1400);
var lengthOfArrayLike = __webpack_require__(6244);
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = lengthOfArrayLike(O);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare -- NaN check
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
module.exports = {
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
/***/ }),
/***/ 1589:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var toAbsoluteIndex = __webpack_require__(1400);
var lengthOfArrayLike = __webpack_require__(6244);
var createProperty = __webpack_require__(6135);
var Array = global.Array;
var max = Math.max;
module.exports = function (O, start, end) {
var length = lengthOfArrayLike(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
var result = Array(max(fin - k, 0));
for (var n = 0; k < fin; k++, n++) createProperty(result, n, O[k]);
result.length = n;
return result;
};
/***/ }),
/***/ 4362:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var arraySlice = __webpack_require__(1589);
var floor = Math.floor;
var mergeSort = function (array, comparefn) {
var length = array.length;
var middle = floor(length / 2);
return length < 8 ? insertionSort(array, comparefn) : merge(
array,
mergeSort(arraySlice(array, 0, middle), comparefn),
mergeSort(arraySlice(array, middle), comparefn),
comparefn
);
};
var insertionSort = function (array, comparefn) {
var length = array.length;
var i = 1;
var element, j;
while (i < length) {
j = i;
element = array[i];
while (j && comparefn(array[j - 1], element) > 0) {
array[j] = array[--j];
}
if (j !== i++) array[j] = element;
} return array;
};
var merge = function (array, left, right, comparefn) {
var llength = left.length;
var rlength = right.length;
var lindex = 0;
var rindex = 0;
while (lindex < llength || rindex < rlength) {
array[lindex + rindex] = (lindex < llength && rindex < rlength)
? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]
: lindex < llength ? left[lindex++] : right[rindex++];
} return array;
};
module.exports = mergeSort;
/***/ }),
/***/ 4326:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var toString = uncurryThis({}.toString);
var stringSlice = uncurryThis(''.slice);
module.exports = function (it) {
return stringSlice(toString(it), 8, -1);
};
/***/ }),
/***/ 648:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var TO_STRING_TAG_SUPPORT = __webpack_require__(1694);
var isCallable = __webpack_require__(614);
var classofRaw = __webpack_require__(4326);
var wellKnownSymbol = __webpack_require__(5112);
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var Object = global.Object;
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && isCallable(O.callee) ? 'Arguments' : result;
};
/***/ }),
/***/ 9920:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var hasOwn = __webpack_require__(2597);
var ownKeys = __webpack_require__(3887);
var getOwnPropertyDescriptorModule = __webpack_require__(1236);
var definePropertyModule = __webpack_require__(3070);
module.exports = function (target, source, exceptions) {
var keys = ownKeys(source);
var defineProperty = definePropertyModule.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
}
};
/***/ }),
/***/ 8544:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var fails = __webpack_require__(7293);
module.exports = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
// eslint-disable-next-line es/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F()) !== F.prototype;
});
/***/ }),
/***/ 4994:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var IteratorPrototype = (__webpack_require__(3383).IteratorPrototype);
var create = __webpack_require__(30);
var createPropertyDescriptor = __webpack_require__(9114);
var setToStringTag = __webpack_require__(8003);
var Iterators = __webpack_require__(7497);
var returnThis = function () { return this; };
module.exports = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
Iterators[TO_STRING_TAG] = returnThis;
return IteratorConstructor;
};
/***/ }),
/***/ 8880:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(9781);
var definePropertyModule = __webpack_require__(3070);
var createPropertyDescriptor = __webpack_require__(9114);
module.exports = DESCRIPTORS ? function (object, key, value) {
return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/***/ 9114:
/***/ (function(module) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/***/ 6135:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var toPropertyKey = __webpack_require__(4948);
var definePropertyModule = __webpack_require__(3070);
var createPropertyDescriptor = __webpack_require__(9114);
module.exports = function (object, key, value) {
var propertyKey = toPropertyKey(key);
if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
/***/ }),
/***/ 654:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(2109);
var call = __webpack_require__(6916);
var IS_PURE = __webpack_require__(1913);
var FunctionName = __webpack_require__(6530);
var isCallable = __webpack_require__(614);
var createIteratorConstructor = __webpack_require__(4994);
var getPrototypeOf = __webpack_require__(9518);
var setPrototypeOf = __webpack_require__(7674);
var setToStringTag = __webpack_require__(8003);
var createNonEnumerableProperty = __webpack_require__(8880);
var redefine = __webpack_require__(1320);
var wellKnownSymbol = __webpack_require__(5112);
var Iterators = __webpack_require__(7497);
var IteratorsCore = __webpack_require__(3383);
var PROPER_FUNCTION_NAME = FunctionName.PROPER;
var CONFIGURABLE_FUNCTION_NAME = FunctionName.CONFIGURABLE;
var IteratorPrototype = IteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis = function () { return this; };
module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf) {
setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
} else if (!isCallable(CurrentIteratorPrototype[ITERATOR])) {
redefine(CurrentIteratorPrototype, ITERATOR, returnThis);
}
}
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
}
}
// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if (PROPER_FUNCTION_NAME && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
if (!IS_PURE && CONFIGURABLE_FUNCTION_NAME) {
createNonEnumerableProperty(IterablePrototype, 'name', VALUES);
} else {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return call(nativeIterator, this); };
}
}
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
redefine(IterablePrototype, KEY, methods[KEY]);
}
} else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
}
// define iterator
if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
redefine(IterablePrototype, ITERATOR, defaultIterator, { name: DEFAULT });
}
Iterators[NAME] = defaultIterator;
return methods;
};
/***/ }),
/***/ 9781:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var fails = __webpack_require__(7293);
// Detect IE8's incomplete defineProperty implementation
module.exports = !fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
/***/ }),
/***/ 317:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isObject = __webpack_require__(111);
var document = global.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return EXISTS ? document.createElement(it) : {};
};
/***/ }),
/***/ 8324:
/***/ (function(module) {
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
module.exports = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
/***/ }),
/***/ 8509:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
// in old WebKit versions, `element.classList` is not an instance of global `DOMTokenList`
var documentCreateElement = __webpack_require__(317);
var classList = documentCreateElement('span').classList;
var DOMTokenListPrototype = classList && classList.constructor && classList.constructor.prototype;
module.exports = DOMTokenListPrototype === Object.prototype ? undefined : DOMTokenListPrototype;
/***/ }),
/***/ 8113:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(5005);
module.exports = getBuiltIn('navigator', 'userAgent') || '';
/***/ }),
/***/ 7392:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var userAgent = __webpack_require__(8113);
var process = global.process;
var Deno = global.Deno;
var versions = process && process.versions || Deno && Deno.version;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && userAgent) {
match = userAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent.match(/Chrome\/(\d+)/);
if (match) version = +match[1];
}
}
module.exports = version;
/***/ }),
/***/ 748:
/***/ (function(module) {
// IE8- don't enum bug keys
module.exports = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/***/ }),
/***/ 2109:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var getOwnPropertyDescriptor = (__webpack_require__(1236).f);
var createNonEnumerableProperty = __webpack_require__(8880);
var redefine = __webpack_require__(1320);
var setGlobal = __webpack_require__(3505);
var copyConstructorProperties = __webpack_require__(9920);
var isForced = __webpack_require__(4705);
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/
module.exports = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global;
} else if (STATIC) {
target = global[TARGET] || setGlobal(TARGET, {});
} else {
target = (global[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty == typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
/***/ }),
/***/ 7293:
/***/ (function(module) {
module.exports = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
/***/ }),
/***/ 9974:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var aCallable = __webpack_require__(9662);
var bind = uncurryThis(uncurryThis.bind);
// optional / simple context binding
module.exports = function (fn, that) {
aCallable(fn);
return that === undefined ? fn : bind ? bind(fn, that) : function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/***/ 6916:
/***/ (function(module) {
var call = Function.prototype.call;
module.exports = call.bind ? call.bind(call) : function () {
return call.apply(call, arguments);
};
/***/ }),
/***/ 6530:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(9781);
var hasOwn = __webpack_require__(2597);
var FunctionPrototype = Function.prototype;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
var EXISTS = hasOwn(FunctionPrototype, 'name');
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
module.exports = {
EXISTS: EXISTS,
PROPER: PROPER,
CONFIGURABLE: CONFIGURABLE
};
/***/ }),
/***/ 1702:
/***/ (function(module) {
var FunctionPrototype = Function.prototype;
var bind = FunctionPrototype.bind;
var call = FunctionPrototype.call;
var uncurryThis = bind && bind.bind(call, call);
module.exports = bind ? function (fn) {
return fn && uncurryThis(fn);
} : function (fn) {
return fn && function () {
return call.apply(fn, arguments);
};
};
/***/ }),
/***/ 5005:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isCallable = __webpack_require__(614);
var aFunction = function (argument) {
return isCallable(argument) ? argument : undefined;
};
module.exports = function (namespace, method) {
return arguments.length < 2 ? aFunction(global[namespace]) : global[namespace] && global[namespace][method];
};
/***/ }),
/***/ 1246:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var classof = __webpack_require__(648);
var getMethod = __webpack_require__(8173);
var Iterators = __webpack_require__(7497);
var wellKnownSymbol = __webpack_require__(5112);
var ITERATOR = wellKnownSymbol('iterator');
module.exports = function (it) {
if (it != undefined) return getMethod(it, ITERATOR)
|| getMethod(it, '@@iterator')
|| Iterators[classof(it)];
};
/***/ }),
/***/ 8554:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var call = __webpack_require__(6916);
var aCallable = __webpack_require__(9662);
var anObject = __webpack_require__(9670);
var tryToString = __webpack_require__(6330);
var getIteratorMethod = __webpack_require__(1246);
var TypeError = global.TypeError;
module.exports = function (argument, usingIterator) {
var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
throw TypeError(tryToString(argument) + ' is not iterable');
};
/***/ }),
/***/ 8173:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var aCallable = __webpack_require__(9662);
// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
module.exports = function (V, P) {
var func = V[P];
return func == null ? undefined : aCallable(func);
};
/***/ }),
/***/ 7854:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
module.exports =
// eslint-disable-next-line es/no-global-this -- safe
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == 'object' && self) ||
check(typeof __webpack_require__.g == 'object' && __webpack_require__.g) ||
// eslint-disable-next-line no-new-func -- fallback
(function () { return this; })() || Function('return this')();
/***/ }),
/***/ 2597:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var toObject = __webpack_require__(7908);
var hasOwnProperty = uncurryThis({}.hasOwnProperty);
// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
module.exports = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty(toObject(it), key);
};
/***/ }),
/***/ 3501:
/***/ (function(module) {
module.exports = {};
/***/ }),
/***/ 490:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(5005);
module.exports = getBuiltIn('document', 'documentElement');
/***/ }),
/***/ 4664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(9781);
var fails = __webpack_require__(7293);
var createElement = __webpack_require__(317);
// Thank's IE8 for his funny defineProperty
module.exports = !DESCRIPTORS && !fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(createElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
/***/ }),
/***/ 8361:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var uncurryThis = __webpack_require__(1702);
var fails = __webpack_require__(7293);
var classof = __webpack_require__(4326);
var Object = global.Object;
var split = uncurryThis(''.split);
// fallback for non-array-like ES3 and non-enumerable old V8 strings
module.exports = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof(it) == 'String' ? split(it, '') : Object(it);
} : Object;
/***/ }),
/***/ 2788:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var isCallable = __webpack_require__(614);
var store = __webpack_require__(5465);
var functionToString = uncurryThis(Function.toString);
// this helper broken in `[email protected]`, so we can't use `shared` helper
if (!isCallable(store.inspectSource)) {
store.inspectSource = function (it) {
return functionToString(it);
};
}
module.exports = store.inspectSource;
/***/ }),
/***/ 9909:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var NATIVE_WEAK_MAP = __webpack_require__(8536);
var global = __webpack_require__(7854);
var uncurryThis = __webpack_require__(1702);
var isObject = __webpack_require__(111);
var createNonEnumerableProperty = __webpack_require__(8880);
var hasOwn = __webpack_require__(2597);
var shared = __webpack_require__(5465);
var sharedKey = __webpack_require__(6200);
var hiddenKeys = __webpack_require__(3501);
var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var TypeError = global.TypeError;
var WeakMap = global.WeakMap;
var set, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP || shared.state) {
var store = shared.state || (shared.state = new WeakMap());
var wmget = uncurryThis(store.get);
var wmhas = uncurryThis(store.has);
var wmset = uncurryThis(store.set);
set = function (it, metadata) {
if (wmhas(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
wmset(store, it, metadata);
return metadata;
};
get = function (it) {
return wmget(store, it) || {};
};
has = function (it) {
return wmhas(store, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return hasOwn(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return hasOwn(it, STATE);
};
}
module.exports = {
set: set,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
/***/ }),
/***/ 614:
/***/ (function(module) {
// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
module.exports = function (argument) {
return typeof argument == 'function';
};
/***/ }),
/***/ 4705:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var fails = __webpack_require__(7293);
var isCallable = __webpack_require__(614);
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: isCallable(detection) ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
module.exports = isForced;
/***/ }),
/***/ 111:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var isCallable = __webpack_require__(614);
module.exports = function (it) {
return typeof it == 'object' ? it !== null : isCallable(it);
};
/***/ }),
/***/ 1913:
/***/ (function(module) {
module.exports = false;
/***/ }),
/***/ 2190:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var getBuiltIn = __webpack_require__(5005);
var isCallable = __webpack_require__(614);
var isPrototypeOf = __webpack_require__(7976);
var USE_SYMBOL_AS_UID = __webpack_require__(3307);
var Object = global.Object;
module.exports = USE_SYMBOL_AS_UID ? function (it) {
return typeof it == 'symbol';
} : function (it) {
var $Symbol = getBuiltIn('Symbol');
return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, Object(it));
};
/***/ }),
/***/ 3383:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var fails = __webpack_require__(7293);
var isCallable = __webpack_require__(614);
var create = __webpack_require__(30);
var getPrototypeOf = __webpack_require__(9518);
var redefine = __webpack_require__(1320);
var wellKnownSymbol = __webpack_require__(5112);
var IS_PURE = __webpack_require__(1913);
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
// `%IteratorPrototype%` object
// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
/* eslint-disable es/no-array-prototype-keys -- safe */
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
var NEW_ITERATOR_PROTOTYPE = IteratorPrototype == undefined || fails(function () {
var test = {};
// FF44- legacy iterators case
return IteratorPrototype[ITERATOR].call(test) !== test;
});
if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
// `%IteratorPrototype%[@@iterator]()` method
// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
if (!isCallable(IteratorPrototype[ITERATOR])) {
redefine(IteratorPrototype, ITERATOR, function () {
return this;
});
}
module.exports = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
/***/ }),
/***/ 7497:
/***/ (function(module) {
module.exports = {};
/***/ }),
/***/ 6244:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var toLength = __webpack_require__(7466);
// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
module.exports = function (obj) {
return toLength(obj.length);
};
/***/ }),
/***/ 133:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/* eslint-disable es/no-symbol -- required for testing */
var V8_VERSION = __webpack_require__(7392);
var fails = __webpack_require__(7293);
// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
var symbol = Symbol();
// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
return !String(symbol) || !(Object(symbol) instanceof Symbol) ||
// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham && V8_VERSION && V8_VERSION < 41;
});
/***/ }),
/***/ 590:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var fails = __webpack_require__(7293);
var wellKnownSymbol = __webpack_require__(5112);
var IS_PURE = __webpack_require__(1913);
var ITERATOR = wellKnownSymbol('iterator');
module.exports = !fails(function () {
// eslint-disable-next-line unicorn/relative-url-style -- required for testing
var url = new URL('b?a=1&b=2&c=3', 'http://a');
var searchParams = url.searchParams;
var result = '';
url.pathname = 'c%20d';
searchParams.forEach(function (value, key) {
searchParams['delete']('b');
result += key + value;
});
return (IS_PURE && !url.toJSON)
|| !searchParams.sort
|| url.href !== 'http://a/c%20d?a=1&c=3'
|| searchParams.get('c') !== '3'
|| String(new URLSearchParams('?a=1')) !== 'a=1'
|| !searchParams[ITERATOR]
// throws in Edge
|| new URL('https://a@b').username !== 'a'
|| new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b'
// not punycoded in Edge
|| new URL('http://тест').host !== 'xn--e1aybc'
// not escaped in Chrome 62-
|| new URL('http://a#б').hash !== '#%D0%B1'
// fails in Chrome 66-
|| result !== 'a1c3'
// throws in Safari
|| new URL('http://x', undefined).host !== 'x';
});
/***/ }),
/***/ 8536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isCallable = __webpack_require__(614);
var inspectSource = __webpack_require__(2788);
var WeakMap = global.WeakMap;
module.exports = isCallable(WeakMap) && /native code/.test(inspectSource(WeakMap));
/***/ }),
/***/ 30:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/* global ActiveXObject -- old IE, WSH */
var anObject = __webpack_require__(9670);
var definePropertiesModule = __webpack_require__(6048);
var enumBugKeys = __webpack_require__(748);
var hiddenKeys = __webpack_require__(3501);
var html = __webpack_require__(490);
var documentCreateElement = __webpack_require__(317);
var sharedKey = __webpack_require__(6200);
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
activeXDocument = new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = typeof document != 'undefined'
? document.domain && activeXDocument
? NullProtoObjectViaActiveX(activeXDocument) // old IE
: NullProtoObjectViaIFrame()
: NullProtoObjectViaActiveX(activeXDocument); // WSH
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
};
/***/ }),
/***/ 6048:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(9781);
var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(3353);
var definePropertyModule = __webpack_require__(3070);
var anObject = __webpack_require__(9670);
var toIndexedObject = __webpack_require__(5656);
var objectKeys = __webpack_require__(1956);
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var props = toIndexedObject(Properties);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
return O;
};
/***/ }),
/***/ 3070:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var global = __webpack_require__(7854);
var DESCRIPTORS = __webpack_require__(9781);
var IE8_DOM_DEFINE = __webpack_require__(4664);
var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(3353);
var anObject = __webpack_require__(9670);
var toPropertyKey = __webpack_require__(4948);
var TypeError = global.TypeError;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty = Object.defineProperty;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ENUMERABLE = 'enumerable';
var CONFIGURABLE = 'configurable';
var WRITABLE = 'writable';
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
var current = $getOwnPropertyDescriptor(O, P);
if (current && current[WRITABLE]) {
O[P] = Attributes.value;
Attributes = {
configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
writable: false
};
}
} return $defineProperty(O, P, Attributes);
} : $defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return $defineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/***/ 1236:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(9781);
var call = __webpack_require__(6916);
var propertyIsEnumerableModule = __webpack_require__(5296);
var createPropertyDescriptor = __webpack_require__(9114);
var toIndexedObject = __webpack_require__(5656);
var toPropertyKey = __webpack_require__(4948);
var hasOwn = __webpack_require__(2597);
var IE8_DOM_DEFINE = __webpack_require__(4664);
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPropertyKey(P);
if (IE8_DOM_DEFINE) try {
return $getOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
};
/***/ }),
/***/ 8006:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var internalObjectKeys = __webpack_require__(6324);
var enumBugKeys = __webpack_require__(748);
var hiddenKeys = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys(O, hiddenKeys);
};
/***/ }),
/***/ 5181:
/***/ (function(__unused_webpack_module, exports) {
// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/***/ 9518:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var hasOwn = __webpack_require__(2597);
var isCallable = __webpack_require__(614);
var toObject = __webpack_require__(7908);
var sharedKey = __webpack_require__(6200);
var CORRECT_PROTOTYPE_GETTER = __webpack_require__(8544);
var IE_PROTO = sharedKey('IE_PROTO');
var Object = global.Object;
var ObjectPrototype = Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
var object = toObject(O);
if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
var constructor = object.constructor;
if (isCallable(constructor) && object instanceof constructor) {
return constructor.prototype;
} return object instanceof Object ? ObjectPrototype : null;
};
/***/ }),
/***/ 7976:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
module.exports = uncurryThis({}.isPrototypeOf);
/***/ }),
/***/ 6324:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var hasOwn = __webpack_require__(2597);
var toIndexedObject = __webpack_require__(5656);
var indexOf = (__webpack_require__(1318).indexOf);
var hiddenKeys = __webpack_require__(3501);
var push = uncurryThis([].push);
module.exports = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
// Don't enum bug & hidden keys
while (names.length > i) if (hasOwn(O, key = names[i++])) {
~indexOf(result, key) || push(result, key);
}
return result;
};
/***/ }),
/***/ 1956:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var internalObjectKeys = __webpack_require__(6324);
var enumBugKeys = __webpack_require__(748);
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
module.exports = Object.keys || function keys(O) {
return internalObjectKeys(O, enumBugKeys);
};
/***/ }),
/***/ 5296:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var $propertyIsEnumerable = {}.propertyIsEnumerable;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable;
/***/ }),
/***/ 7674:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/* eslint-disable no-proto -- safe */
var uncurryThis = __webpack_require__(1702);
var anObject = __webpack_require__(9670);
var aPossiblePrototype = __webpack_require__(6077);
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es/no-object-setprototypeof -- safe
module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
setter = uncurryThis(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set);
setter(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
/***/ }),
/***/ 288:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var TO_STRING_TAG_SUPPORT = __webpack_require__(1694);
var classof = __webpack_require__(648);
// `Object.prototype.toString` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.tostring
module.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() {
return '[object ' + classof(this) + ']';
};
/***/ }),
/***/ 2140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var call = __webpack_require__(6916);
var isCallable = __webpack_require__(614);
var isObject = __webpack_require__(111);
var TypeError = global.TypeError;
// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
module.exports = function (input, pref) {
var fn, val;
if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/***/ 3887:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(5005);
var uncurryThis = __webpack_require__(1702);
var getOwnPropertyNamesModule = __webpack_require__(8006);
var getOwnPropertySymbolsModule = __webpack_require__(5181);
var anObject = __webpack_require__(9670);
var concat = uncurryThis([].concat);
// all object keys, includes non-enumerable and symbols
module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule.f(anObject(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
};
/***/ }),
/***/ 2248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var redefine = __webpack_require__(1320);
module.exports = function (target, src, options) {
for (var key in src) redefine(target, key, src[key], options);
return target;
};
/***/ }),
/***/ 1320:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var isCallable = __webpack_require__(614);
var hasOwn = __webpack_require__(2597);
var createNonEnumerableProperty = __webpack_require__(8880);
var setGlobal = __webpack_require__(3505);
var inspectSource = __webpack_require__(2788);
var InternalStateModule = __webpack_require__(9909);
var CONFIGURABLE_FUNCTION_NAME = (__webpack_require__(6530).CONFIGURABLE);
var getInternalState = InternalStateModule.get;
var enforceInternalState = InternalStateModule.enforce;
var TEMPLATE = String(String).split('String');
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
var name = options && options.name !== undefined ? options.name : key;
var state;
if (isCallable(value)) {
if (String(name).slice(0, 7) === 'Symbol(') {
name = '[' + String(name).replace(/^Symbol\(([^)]*)\)/, '$1') + ']';
}
if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
createNonEnumerableProperty(value, 'name', name);
}
state = enforceInternalState(value);
if (!state.source) {
state.source = TEMPLATE.join(typeof name == 'string' ? name : '');
}
}
if (O === global) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return isCallable(this) && getInternalState(this).source || inspectSource(this);
});
/***/ }),
/***/ 4488:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var TypeError = global.TypeError;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/***/ 3505:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;
module.exports = function (key, value) {
try {
defineProperty(global, key, { value: value, configurable: true, writable: true });
} catch (error) {
global[key] = value;
} return value;
};
/***/ }),
/***/ 8003:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var defineProperty = (__webpack_require__(3070).f);
var hasOwn = __webpack_require__(2597);
var wellKnownSymbol = __webpack_require__(5112);
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
module.exports = function (target, TAG, STATIC) {
if (target && !STATIC) target = target.prototype;
if (target && !hasOwn(target, TO_STRING_TAG)) {
defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG });
}
};
/***/ }),
/***/ 6200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var shared = __webpack_require__(2309);
var uid = __webpack_require__(9711);
var keys = shared('keys');
module.exports = function (key) {
return keys[key] || (keys[key] = uid(key));
};
/***/ }),
/***/ 5465:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var setGlobal = __webpack_require__(3505);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || setGlobal(SHARED, {});
module.exports = store;
/***/ }),
/***/ 2309:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var IS_PURE = __webpack_require__(1913);
var store = __webpack_require__(5465);
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.20.2',
mode: IS_PURE ? 'pure' : 'global',
copyright: '© 2022 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/***/ 8710:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var toIntegerOrInfinity = __webpack_require__(9303);
var toString = __webpack_require__(1340);
var requireObjectCoercible = __webpack_require__(4488);
var charAt = uncurryThis(''.charAt);
var charCodeAt = uncurryThis(''.charCodeAt);
var stringSlice = uncurryThis(''.slice);
var createMethod = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = toString(requireObjectCoercible($this));
var position = toIntegerOrInfinity(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = charCodeAt(S, position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = charCodeAt(S, position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING
? charAt(S, position)
: first
: CONVERT_TO_STRING
? stringSlice(S, position, position + 2)
: (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
module.exports = {
// `String.prototype.codePointAt` method
// https://tc39.es/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod(true)
};
/***/ }),
/***/ 1400:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var toIntegerOrInfinity = __webpack_require__(9303);
var max = Math.max;
var min = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
module.exports = function (index, length) {
var integer = toIntegerOrInfinity(index);
return integer < 0 ? max(integer + length, 0) : min(integer, length);
};
/***/ }),
/***/ 5656:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
// toObject with fallback for non-array-like ES3 strings
var IndexedObject = __webpack_require__(8361);
var requireObjectCoercible = __webpack_require__(4488);
module.exports = function (it) {
return IndexedObject(requireObjectCoercible(it));
};
/***/ }),
/***/ 9303:
/***/ (function(module) {
var ceil = Math.ceil;
var floor = Math.floor;
// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
module.exports = function (argument) {
var number = +argument;
// eslint-disable-next-line no-self-compare -- safe
return number !== number || number === 0 ? 0 : (number > 0 ? floor : ceil)(number);
};
/***/ }),
/***/ 7466:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var toIntegerOrInfinity = __webpack_require__(9303);
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
module.exports = function (argument) {
return argument > 0 ? min(toIntegerOrInfinity(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
/***/ }),
/***/ 7908:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var requireObjectCoercible = __webpack_require__(4488);
var Object = global.Object;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
module.exports = function (argument) {
return Object(requireObjectCoercible(argument));
};
/***/ }),
/***/ 7593:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var call = __webpack_require__(6916);
var isObject = __webpack_require__(111);
var isSymbol = __webpack_require__(2190);
var getMethod = __webpack_require__(8173);
var ordinaryToPrimitive = __webpack_require__(2140);
var wellKnownSymbol = __webpack_require__(5112);
var TypeError = global.TypeError;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
module.exports = function (input, pref) {
if (!isObject(input) || isSymbol(input)) return input;
var exoticToPrim = getMethod(input, TO_PRIMITIVE);
var result;
if (exoticToPrim) {
if (pref === undefined) pref = 'default';
result = call(exoticToPrim, input, pref);
if (!isObject(result) || isSymbol(result)) return result;
throw TypeError("Can't convert object to primitive value");
}
if (pref === undefined) pref = 'number';
return ordinaryToPrimitive(input, pref);
};
/***/ }),
/***/ 4948:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var toPrimitive = __webpack_require__(7593);
var isSymbol = __webpack_require__(2190);
// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
module.exports = function (argument) {
var key = toPrimitive(argument, 'string');
return isSymbol(key) ? key : key + '';
};
/***/ }),
/***/ 1694:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(5112);
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG] = 'z';
module.exports = String(test) === '[object z]';
/***/ }),
/***/ 1340:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var classof = __webpack_require__(648);
var String = global.String;
module.exports = function (argument) {
if (classof(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
return String(argument);
};
/***/ }),
/***/ 6330:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var String = global.String;
module.exports = function (argument) {
try {
return String(argument);
} catch (error) {
return 'Object';
}
};
/***/ }),
/***/ 9711:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var uncurryThis = __webpack_require__(1702);
var id = 0;
var postfix = Math.random();
var toString = uncurryThis(1.0.toString);
module.exports = function (key) {
return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
};
/***/ }),
/***/ 3307:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/* eslint-disable es/no-symbol -- required for testing */
var NATIVE_SYMBOL = __webpack_require__(133);
module.exports = NATIVE_SYMBOL
&& !Symbol.sham
&& typeof Symbol.iterator == 'symbol';
/***/ }),
/***/ 3353:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(9781);
var fails = __webpack_require__(7293);
// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
module.exports = DESCRIPTORS && fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty(function () { /* empty */ }, 'prototype', {
value: 42,
writable: false
}).prototype != 42;
});
/***/ }),
/***/ 5112:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var shared = __webpack_require__(2309);
var hasOwn = __webpack_require__(2597);
var uid = __webpack_require__(9711);
var NATIVE_SYMBOL = __webpack_require__(133);
var USE_SYMBOL_AS_UID = __webpack_require__(3307);
var WellKnownSymbolsStore = shared('wks');
var Symbol = global.Symbol;
var symbolFor = Symbol && Symbol['for'];
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;
module.exports = function (name) {
if (!hasOwn(WellKnownSymbolsStore, name) || !(NATIVE_SYMBOL || typeof WellKnownSymbolsStore[name] == 'string')) {
var description = 'Symbol.' + name;
if (NATIVE_SYMBOL && hasOwn(Symbol, name)) {
WellKnownSymbolsStore[name] = Symbol[name];
} else if (USE_SYMBOL_AS_UID && symbolFor) {
WellKnownSymbolsStore[name] = symbolFor(description);
} else {
WellKnownSymbolsStore[name] = createWellKnownSymbol(description);
}
} return WellKnownSymbolsStore[name];
};
/***/ }),
/***/ 6992:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var toIndexedObject = __webpack_require__(5656);
var addToUnscopables = __webpack_require__(1223);
var Iterators = __webpack_require__(7497);
var InternalStateModule = __webpack_require__(9909);
var defineProperty = (__webpack_require__(3070).f);
var defineIterator = __webpack_require__(654);
var IS_PURE = __webpack_require__(1913);
var DESCRIPTORS = __webpack_require__(9781);
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.es/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.es/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.es/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.es/ecma262/#sec-createarrayiterator
module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
var values = Iterators.Arguments = Iterators.Array;
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
// V8 ~ Chrome 45- bug
if (!IS_PURE && DESCRIPTORS && values.name !== 'values') try {
defineProperty(values, 'name', { value: 'values' });
} catch (error) { /* empty */ }
/***/ }),
/***/ 1539:
/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {
var TO_STRING_TAG_SUPPORT = __webpack_require__(1694);
var redefine = __webpack_require__(1320);
var toString = __webpack_require__(288);
// `Object.prototype.toString` method
// https://tc39.es/ecma262/#sec-object.prototype.tostring
if (!TO_STRING_TAG_SUPPORT) {
redefine(Object.prototype, 'toString', toString, { unsafe: true });
}
/***/ }),
/***/ 8783:
/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var charAt = (__webpack_require__(8710).charAt);
var toString = __webpack_require__(1340);
var InternalStateModule = __webpack_require__(9909);
var defineIterator = __webpack_require__(654);
var STRING_ITERATOR = 'String Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState(this, {
type: STRING_ITERATOR,
string: toString(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt(string, index);
state.index += point.length;
return { value: point, done: false };
});
/***/ }),
/***/ 3948:
/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) {
var global = __webpack_require__(7854);
var DOMIterables = __webpack_require__(8324);
var DOMTokenListPrototype = __webpack_require__(8509);
var ArrayIteratorMethods = __webpack_require__(6992);
var createNonEnumerableProperty = __webpack_require__(8880);
var wellKnownSymbol = __webpack_require__(5112);
var ITERATOR = wellKnownSymbol('iterator');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var ArrayValues = ArrayIteratorMethods.values;
var handlePrototype = function (CollectionPrototype, COLLECTION_NAME) {
if (CollectionPrototype) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[ITERATOR] !== ArrayValues) try {
createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);
} catch (error) {
CollectionPrototype[ITERATOR] = ArrayValues;
}
if (!CollectionPrototype[TO_STRING_TAG]) {
createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);
}
if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {
createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);
} catch (error) {
CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];
}
}
}
};
for (var COLLECTION_NAME in DOMIterables) {
handlePrototype(global[COLLECTION_NAME] && global[COLLECTION_NAME].prototype, COLLECTION_NAME);
}
handlePrototype(DOMTokenListPrototype, 'DOMTokenList');
/***/ }),
/***/ 1637:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
__webpack_require__(6992);
var $ = __webpack_require__(2109);
var global = __webpack_require__(7854);
var getBuiltIn = __webpack_require__(5005);
var call = __webpack_require__(6916);
var uncurryThis = __webpack_require__(1702);
var USE_NATIVE_URL = __webpack_require__(590);
var redefine = __webpack_require__(1320);
var redefineAll = __webpack_require__(2248);
var setToStringTag = __webpack_require__(8003);
var createIteratorConstructor = __webpack_require__(4994);
var InternalStateModule = __webpack_require__(9909);
var anInstance = __webpack_require__(5787);
var isCallable = __webpack_require__(614);
var hasOwn = __webpack_require__(2597);
var bind = __webpack_require__(9974);
var classof = __webpack_require__(648);
var anObject = __webpack_require__(9670);
var isObject = __webpack_require__(111);
var $toString = __webpack_require__(1340);
var create = __webpack_require__(30);
var createPropertyDescriptor = __webpack_require__(9114);
var getIterator = __webpack_require__(8554);
var getIteratorMethod = __webpack_require__(1246);
var wellKnownSymbol = __webpack_require__(5112);
var arraySort = __webpack_require__(4362);
var ITERATOR = wellKnownSymbol('iterator');
var URL_SEARCH_PARAMS = 'URLSearchParams';
var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator';
var setInternalState = InternalStateModule.set;
var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS);
var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR);
var n$Fetch = getBuiltIn('fetch');
var N$Request = getBuiltIn('Request');
var Headers = getBuiltIn('Headers');
var RequestPrototype = N$Request && N$Request.prototype;
var HeadersPrototype = Headers && Headers.prototype;
var RegExp = global.RegExp;
var TypeError = global.TypeError;
var decodeURIComponent = global.decodeURIComponent;
var encodeURIComponent = global.encodeURIComponent;
var charAt = uncurryThis(''.charAt);
var join = uncurryThis([].join);
var push = uncurryThis([].push);
var replace = uncurryThis(''.replace);
var shift = uncurryThis([].shift);
var splice = uncurryThis([].splice);
var split = uncurryThis(''.split);
var stringSlice = uncurryThis(''.slice);
var plus = /\+/g;
var sequences = Array(4);
var percentSequence = function (bytes) {
return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi'));
};
var percentDecode = function (sequence) {
try {
return decodeURIComponent(sequence);
} catch (error) {
return sequence;
}
};
var deserialize = function (it) {
var result = replace(it, plus, ' ');
var bytes = 4;
try {
return decodeURIComponent(result);
} catch (error) {
while (bytes) {
result = replace(result, percentSequence(bytes--), percentDecode);
}
return result;
}
};
var find = /[!'()~]|%20/g;
var replacements = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
var replacer = function (match) {
return replacements[match];
};
var serialize = function (it) {
return replace(encodeURIComponent(it), find, replacer);
};
var validateArgumentsLength = function (passed, required) {
if (passed < required) throw TypeError('Not enough arguments');
};
var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
setInternalState(this, {
type: URL_SEARCH_PARAMS_ITERATOR,
iterator: getIterator(getInternalParamsState(params).entries),
kind: kind
});
}, 'Iterator', function next() {
var state = getInternalIteratorState(this);
var kind = state.kind;
var step = state.iterator.next();
var entry = step.value;
if (!step.done) {
step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value];
} return step;
}, true);
var URLSearchParamsState = function (init) {
this.entries = [];
this.url = null;
if (init !== undefined) {
if (isObject(init)) this.parseObject(init);
else this.parseQuery(typeof init == 'string' ? charAt(init, 0) === '?' ? stringSlice(init, 1) : init : $toString(init));
}
};
URLSearchParamsState.prototype = {
type: URL_SEARCH_PARAMS,
bindURL: function (url) {
this.url = url;
this.update();
},
parseObject: function (object) {
var iteratorMethod = getIteratorMethod(object);
var iterator, next, step, entryIterator, entryNext, first, second;
if (iteratorMethod) {
iterator = getIterator(object, iteratorMethod);
next = iterator.next;
while (!(step = call(next, iterator)).done) {
entryIterator = getIterator(anObject(step.value));
entryNext = entryIterator.next;
if (
(first = call(entryNext, entryIterator)).done ||
(second = call(entryNext, entryIterator)).done ||
!call(entryNext, entryIterator).done
) throw TypeError('Expected sequence with length 2');
push(this.entries, { key: $toString(first.value), value: $toString(second.value) });
}
} else for (var key in object) if (hasOwn(object, key)) {
push(this.entries, { key: key, value: $toString(object[key]) });
}
},
parseQuery: function (query) {
if (query) {
var attributes = split(query, '&');
var index = 0;
var attribute, entry;
while (index < attributes.length) {
attribute = attributes[index++];
if (attribute.length) {
entry = split(attribute, '=');
push(this.entries, {
key: deserialize(shift(entry)),
value: deserialize(join(entry, '='))
});
}
}
}
},
serialize: function () {
var entries = this.entries;
var result = [];
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
push(result, serialize(entry.key) + '=' + serialize(entry.value));
} return join(result, '&');
},
update: function () {
this.entries.length = 0;
this.parseQuery(this.url.query);
},
updateURL: function () {
if (this.url) this.url.update();
}
};
// `URLSearchParams` constructor
// https://url.spec.whatwg.org/#interface-urlsearchparams
var URLSearchParamsConstructor = function URLSearchParams(/* init */) {
anInstance(this, URLSearchParamsPrototype);
var init = arguments.length > 0 ? arguments[0] : undefined;
setInternalState(this, new URLSearchParamsState(init));
};
var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype;
redefineAll(URLSearchParamsPrototype, {
// `URLSearchParams.prototype.append` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append: function append(name, value) {
validateArgumentsLength(arguments.length, 2);
var state = getInternalParamsState(this);
push(state.entries, { key: $toString(name), value: $toString(value) });
state.updateURL();
},
// `URLSearchParams.prototype.delete` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
'delete': function (name) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var key = $toString(name);
var index = 0;
while (index < entries.length) {
if (entries[index].key === key) splice(entries, index, 1);
else index++;
}
state.updateURL();
},
// `URLSearchParams.prototype.get` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get: function get(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = $toString(name);
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) return entries[index].value;
}
return null;
},
// `URLSearchParams.prototype.getAll` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll: function getAll(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = $toString(name);
var result = [];
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) push(result, entries[index].value);
}
return result;
},
// `URLSearchParams.prototype.has` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has: function has(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = $toString(name);
var index = 0;
while (index < entries.length) {
if (entries[index++].key === key) return true;
}
return false;
},
// `URLSearchParams.prototype.set` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set: function set(name, value) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var found = false;
var key = $toString(name);
var val = $toString(value);
var index = 0;
var entry;
for (; index < entries.length; index++) {
entry = entries[index];
if (entry.key === key) {
if (found) splice(entries, index--, 1);
else {
found = true;
entry.value = val;
}
}
}
if (!found) push(entries, { key: key, value: val });
state.updateURL();
},
// `URLSearchParams.prototype.sort` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-sort
sort: function sort() {
var state = getInternalParamsState(this);
arraySort(state.entries, function (a, b) {
return a.key > b.key ? 1 : -1;
});
state.updateURL();
},
// `URLSearchParams.prototype.forEach` method
forEach: function forEach(callback /* , thisArg */) {
var entries = getInternalParamsState(this).entries;
var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined);
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
boundFunction(entry.value, entry.key, this);
}
},
// `URLSearchParams.prototype.keys` method
keys: function keys() {
return new URLSearchParamsIterator(this, 'keys');
},
// `URLSearchParams.prototype.values` method
values: function values() {
return new URLSearchParamsIterator(this, 'values');
},
// `URLSearchParams.prototype.entries` method
entries: function entries() {
return new URLSearchParamsIterator(this, 'entries');
}
}, { enumerable: true });
// `URLSearchParams.prototype[@@iterator]` method
redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries, { name: 'entries' });
// `URLSearchParams.prototype.toString` method
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
redefine(URLSearchParamsPrototype, 'toString', function toString() {
return getInternalParamsState(this).serialize();
}, { enumerable: true });
setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
$({ global: true, forced: !USE_NATIVE_URL }, {
URLSearchParams: URLSearchParamsConstructor
});
// Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams`
if (!USE_NATIVE_URL && isCallable(Headers)) {
var headersHas = uncurryThis(HeadersPrototype.has);
var headersSet = uncurryThis(HeadersPrototype.set);
var wrapRequestOptions = function (init) {
if (isObject(init)) {
var body = init.body;
var headers;
if (classof(body) === URL_SEARCH_PARAMS) {
headers = init.headers ? new Headers(init.headers) : new Headers();
if (!headersHas(headers, 'content-type')) {
headersSet(headers, 'content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
return create(init, {
body: createPropertyDescriptor(0, $toString(body)),
headers: createPropertyDescriptor(0, headers)
});
}
} return init;
};
if (isCallable(n$Fetch)) {
$({ global: true, enumerable: true, forced: true }, {
fetch: function fetch(input /* , init */) {
return n$Fetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
}
});
}
if (isCallable(N$Request)) {
var RequestConstructor = function Request(input /* , init */) {
anInstance(this, RequestPrototype);
return new N$Request(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
};
RequestPrototype.constructor = RequestConstructor;
RequestConstructor.prototype = RequestPrototype;
$({ global: true, forced: true }, {
Request: RequestConstructor
});
}
}
module.exports = {
URLSearchParams: URLSearchParamsConstructor,
getState: getInternalParamsState
};
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/global */
/******/ !function() {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
/* harmony import */ var core_js_modules_es_array_iterator_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6992);
/* harmony import */ var core_js_modules_es_array_iterator_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es_array_iterator_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var core_js_modules_es_object_to_string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1539);
/* harmony import */ var core_js_modules_es_object_to_string_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es_object_to_string_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var core_js_modules_es_string_iterator_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8783);
/* harmony import */ var core_js_modules_es_string_iterator_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_es_string_iterator_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var core_js_modules_web_dom_collections_iterator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3948);
/* harmony import */ var core_js_modules_web_dom_collections_iterator_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_web_dom_collections_iterator_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var core_js_modules_web_url_search_params_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1637);
/* harmony import */ var core_js_modules_web_url_search_params_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(core_js_modules_web_url_search_params_js__WEBPACK_IMPORTED_MODULE_4__);
(function (cb) {
var params = new URLSearchParams("key=730d67");
cb(params.get("key") === "730d67");
})(callback);
}();
/******/ })()
; |
'use strict';
module.exports=(req,res,next)=>{
if(req.params.id){
next();
}else{
next('Name Not Found');
}
} |
// Object of plugins to add to Globals.PLUGINS
// Add custom plugin integration here or as separate files
// within the /src/plugins directory
var defaultPlugins = {
//themePluginPLUGINNAME: function(context) {
// // Example: Plugin integration code here
//},
// Next plugin here
};
// Add to Globals.PLUGINS
$.extend($.fn, {themePlugins: defaultPlugins});
|
const Stream = require("./stream");
it("should default export to be a function", () => {
expect(new Stream()).toBeInstanceOf(Stream);
});
|
'use strict';
import * as Time from 'time.js';
describe('Time', function() {
describe('format', function() {
describe('with NAN', function() {
it('return a correct time format', function() {
expect(Time.format('string')).toEqual('0:00');
expect(Time.format(void(0))).toEqual('0:00');
});
});
describe('with duration more than or equal to 1 hour', function() {
it('return a correct time format', function() {
expect(Time.format(3600)).toEqual('1:00:00');
expect(Time.format(7272)).toEqual('2:01:12');
});
});
describe('with duration less than 1 hour', function() {
it('return a correct time format', function() {
expect(Time.format(1)).toEqual('0:01');
expect(Time.format(61)).toEqual('1:01');
expect(Time.format(3599)).toEqual('59:59');
});
});
});
describe('formatFull', function() {
it('gives correct string for times', function() {
var testTimes = [
[0, '00:00:00'], [60, '00:01:00'],
[488, '00:08:08'], [2452, '00:40:52'],
[3600, '01:00:00'], [28800, '08:00:00'],
[144532, '40:08:52'], [190360, '52:52:40'],
[294008, '81:40:08'], [-5, '00:00:00']
];
$.each(testTimes, function(index, times) {
var timeInt = times[0],
timeStr = times[1];
expect(Time.formatFull(timeInt)).toBe(timeStr);
});
});
});
describe('convert', function() {
it('return a correct time based on speed modifier', function() {
expect(Time.convert(0, 1, 1.5)).toEqual('0.000');
expect(Time.convert(100, 1, 1.5)).toEqual('66.667');
expect(Time.convert(100, 1.5, 1)).toEqual('150.000');
});
});
});
|
/**
* This application creates a widget for the
* search, help, and sign-in header navigation on Vets.gov
*
* @module platform/site-wide/login
*/
import React from 'react';
import { Provider } from 'react-redux';
import startReactApp from '../../startup/react';
import Main from './containers/Main';
/**
* Sets up the login widget with the given store at login-root
*
* @param {Redux.Store} store The common store used on the site
*/
export default function startMegaMenuWidget(store) {
startReactApp((
<Provider store={store}>
<Main/>
</Provider>
), document.getElementById('mega-menu'));
}
|
/*
Copyright 2010-2013 SourceGear, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
*/
load("../js_test_lib/vscript_test_lib.js");
//////////////////////////////////////////////////////////////////
// Basic MERGE tests that DO NOT require UPDATE nor REVERT.
//////////////////////////////////////////////////////////////////
function st_wc_merge_resolve_016()
{
var my_group = "st_wc_merge_resolve_016"; // this variable must match the above group name.
this.no_setup = true; // do not create an initial REPO and WD.
//////////////////////////////////////////////////////////////////
load("update_helpers.js"); // load the helper functions
initialize_update_helpers(this); // initialize helper functions
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
this.test_it = function()
{
var unique = my_group + "_" + new Date().getTime();
var repoName = unique;
var rootDir = pathCombine(tempDir, unique);
var wdDirs = [];
var csets = {};
var nrWD = 0;
var my_make_wd = function(obj)
{
var new_wd = pathCombine(rootDir, "wd_" + nrWD);
vscript_test_wc__print_section_divider("Creating WD[" + nrWD + "]: " + new_wd);
obj.do_fsobj_mkdir_recursive( new_wd );
obj.do_fsobj_cd( new_wd );
wdDirs.push( new_wd );
nrWD += 1;
return new_wd;
}
//////////////////////////////////////////////////////////////////
// stock content for creating files.
var content_equal = ("This is a test 1.\n"
+"This is a test 2.\n"
+"This is a test 3.\n"
+"This is a test 4.\n"
+"This is a test 5.\n"
+"This is a test 6.\n"
+"This is a test 7.\n"
+"This is a test 8.\n");
var content_B1 = "abcdefghij\n";
var content_C1 = "0123456789\n";
//////////////////////////////////////////////////////////////////
// Create the first WD and initialize the REPO.
my_make_wd(this);
sg.vv2.init_new_repo( { "repo" : repoName,
"hash" : "SHA1/160",
"path" : "."
} );
whoami_testing(repoName);
//////////////////////////////////////////////////////////////////
// Build a sequence of CSETs using current WD.
vscript_test_wc__write_file("file_1.txt", content_equal);
vscript_test_wc__write_file("file_2.txt", content_equal);
vscript_test_wc__write_file("file_3.txt", content_equal);
vscript_test_wc__write_file("file_4.txt", content_equal);
vscript_test_wc__addremove();
csets.A = vscript_test_wc__commit("A");
//////////////////////////////////////////////////////////////////
// Start a sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file_1.txt", (content_B1 + content_equal));
vscript_test_wc__write_file("file_2.txt", (content_B1 + content_equal));
vscript_test_wc__write_file("file_3.txt", (content_B1 + content_equal));
vscript_test_wc__write_file("file_4.txt", (content_B1 + content_equal));
csets.B = vscript_test_wc__commit("B");
//////////////////////////////////////////////////////////////////
// Start an alternate sequence of CSETS in a new WD.
my_make_wd(this);
sg.wc.checkout( { "repo" : repoName,
"attach" : "master",
"rev" : csets.A
} );
// re-write the file contents so that they look edited.
vscript_test_wc__write_file("file_1.txt", (content_C1 + content_equal));
vscript_test_wc__write_file("file_2.txt", (content_C1 + content_equal));
vscript_test_wc__write_file("file_3.txt", (content_C1 + content_equal));
vscript_test_wc__write_file("file_4.txt", (content_C1 + content_equal));
csets.C = vscript_test_wc__commit("C");
//////////////////////////////////////////////////////////////////
// Now start some MERGES using a fresh WD for each.
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("Checkout B and merge C into it.");
my_make_wd(this);
vscript_test_wc__checkout_np( { "repo" : repoName,
"attach" : "master",
"rev" : csets.B
} );
vscript_test_wc__merge_np( { "rev" : csets.C } );
// auto-merge should have been attempted and failed.
var expect_test = new Array;
expect_test["Modified (WC!=A,WC!=B,WC!=C)"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
expect_test["Auto-Merged"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
expect_test["Unresolved"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
expect_test["Choice Unresolved (Contents)"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("RESOLVE 1:");
vscript_test_wc__resolve__list_all();
// TODO vv resolve list --all
// TODO Contents: @/file_1.txt
// TODO Contents: @/file_2.txt
// TODO Contents: @/file_3.txt
// TODO Contents: @/file_4.txt
vscript_test_wc__resolve__accept("baseline", "@/file_1.txt");
vscript_test_wc__resolve__accept("other", "@/file_2.txt");
vscript_test_wc__resolve__accept("ancestor", "@/file_3.txt");
var expect_test = new Array;
expect_test["Modified (WC!=A,WC==B,WC!=C)"] = [ "@/file_1.txt" ];
expect_test["Modified (WC!=A,WC!=B,WC==C)"] = [ "@/file_2.txt" ];
expect_test["Modified (WC==A,WC!=B,WC!=C)"] = [ "@/file_3.txt" ];
expect_test["Modified (WC!=A,WC!=B,WC!=C)"] = [ "@/file_4.txt" ];
expect_test["Auto-Merged (Edited)"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt" ];
expect_test["Auto-Merged"] = [ "@/file_4.txt" ];
expect_test["Resolved"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt" ];
expect_test["Choice Resolved (Contents)"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt" ];
expect_test["Unresolved"] = [ "@/file_4.txt" ];
expect_test["Choice Unresolved (Contents)"] = [ "@/file_4.txt" ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
//////////////////////////////////////////////////////////////////
vscript_test_wc__print_section_divider("RESOLVE 2:");
vscript_test_wc__resolve__list_all();
// TODO vv resolve list --all
// TODO Contents: @/file_1.txt
// TODO Contents: @/file_2.txt
// TODO Contents: @/file_3.txt
// TODO Contents: @/file_4.txt
// overwrite working to say we fixed it and then tell resolve to just use it
vscript_test_wc__write_file("file_4.txt", (content_B1 + content_C1 + content_equal));
// TODO 2012/04/12 This requires that _wc__variantFile_to_absolute()
// TODO works with gid-domain paths and that overwrite-cache thing.
vscript_test_wc__resolve__accept("working", "@/file_4.txt");
var expect_test = new Array;
expect_test["Modified (WC!=A,WC==B,WC!=C)"] = [ "@/file_1.txt" ];
expect_test["Modified (WC!=A,WC!=B,WC==C)"] = [ "@/file_2.txt" ];
expect_test["Modified (WC==A,WC!=B,WC!=C)"] = [ "@/file_3.txt" ];
expect_test["Modified (WC!=A,WC!=B,WC!=C)"] = [ "@/file_4.txt" ];
expect_test["Auto-Merged (Edited)"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
expect_test["Resolved"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
expect_test["Choice Resolved (Contents)"] = [ "@/file_1.txt",
"@/file_2.txt",
"@/file_3.txt",
"@/file_4.txt" ];
vscript_test_wc__mstatus_confirm_wii(expect_test);
}
}
|
'use strict';
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var util = require('util');
var mkdirp = require('mkdirp');
var bitcore = require('capricoinplus-bitcore-lib');
var zmq = require('zmq');
var async = require('async');
var LRU = require('lru-cache');
var BitcoinRPC = require('capricoinplus-bitcoind-rpc');
var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;
var Transaction = bitcore.Transaction;
var index = require('../');
var errors = index.errors;
var log = index.log;
var utils = require('../utils');
var Service = require('../service');
/**
* Provides a friendly event driven API to bitcoind in Node.js. Manages starting and
* stopping bitcoind as a child process for application support, as well as connecting
* to multiple bitcoind processes for server infrastructure. Results are cached in an
* LRU cache for improved performance and methods added for common queries.
*
* @param {Object} options
* @param {Node} options.node - A reference to the node
*/
function Bitcoin(options) {
if (!(this instanceof Bitcoin)) {
return new Bitcoin(options);
}
Service.call(this, options);
this.options = options;
this._initCaches();
// bitcoind child process
this.spawn = false;
// event subscribers
this.subscriptions = {};
this.subscriptions.rawtransaction = [];
this.subscriptions.hashblock = [];
this.subscriptions.address = {};
// set initial settings
this._initDefaults(options);
// available bitcoind nodes
this._initClients();
// for testing purposes
this._process = options.process || process;
this.on('error', function(err) {
log.error(err.stack);
});
}
util.inherits(Bitcoin, Service);
Bitcoin.dependencies = [];
Bitcoin.DEFAULT_MAX_TXIDS = 1000;
Bitcoin.DEFAULT_MAX_HISTORY = 50;
Bitcoin.DEFAULT_SHUTDOWN_TIMEOUT = 15000;
Bitcoin.DEFAULT_ZMQ_SUBSCRIBE_PROGRESS = 0.9999;
Bitcoin.DEFAULT_MAX_ADDRESSES_QUERY = 10000;
Bitcoin.DEFAULT_SPAWN_RESTART_TIME = 5000;
Bitcoin.DEFAULT_SPAWN_STOP_TIME = 10000;
Bitcoin.DEFAULT_TRY_ALL_INTERVAL = 1000;
Bitcoin.DEFAULT_REINDEX_INTERVAL = 10000;
Bitcoin.DEFAULT_START_RETRY_INTERVAL = 5000;
Bitcoin.DEFAULT_TIP_UPDATE_INTERVAL = 15000;
Bitcoin.DEFAULT_TRANSACTION_CONCURRENCY = 5;
Bitcoin.DEFAULT_CONFIG_SETTINGS = {
server: 1,
whitelist: '127.0.0.1',
dbcompression: true,
dbmaxopenfiles: 1000,
txindex: 1,
addressindex: 1,
timestampindex: 1,
spentindex: 1,
zmqpubrawtx: 'tcp://127.0.0.1:28332',
zmqpubhashblock: 'tcp://127.0.0.1:28332',
rpcallowip: '127.0.0.1',
rpcuser: 'bitcoin',
rpcpassword: 'local321',
rpcport: 11112,
uacomment: 'bitcore'
};
Bitcoin.prototype._initDefaults = function(options) {
/* jshint maxcomplexity: 15 */
// limits
this.maxTxids = options.maxTxids || Bitcoin.DEFAULT_MAX_TXIDS;
this.maxTransactionHistory = options.maxTransactionHistory || Bitcoin.DEFAULT_MAX_HISTORY;
this.maxAddressesQuery = options.maxAddressesQuery || Bitcoin.DEFAULT_MAX_ADDRESSES_QUERY;
this.shutdownTimeout = options.shutdownTimeout || Bitcoin.DEFAULT_SHUTDOWN_TIMEOUT;
// spawn restart setting
this.spawnRestartTime = options.spawnRestartTime || Bitcoin.DEFAULT_SPAWN_RESTART_TIME;
this.spawnStopTime = options.spawnStopTime || Bitcoin.DEFAULT_SPAWN_STOP_TIME;
// try all interval
this.tryAllInterval = options.tryAllInterval || Bitcoin.DEFAULT_TRY_ALL_INTERVAL;
this.startRetryInterval = options.startRetryInterval || Bitcoin.DEFAULT_START_RETRY_INTERVAL;
// rpc limits
this.transactionConcurrency = options.transactionConcurrency || Bitcoin.DEFAULT_TRANSACTION_CONCURRENCY;
// sync progress level when zmq subscribes to events
this.zmqSubscribeProgress = options.zmqSubscribeProgress || Bitcoin.DEFAULT_ZMQ_SUBSCRIBE_PROGRESS;
};
Bitcoin.prototype._initCaches = function() {
// caches valid until there is a new block
this.utxosCache = LRU(50000);
this.txidsCache = LRU(50000);
this.balanceCache = LRU(50000);
this.summaryCache = LRU(50000);
this.blockOverviewCache = LRU(144);
this.transactionDetailedCache = LRU(100000);
// caches valid indefinitely
this.transactionCache = LRU(100000);
this.rawTransactionCache = LRU(50000);
this.blockCache = LRU(144);
this.rawBlockCache = LRU(72);
this.blockHeaderCache = LRU(288);
this.zmqKnownTransactions = LRU(5000);
this.zmqKnownBlocks = LRU(50);
this.lastTip = 0;
this.lastTipTimeout = false;
};
Bitcoin.prototype._initClients = function() {
var self = this;
this.nodes = [];
this.nodesIndex = 0;
Object.defineProperty(this, 'client', {
get: function() {
var client = self.nodes[self.nodesIndex].client;
self.nodesIndex = (self.nodesIndex + 1) % self.nodes.length;
return client;
},
enumerable: true,
configurable: false
});
};
/**
* Called by Node to determine the available API methods.
*/
Bitcoin.prototype.getAPIMethods = function() {
var methods = [
['getBlock', this, this.getBlock, 1],
['getRawBlock', this, this.getRawBlock, 1],
['getBlockHeader', this, this.getBlockHeader, 1],
['getBlockOverview', this, this.getBlockOverview, 1],
['getBlockHashesByTimestamp', this, this.getBlockHashesByTimestamp, 2],
['getBestBlockHash', this, this.getBestBlockHash, 0],
['getSpentInfo', this, this.getSpentInfo, 1],
['getBlockchainInfo', this, this.getBlockchainInfo, 0],
['getNetworkInfo', this, this.getNetworkInfo, 0],
['getWalletInfo', this, this.getWalletInfo, 0],
['syncPercentage', this, this.syncPercentage, 0],
['isSynced', this, this.isSynced, 0],
['getRawTransaction', this, this.getRawTransaction, 1],
['getTransaction', this, this.getTransaction, 1],
['getDetailedTransaction', this, this.getDetailedTransaction, 1],
['sendTransaction', this, this.sendTransaction, 1],
['estimateFee', this, this.estimateFee, 1],
['getAddressTxids', this, this.getAddressTxids, 2],
['getAddressBalance', this, this.getAddressBalance, 2],
['getAddressUnspentOutputs', this, this.getAddressUnspentOutputs, 2],
['getAddressHistory', this, this.getAddressHistory, 2],
['getAddressSummary', this, this.getAddressSummary, 1],
['generateBlock', this, this.generateBlock, 1]
];
return methods;
};
/**
* Called by the Bus to determine the available events.
*/
Bitcoin.prototype.getPublishEvents = function() {
return [
{
name: 'bitcoind/rawtransaction',
scope: this,
subscribe: this.subscribe.bind(this, 'rawtransaction'),
unsubscribe: this.unsubscribe.bind(this, 'rawtransaction')
},
{
name: 'bitcoind/hashblock',
scope: this,
subscribe: this.subscribe.bind(this, 'hashblock'),
unsubscribe: this.unsubscribe.bind(this, 'hashblock')
},
{
name: 'bitcoind/addresstxid',
scope: this,
subscribe: this.subscribeAddress.bind(this),
unsubscribe: this.unsubscribeAddress.bind(this)
}
];
};
Bitcoin.prototype.subscribe = function(name, emitter) {
this.subscriptions[name].push(emitter);
log.info(emitter.remoteAddress, 'subscribe:', 'bitcoind/' + name, 'total:', this.subscriptions[name].length);
};
Bitcoin.prototype.unsubscribe = function(name, emitter) {
var index = this.subscriptions[name].indexOf(emitter);
if (index > -1) {
this.subscriptions[name].splice(index, 1);
}
log.info(emitter.remoteAddress, 'unsubscribe:', 'bitcoind/' + name, 'total:', this.subscriptions[name].length);
};
Bitcoin.prototype.subscribeAddress = function(emitter, addresses) {
var self = this;
function addAddress(addressStr) {
if(self.subscriptions.address[addressStr]) {
var emitters = self.subscriptions.address[addressStr];
var index = emitters.indexOf(emitter);
if (index === -1) {
self.subscriptions.address[addressStr].push(emitter);
}
} else {
self.subscriptions.address[addressStr] = [emitter];
}
}
for(var i = 0; i < addresses.length; i++) {
if (bitcore.Address.isValid(addresses[i], this.node.network)) {
addAddress(addresses[i]);
}
}
log.info(emitter.remoteAddress, 'subscribe:', 'bitcoind/addresstxid', 'total:', _.size(this.subscriptions.address));
};
Bitcoin.prototype.unsubscribeAddress = function(emitter, addresses) {
var self = this;
if(!addresses) {
return this.unsubscribeAddressAll(emitter);
}
function removeAddress(addressStr) {
var emitters = self.subscriptions.address[addressStr];
var index = emitters.indexOf(emitter);
if(index > -1) {
emitters.splice(index, 1);
if (emitters.length === 0) {
delete self.subscriptions.address[addressStr];
}
}
}
for(var i = 0; i < addresses.length; i++) {
if(this.subscriptions.address[addresses[i]]) {
removeAddress(addresses[i]);
}
}
log.info(emitter.remoteAddress, 'unsubscribe:', 'bitcoind/addresstxid', 'total:', _.size(this.subscriptions.address));
};
/**
* A helper function for the `unsubscribe` method to unsubscribe from all addresses.
* @param {String} name - The name of the event
* @param {EventEmitter} emitter - An instance of an event emitter
*/
Bitcoin.prototype.unsubscribeAddressAll = function(emitter) {
for(var hashHex in this.subscriptions.address) {
var emitters = this.subscriptions.address[hashHex];
var index = emitters.indexOf(emitter);
if(index > -1) {
emitters.splice(index, 1);
}
if (emitters.length === 0) {
delete this.subscriptions.address[hashHex];
}
}
log.info(emitter.remoteAddress, 'unsubscribe:', 'bitcoind/addresstxid', 'total:', _.size(this.subscriptions.address));
};
Bitcoin.prototype._getDefaultConfig = function() {
var config = '';
var defaults = Bitcoin.DEFAULT_CONFIG_SETTINGS;
for(var key in defaults) {
config += key + '=' + defaults[key] + '\n';
}
return config;
};
Bitcoin.prototype._parseBitcoinConf = function(configPath) {
var options = {};
var file = fs.readFileSync(configPath);
var unparsed = file.toString().split('\n');
for(var i = 0; i < unparsed.length; i++) {
var line = unparsed[i];
if (!line.match(/^\#/) && line.match(/\=/)) {
var option = line.split('=');
var value;
if (!Number.isNaN(Number(option[1]))) {
value = Number(option[1]);
} else {
value = option[1];
}
options[option[0]] = value;
}
}
return options;
};
Bitcoin.prototype._expandRelativeDatadir = function() {
if (!utils.isAbsolutePath(this.options.spawn.datadir)) {
$.checkState(this.node.configPath);
$.checkState(utils.isAbsolutePath(this.node.configPath));
var baseConfigPath = path.dirname(this.node.configPath);
this.options.spawn.datadir = path.resolve(baseConfigPath, this.options.spawn.datadir);
}
};
Bitcoin.prototype._loadSpawnConfiguration = function(node) {
/* jshint maxstatements: 25 */
$.checkArgument(this.options.spawn, 'Please specify "spawn" in bitcoind config options');
$.checkArgument(this.options.spawn.datadir, 'Please specify "spawn.datadir" in bitcoind config options');
$.checkArgument(this.options.spawn.exec, 'Please specify "spawn.exec" in bitcoind config options');
this._expandRelativeDatadir();
var spawnOptions = this.options.spawn;
var configPath = path.resolve(spawnOptions.datadir, './capricoinplus.conf');
log.info('Using capricoinplus config file:', configPath);
this.spawn = {};
this.spawn.datadir = this.options.spawn.datadir;
this.spawn.exec = this.options.spawn.exec;
this.spawn.configPath = configPath;
this.spawn.config = {};
if (!fs.existsSync(spawnOptions.datadir)) {
mkdirp.sync(spawnOptions.datadir);
}
if (!fs.existsSync(configPath)) {
var defaultConfig = this._getDefaultConfig();
fs.writeFileSync(configPath, defaultConfig);
}
_.extend(this.spawn.config, this._getDefaultConf());
_.extend(this.spawn.config, this._parseBitcoinConf(configPath));
var networkConfigPath = this._getNetworkConfigPath();
if (networkConfigPath && fs.existsSync(networkConfigPath)) {
_.extend(this.spawn.config, this._parseBitcoinConf(networkConfigPath));
}
var spawnConfig = this.spawn.config;
this._checkConfigIndexes(spawnConfig, node);
};
Bitcoin.prototype._checkConfigIndexes = function(spawnConfig, node) {
$.checkState(
spawnConfig.txindex && spawnConfig.txindex === 1,
'"txindex" option is required in order to use transaction query features of bitcore-node. ' +
'Please add "txindex=1" to your configuration and reindex an existing database if ' +
'necessary with reindex=1'
);
$.checkState(
spawnConfig.addressindex && spawnConfig.addressindex === 1,
'"addressindex" option is required in order to use address query features of bitcore-node. ' +
'Please add "addressindex=1" to your configuration and reindex an existing database if ' +
'necessary with reindex=1'
);
$.checkState(
spawnConfig.spentindex && spawnConfig.spentindex === 1,
'"spentindex" option is required in order to use spent info query features of bitcore-node. ' +
'Please add "spentindex=1" to your configuration and reindex an existing database if ' +
'necessary with reindex=1'
);
$.checkState(
spawnConfig.server && spawnConfig.server === 1,
'"server" option is required to communicate to bitcoind from bitcore. ' +
'Please add "server=1" to your configuration and restart'
);
$.checkState(
spawnConfig.zmqpubrawtx,
'"zmqpubrawtx" option is required to get event updates from bitcoind. ' +
'Please add "zmqpubrawtx=tcp://127.0.0.1:<port>" to your configuration and restart'
);
$.checkState(
spawnConfig.zmqpubhashblock,
'"zmqpubhashblock" option is required to get event updates from bitcoind. ' +
'Please add "zmqpubhashblock=tcp://127.0.0.1:<port>" to your configuration and restart'
);
$.checkState(
(spawnConfig.zmqpubhashblock === spawnConfig.zmqpubrawtx),
'"zmqpubrawtx" and "zmqpubhashblock" are expected to the same host and port in bitcoin.conf'
);
if (spawnConfig.reindex && spawnConfig.reindex === 1) {
log.warn('Reindex option is currently enabled. This means that bitcoind is undergoing a reindex. ' +
'The reindex flag will start the index from beginning every time the node is started, so it ' +
'should be removed after the reindex has been initiated. Once the reindex is complete, the rest ' +
'of bitcore-node services will start.');
node._reindex = true;
}
};
Bitcoin.prototype._resetCaches = function() {
this.transactionDetailedCache.reset();
this.utxosCache.reset();
this.txidsCache.reset();
this.balanceCache.reset();
this.summaryCache.reset();
this.blockOverviewCache.reset();
};
Bitcoin.prototype._tryAllClients = function(func, callback) {
var self = this;
var nodesIndex = this.nodesIndex;
var retry = function(done) {
var client = self.nodes[nodesIndex].client;
nodesIndex = (nodesIndex + 1) % self.nodes.length;
func(client, done);
};
async.retry({times: this.nodes.length, interval: this.tryAllInterval || 1000}, retry, callback);
};
Bitcoin.prototype._wrapRPCError = function(errObj) {
var err = new errors.RPCError(errObj.message);
err.code = errObj.code;
return err;
};
Bitcoin.prototype._initChain = function(callback) {
var self = this;
self.client.getBestBlockHash(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
self.client.getBlock(response.result, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
self.height = response.result.height;
self.client.getBlockHash(0, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var blockhash = response.result;
self.getRawBlock(blockhash, function(err, blockBuffer) {
if (err) {
return callback(err);
}
self.genesisBuffer = blockBuffer;
self.emit('ready');
log.info('CapricoinPlus Daemon Ready');
callback();
});
});
});
});
};
Bitcoin.prototype._getDefaultConf = function() {
var networkOptions = {
rpcport: 8332
};
if (this.node.network === bitcore.Networks.testnet) {
networkOptions.rpcport = 18332;
}
return networkOptions;
};
Bitcoin.prototype._getNetworkConfigPath = function() {
var networkPath;
if (this.node.network === bitcore.Networks.testnet) {
networkPath = 'testnet/capricoinplus.conf';
if (this.node.network.regtestEnabled) {
networkPath = 'regtest/capricoinplus.conf';
}
}
return networkPath;
};
Bitcoin.prototype._getNetworkOption = function() {
var networkOption;
if (this.node.network === bitcore.Networks.testnet) {
networkOption = '--testnet';
if (this.node.network.regtestEnabled) {
networkOption = '--regtest';
}
}
return networkOption;
};
Bitcoin.prototype._zmqBlockHandler = function(node, message) {
var self = this;
// Update the current chain tip
self._rapidProtectedUpdateTip(node, message);
// Notify block subscribers
var id = message.toString('binary');
if (!self.zmqKnownBlocks.get(id)) {
self.zmqKnownBlocks.set(id, true);
self.emit('block', message);
for (var i = 0; i < this.subscriptions.hashblock.length; i++) {
this.subscriptions.hashblock[i].emit('bitcoind/hashblock', message.toString('hex'));
}
}
};
Bitcoin.prototype._rapidProtectedUpdateTip = function(node, message) {
var self = this;
// Prevent a rapid succession of tip updates
if (new Date() - self.lastTip > 1000) {
self.lastTip = new Date();
self._updateTip(node, message);
} else {
clearTimeout(self.lastTipTimeout);
self.lastTipTimeout = setTimeout(function() {
self._updateTip(node, message);
}, 1000);
}
};
Bitcoin.prototype._updateTip = function(node, message) {
var self = this;
var hex = message.toString('hex');
if (hex !== self.tiphash) {
self.tiphash = message.toString('hex');
// reset block valid caches
self._resetCaches();
node.client.getBlock(self.tiphash, function(err, response) {
if (err) {
var error = self._wrapRPCError(err);
self.emit('error', error);
} else {
self.height = response.result.height;
$.checkState(self.height >= 0);
self.emit('tip', self.height);
}
});
if(!self.node.stopping) {
self.syncPercentage(function(err, percentage) {
if (err) {
self.emit('error', err);
} else {
if (Math.round(percentage) >= 100) {
self.emit('synced', self.height);
}
log.info('CapricoinPlus Height:', self.height, 'Percentage:', percentage.toFixed(2));
}
});
}
}
};
Bitcoin.prototype._getAddressesFromTransaction = function(transaction) {
var addresses = [];
for (var i = 0; i < transaction.inputs.length; i++) {
var input = transaction.inputs[i];
if (input.script) {
var inputAddress = input.script.toAddress(this.node.network);
if (inputAddress) {
addresses.push(inputAddress.toString());
}
}
}
for (var j = 0; j < transaction.outputs.length; j++) {
var output = transaction.outputs[j];
if (output.script) {
var outputAddress = output.script.toAddress(this.node.network);
if (outputAddress) {
addresses.push(outputAddress.toString());
}
}
}
return _.uniq(addresses);
};
Bitcoin.prototype._notifyAddressTxidSubscribers = function(txid, transaction) {
var addresses = this._getAddressesFromTransaction(transaction);
for (var i = 0; i < addresses.length; i++) {
var address = addresses[i];
if(this.subscriptions.address[address]) {
var emitters = this.subscriptions.address[address];
for(var j = 0; j < emitters.length; j++) {
emitters[j].emit('bitcoind/addresstxid', {
address: address,
txid: txid
});
}
}
}
};
Bitcoin.prototype._zmqTransactionHandler = function(node, message) {
var self = this;
var hash = bitcore.crypto.Hash.sha256sha256(message);
var id = hash.toString('binary');
if (!self.zmqKnownTransactions.get(id)) {
self.zmqKnownTransactions.set(id, true);
self.emit('tx', message);
// Notify transaction subscribers
for (var i = 0; i < this.subscriptions.rawtransaction.length; i++) {
this.subscriptions.rawtransaction[i].emit('bitcoind/rawtransaction', message.toString('hex'));
}
var tx = bitcore.Transaction();
tx.fromString(message);
self._notifyAddressTxidSubscribers(tx.id, tx);
}
};
Bitcoin.prototype._checkSyncedAndSubscribeZmqEvents = function(node) {
var self = this;
var interval;
function checkAndSubscribe(callback) {
// update tip
node.client.getBestBlockHash(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var blockhash = new Buffer(response.result, 'hex');
self.emit('block', blockhash);
self._updateTip(node, blockhash);
// check if synced
node.client.getBlockchainInfo(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var progress = response.result.verificationprogress;
if (progress >= self.zmqSubscribeProgress) {
// subscribe to events for further updates
self._subscribeZmqEvents(node);
clearInterval(interval);
callback(null, true);
} else {
callback(null, false);
}
});
});
}
checkAndSubscribe(function(err, synced) {
if (err) {
log.error(err);
}
if (!synced) {
interval = setInterval(function() {
if (self.node.stopping) {
return clearInterval(interval);
}
checkAndSubscribe(function(err) {
if (err) {
log.error(err);
}
});
}, node._tipUpdateInterval || Bitcoin.DEFAULT_TIP_UPDATE_INTERVAL);
}
});
};
Bitcoin.prototype._subscribeZmqEvents = function(node) {
var self = this;
node.zmqSubSocket.subscribe('hashblock');
node.zmqSubSocket.subscribe('rawtx');
node.zmqSubSocket.on('message', function(topic, message) {
var topicString = topic.toString('utf8');
if (topicString === 'rawtx') {
self._zmqTransactionHandler(node, message);
} else if (topicString === 'hashblock') {
self._zmqBlockHandler(node, message);
}
});
};
Bitcoin.prototype._initZmqSubSocket = function(node, zmqUrl) {
node.zmqSubSocket = zmq.socket('sub');
node.zmqSubSocket.on('connect', function(fd, endPoint) {
log.info('ZMQ connected to:', endPoint);
});
node.zmqSubSocket.on('connect_delay', function(fd, endPoint) {
log.warn('ZMQ connection delay:', endPoint);
});
node.zmqSubSocket.on('disconnect', function(fd, endPoint) {
log.warn('ZMQ disconnect:', endPoint);
});
node.zmqSubSocket.on('monitor_error', function(err) {
log.error('Error in monitoring: %s, will restart monitoring in 5 seconds', err);
setTimeout(function() {
node.zmqSubSocket.monitor(500, 0);
}, 5000);
});
node.zmqSubSocket.monitor(500, 0);
node.zmqSubSocket.connect(zmqUrl);
};
Bitcoin.prototype._checkReindex = function(node, callback) {
var self = this;
var interval;
function finish(err) {
clearInterval(interval);
callback(err);
}
if (node._reindex) {
interval = setInterval(function() {
node.client.getBlockchainInfo(function(err, response) {
if (err) {
return finish(self._wrapRPCError(err));
}
var percentSynced = response.result.verificationprogress * 100;
log.info('CapricoinPlus Core Daemon Reindex Percentage: ' + percentSynced.toFixed(2));
if (Math.round(percentSynced) >= 100) {
node._reindex = false;
finish();
}
});
}, node._reindexWait || Bitcoin.DEFAULT_REINDEX_INTERVAL);
} else {
callback();
}
};
Bitcoin.prototype._loadTipFromNode = function(node, callback) {
var self = this;
node.client.getBestBlockHash(function(err, response) {
if (err && err.code === -28) {
log.warn(err.message);
return callback(self._wrapRPCError(err));
} else if (err) {
return callback(self._wrapRPCError(err));
}
node.client.getBlock(response.result, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
self.height = response.result.height;
$.checkState(self.height >= 0);
self.emit('tip', self.height);
callback();
});
});
};
Bitcoin.prototype._stopSpawnedBitcoin = function(callback) {
var self = this;
var spawnOptions = this.options.spawn;
var pidPath = spawnOptions.datadir + '/capricoinplusd.pid';
function stopProcess() {
fs.readFile(pidPath, 'utf8', function(err, pid) {
if (err && err.code === 'ENOENT') {
// pid file doesn't exist we can continue
return callback(null);
} else if (err) {
return callback(err);
}
pid = parseInt(pid);
if (!Number.isFinite(pid)) {
// pid doesn't exist we can continue
return callback(null);
}
try {
log.warn('Stopping existing spawned capricoinplus process with pid: ' + pid);
self._process.kill(pid, 'SIGINT');
} catch(err) {
if (err && err.code === 'ESRCH') {
log.warn('Unclean capricoinplus process shutdown, process not found with pid: ' + pid);
return callback(null);
} else if(err) {
return callback(err);
}
}
setTimeout(function() {
stopProcess();
}, self.spawnStopTime);
});
}
stopProcess();
};
Bitcoin.prototype._spawnChildProcess = function(callback) {
var self = this;
var node = {};
node._reindex = false;
node._reindexWait = 10000;
try {
self._loadSpawnConfiguration(node);
} catch(e) {
return callback(e);
}
var options = [
'--conf=' + this.spawn.configPath,
'--datadir=' + this.spawn.datadir,
];
if (self._getNetworkOption()) {
options.push(self._getNetworkOption());
}
self._stopSpawnedBitcoin(function(err) {
if (err) {
return callback(err);
}
log.info('Starting capricoinplus process');
self.spawn.process = spawn(self.spawn.exec, options, {stdio: 'inherit'});
self.spawn.process.on('error', function(err) {
self.emit('error', err);
});
self.spawn.process.once('exit', function(code) {
if (!self.node.stopping) {
log.warn('CapricoinPlus process unexpectedly exited with code:', code);
log.warn('Restarting capricoinplus child process in ' + self.spawnRestartTime + 'ms');
setTimeout(function() {
self._spawnChildProcess(function(err) {
if (err) {
return self.emit('error', err);
}
log.warn('CapricoinPlus process restarted');
});
}, self.spawnRestartTime);
}
});
var exitShutdown = false;
async.retry({times: 60, interval: self.startRetryInterval}, function(done) {
if (self.node.stopping) {
exitShutdown = true;
return done();
}
node.client = new BitcoinRPC({
protocol: 'http',
host: '127.0.0.1',
port: self.spawn.config.rpcport,
user: self.spawn.config.rpcuser,
pass: self.spawn.config.rpcpassword
});
self._loadTipFromNode(node, done);
}, function(err) {
if (err) {
return callback(err);
}
if (exitShutdown) {
return callback(new Error('Stopping while trying to spawn capricoinplusd.'));
}
self._initZmqSubSocket(node, self.spawn.config.zmqpubrawtx);
self._checkReindex(node, function(err) {
if (err) {
return callback(err);
}
self._checkSyncedAndSubscribeZmqEvents(node);
callback(null, node);
});
});
});
};
Bitcoin.prototype._connectProcess = function(config, callback) {
var self = this;
var node = {};
var exitShutdown = false;
async.retry({times: 60, interval: self.startRetryInterval}, function(done) {
if (self.node.stopping) {
exitShutdown = true;
return done();
}
node.client = new BitcoinRPC({
protocol: config.rpcprotocol || 'http',
host: config.rpchost || '127.0.0.1',
port: config.rpcport,
user: config.rpcuser,
pass: config.rpcpassword,
rejectUnauthorized: _.isUndefined(config.rpcstrict) ? true : config.rpcstrict
});
self._loadTipFromNode(node, done);
}, function(err) {
if (err) {
return callback(err);
}
if (exitShutdown) {
return callback(new Error('Stopping while trying to connect to capricoinplusd.'));
}
self._initZmqSubSocket(node, config.zmqpubrawtx);
self._subscribeZmqEvents(node);
callback(null, node);
});
};
/**
* Called by Node to start the service
* @param {Function} callback
*/
Bitcoin.prototype.start = function(callback) {
var self = this;
async.series([
function(next) {
if (self.options.spawn) {
self._spawnChildProcess(function(err, node) {
if (err) {
return next(err);
}
self.nodes.push(node);
next();
});
} else {
next();
}
},
function(next) {
if (self.options.connect) {
async.map(self.options.connect, self._connectProcess.bind(self), function(err, nodes) {
if (err) {
return callback(err);
}
for(var i = 0; i < nodes.length; i++) {
self.nodes.push(nodes[i]);
}
next();
});
} else {
next();
}
}
], function(err) {
if (err) {
return callback(err);
}
if (self.nodes.length === 0) {
return callback(new Error('CapricoinPlus configuration options "spawn" or "connect" are expected'));
}
self._initChain(callback);
});
};
/**
* Helper to determine the state of the database.
* @param {Function} callback
*/
Bitcoin.prototype.isSynced = function(callback) {
this.syncPercentage(function(err, percentage) {
if (err) {
return callback(err);
}
if (Math.round(percentage) >= 100) {
callback(null, true);
} else {
callback(null, false);
}
});
};
/**
* Helper to determine the progress of the database.
* @param {Function} callback
*/
Bitcoin.prototype.syncPercentage = function(callback) {
var self = this;
this.client.getBlockchainInfo(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var percentSynced = response.result.verificationprogress * 100;
callback(null, percentSynced);
});
};
Bitcoin.prototype._normalizeAddressArg = function(addressArg) {
var addresses = [addressArg];
if (Array.isArray(addressArg)) {
addresses = addressArg;
}
return addresses;
};
/**
* Will get the balance for an address or multiple addresses
* @param {String|Address|Array} addressArg - An address string, bitcore address, or array of addresses
* @param {Object} options
* @param {Function} callback
*/
Bitcoin.prototype.getAddressBalance = function(addressArg, options, callback) {
var self = this;
var addresses = self._normalizeAddressArg(addressArg);
var cacheKey = addresses.join('');
var balance = self.balanceCache.get(cacheKey);
if (balance) {
return setImmediate(function() {
callback(null, balance);
});
} else {
this.client.getAddressBalance({addresses: addresses}, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
self.balanceCache.set(cacheKey, response.result);
callback(null, response.result);
});
}
};
/**
* Will get the unspent outputs for an address or multiple addresses
* @param {String|Address|Array} addressArg - An address string, bitcore address, or array of addresses
* @param {Object} options
* @param {Function} callback
*/
Bitcoin.prototype.getAddressUnspentOutputs = function(addressArg, options, callback) {
var self = this;
var queryMempool = _.isUndefined(options.queryMempool) ? true : options.queryMempool;
var addresses = self._normalizeAddressArg(addressArg);
var cacheKey = addresses.join('');
var utxos = self.utxosCache.get(cacheKey);
function transformUnspentOutput(delta) {
var script = bitcore.Script.fromAddress(delta.address);
return {
address: delta.address,
txid: delta.txid,
outputIndex: delta.index,
script: script.toHex(),
satoshis: delta.satoshis,
timestamp: delta.timestamp
};
}
function updateWithMempool(confirmedUtxos, mempoolDeltas) {
/* jshint maxstatements: 20 */
if (!mempoolDeltas || !mempoolDeltas.length) {
return confirmedUtxos;
}
var isSpentOutputs = false;
var mempoolUnspentOutputs = [];
var spentOutputs = [];
for (var i = 0; i < mempoolDeltas.length; i++) {
var delta = mempoolDeltas[i];
if (delta.prevtxid && delta.satoshis <= 0) {
if (!spentOutputs[delta.prevtxid]) {
spentOutputs[delta.prevtxid] = [delta.prevout];
} else {
spentOutputs[delta.prevtxid].push(delta.prevout);
}
isSpentOutputs = true;
} else {
mempoolUnspentOutputs.push(transformUnspentOutput(delta));
}
}
var utxos = mempoolUnspentOutputs.reverse().concat(confirmedUtxos);
if (isSpentOutputs) {
return utxos.filter(function(utxo) {
if (!spentOutputs[utxo.txid]) {
return true;
} else {
return (spentOutputs[utxo.txid].indexOf(utxo.outputIndex) === -1);
}
});
}
return utxos;
}
function finish(mempoolDeltas) {
if (utxos) {
return setImmediate(function() {
callback(null, updateWithMempool(utxos, mempoolDeltas));
});
} else {
self.client.getAddressUtxos({addresses: addresses}, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var utxos = response.result.reverse();
self.utxosCache.set(cacheKey, utxos);
callback(null, updateWithMempool(utxos, mempoolDeltas));
});
}
}
if (queryMempool) {
self.client.getAddressMempool({addresses: addresses}, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
finish(response.result);
});
} else {
finish();
}
};
Bitcoin.prototype._getBalanceFromMempool = function(deltas) {
var satoshis = 0;
for (var i = 0; i < deltas.length; i++) {
satoshis += deltas[i].satoshis;
}
return satoshis;
};
Bitcoin.prototype._getTxidsFromMempool = function(deltas) {
var mempoolTxids = [];
var mempoolTxidsKnown = {};
for (var i = 0; i < deltas.length; i++) {
var txid = deltas[i].txid;
if (!mempoolTxidsKnown[txid]) {
mempoolTxids.push(txid);
mempoolTxidsKnown[txid] = true;
}
}
return mempoolTxids;
};
Bitcoin.prototype._getHeightRangeQuery = function(options, clone) {
if (options.start >= 0 && options.end >= 0) {
if (options.end > options.start) {
throw new TypeError('"end" is expected to be less than or equal to "start"');
}
if (clone) {
// reverse start and end as the order in bitcore is most recent to less recent
clone.start = options.end;
clone.end = options.start;
}
return true;
}
return false;
};
/**
* Will get the txids for an address or multiple addresses
* @param {String|Address|Array} addressArg - An address string, bitcore address, or array of addresses
* @param {Object} options
* @param {Function} callback
*/
Bitcoin.prototype.getAddressTxids = function(addressArg, options, callback) {
/* jshint maxstatements: 20 */
var self = this;
var queryMempool = _.isUndefined(options.queryMempool) ? true : options.queryMempool;
var queryMempoolOnly = _.isUndefined(options.queryMempoolOnly) ? false : options.queryMempoolOnly;
var rangeQuery = false;
try {
rangeQuery = self._getHeightRangeQuery(options);
} catch(err) {
return callback(err);
}
if (rangeQuery) {
queryMempool = false;
}
if (queryMempoolOnly) {
queryMempool = true;
rangeQuery = false;
}
var addresses = self._normalizeAddressArg(addressArg);
var cacheKey = addresses.join('');
var mempoolTxids = [];
var txids = queryMempoolOnly ? false : self.txidsCache.get(cacheKey);
function finish() {
if (queryMempoolOnly) {
return setImmediate(function() {
callback(null, mempoolTxids.reverse());
});
}
if (txids && !rangeQuery) {
var allTxids = mempoolTxids.reverse().concat(txids);
return setImmediate(function() {
callback(null, allTxids);
});
} else {
var txidOpts = {
addresses: addresses
};
if (rangeQuery) {
self._getHeightRangeQuery(options, txidOpts);
}
self.client.getAddressTxids(txidOpts, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
response.result.reverse();
if (!rangeQuery) {
self.txidsCache.set(cacheKey, response.result);
}
var allTxids = mempoolTxids.reverse().concat(response.result);
return callback(null, allTxids);
});
}
}
if (queryMempool) {
self.client.getAddressMempool({addresses: addresses}, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
mempoolTxids = self._getTxidsFromMempool(response.result);
finish();
});
} else {
finish();
}
};
Bitcoin.prototype._getConfirmationsDetail = function(transaction) {
$.checkState(this.height > 0, 'current height is unknown');
var confirmations = 0;
if (transaction.height >= 0) {
confirmations = this.height - transaction.height + 1;
}
if (confirmations < 0) {
log.warn('Negative confirmations calculated for transaction:', transaction.hash);
}
return Math.max(0, confirmations);
};
Bitcoin.prototype._getAddressDetailsForInput = function(input, inputIndex, result, addressStrings) {
if (!input.address) {
return;
}
var address = input.address;
if (addressStrings.indexOf(address) >= 0) {
if (!result.addresses[address]) {
result.addresses[address] = {
inputIndexes: [inputIndex],
outputIndexes: []
};
} else {
result.addresses[address].inputIndexes.push(inputIndex);
}
result.satoshis -= input.satoshis;
}
};
Bitcoin.prototype._getAddressDetailsForOutput = function(output, outputIndex, result, addressStrings) {
if (!output.address) {
return;
}
var address = output.address;
if (addressStrings.indexOf(address) >= 0) {
if (!result.addresses[address]) {
result.addresses[address] = {
inputIndexes: [],
outputIndexes: [outputIndex]
};
} else {
result.addresses[address].outputIndexes.push(outputIndex);
}
result.satoshis += output.satoshis;
}
};
Bitcoin.prototype._getAddressDetailsForTransaction = function(transaction, addressStrings) {
var result = {
addresses: {},
satoshis: 0
};
for (var inputIndex = 0; inputIndex < transaction.inputs.length; inputIndex++) {
var input = transaction.inputs[inputIndex];
this._getAddressDetailsForInput(input, inputIndex, result, addressStrings);
}
for (var outputIndex = 0; outputIndex < transaction.outputs.length; outputIndex++) {
var output = transaction.outputs[outputIndex];
this._getAddressDetailsForOutput(output, outputIndex, result, addressStrings);
}
$.checkState(Number.isFinite(result.satoshis));
return result;
};
/**
* Will expand into a detailed transaction from a txid
* @param {Object} txid - A bitcoin transaction id
* @param {Function} callback
*/
Bitcoin.prototype._getAddressDetailedTransaction = function(txid, options, next) {
var self = this;
self.getDetailedTransaction(
txid,
function(err, transaction) {
if (err) {
return next(err);
}
var addressDetails = self._getAddressDetailsForTransaction(transaction, options.addressStrings);
var details = {
addresses: addressDetails.addresses,
satoshis: addressDetails.satoshis,
confirmations: self._getConfirmationsDetail(transaction),
tx: transaction
};
next(null, details);
}
);
};
Bitcoin.prototype._getAddressStrings = function(addresses) {
var addressStrings = [];
for (var i = 0; i < addresses.length; i++) {
var address = addresses[i];
if (address instanceof bitcore.Address) {
addressStrings.push(address.toString());
} else if (_.isString(address)) {
addressStrings.push(address);
} else {
throw new TypeError('Addresses are expected to be strings');
}
}
return addressStrings;
};
Bitcoin.prototype._paginateTxids = function(fullTxids, fromArg, toArg) {
var txids;
var from = parseInt(fromArg);
var to = parseInt(toArg);
$.checkState(from < to, '"from" (' + from + ') is expected to be less than "to" (' + to + ')');
txids = fullTxids.slice(from, to);
return txids;
};
/**
* Will detailed transaction history for an address or multiple addresses
* @param {String|Address|Array} addressArg - An address string, bitcore address, or array of addresses
* @param {Object} options
* @param {Function} callback
*/
Bitcoin.prototype.getAddressHistory = function(addressArg, options, callback) {
var self = this;
var addresses = self._normalizeAddressArg(addressArg);
if (addresses.length > this.maxAddressesQuery) {
return callback(new TypeError('Maximum number of addresses (' + this.maxAddressesQuery + ') exceeded'));
}
var queryMempool = _.isUndefined(options.queryMempool) ? true : options.queryMempool;
var addressStrings = this._getAddressStrings(addresses);
var fromArg = parseInt(options.from || 0);
var toArg = parseInt(options.to || self.maxTransactionHistory);
if ((toArg - fromArg) > self.maxTransactionHistory) {
return callback(new Error(
'"from" (' + options.from + ') and "to" (' + options.to + ') range should be less than or equal to ' +
self.maxTransactionHistory
));
}
self.getAddressTxids(addresses, options, function(err, txids) {
if (err) {
return callback(err);
}
var totalCount = txids.length;
try {
txids = self._paginateTxids(txids, fromArg, toArg);
} catch(e) {
return callback(e);
}
async.mapLimit(
txids,
self.transactionConcurrency,
function(txid, next) {
self._getAddressDetailedTransaction(txid, {
queryMempool: queryMempool,
addressStrings: addressStrings
}, next);
},
function(err, transactions) {
if (err) {
return callback(err);
}
callback(null, {
totalCount: totalCount,
items: transactions
});
}
);
});
};
/**
* Will get the summary including txids and balance for an address or multiple addresses
* @param {String|Address|Array} addressArg - An address string, bitcore address, or array of addresses
* @param {Object} options
* @param {Function} callback
*/
Bitcoin.prototype.getAddressSummary = function(addressArg, options, callback) {
var self = this;
var summary = {};
var queryMempool = _.isUndefined(options.queryMempool) ? true : options.queryMempool;
var summaryTxids = [];
var mempoolTxids = [];
var addresses = self._normalizeAddressArg(addressArg);
var cacheKey = addresses.join('');
function finishWithTxids() {
if (!options.noTxList) {
var allTxids = mempoolTxids.reverse().concat(summaryTxids);
var fromArg = parseInt(options.from || 0);
var toArg = parseInt(options.to || self.maxTxids);
if ((toArg - fromArg) > self.maxTxids) {
return callback(new Error(
'"from" (' + fromArg + ') and "to" (' + toArg + ') range should be less than or equal to ' +
self.maxTxids
));
}
var paginatedTxids;
try {
paginatedTxids = self._paginateTxids(allTxids, fromArg, toArg);
} catch(e) {
return callback(e);
}
var allSummary = _.clone(summary);
allSummary.txids = paginatedTxids;
callback(null, allSummary);
} else {
callback(null, summary);
}
}
function querySummary() {
async.parallel([
function getTxList(done) {
self.getAddressTxids(addresses, {queryMempool: false}, function(err, txids) {
if (err) {
return done(err);
}
summaryTxids = txids;
summary.appearances = txids.length;
done();
});
},
function getBalance(done) {
self.getAddressBalance(addresses, options, function(err, data) {
if (err) {
return done(err);
}
summary.totalReceived = data.received;
summary.totalSpent = data.received - data.balance;
summary.balance = data.balance;
done();
});
},
function getMempool(done) {
if (!queryMempool) {
return done();
}
self.client.getAddressMempool({'addresses': addresses}, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
mempoolTxids = self._getTxidsFromMempool(response.result);
summary.unconfirmedAppearances = mempoolTxids.length;
summary.unconfirmedBalance = self._getBalanceFromMempool(response.result);
done();
});
},
], function(err) {
if (err) {
return callback(err);
}
self.summaryCache.set(cacheKey, summary);
finishWithTxids();
});
}
if (options.noTxList) {
var summaryCache = self.summaryCache.get(cacheKey);
if (summaryCache) {
callback(null, summaryCache);
} else {
querySummary();
}
} else {
querySummary();
}
};
Bitcoin.prototype._maybeGetBlockHash = function(blockArg, callback) {
var self = this;
if (_.isNumber(blockArg) || (blockArg.length < 40 && /^[0-9]+$/.test(blockArg))) {
self._tryAllClients(function(client, done) {
client.getBlockHash(blockArg, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
done(null, response.result);
});
}, callback);
} else {
callback(null, blockArg);
}
};
/**
* Will retrieve a block as a Node.js Buffer
* @param {String|Number} block - A block hash or block height number
* @param {Function} callback
*/
Bitcoin.prototype.getRawBlock = function(blockArg, callback) {
// TODO apply performance patch to the RPC method for raw data
var self = this;
function queryBlock(err, blockhash) {
if (err) {
return callback(err);
}
self._tryAllClients(function(client, done) {
self.client.getBlock(blockhash, false, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var buffer = new Buffer(response.result, 'hex');
self.rawBlockCache.set(blockhash, buffer);
done(null, buffer);
});
}, callback);
}
var cachedBlock = self.rawBlockCache.get(blockArg);
if (cachedBlock) {
return setImmediate(function() {
callback(null, cachedBlock);
});
} else {
self._maybeGetBlockHash(blockArg, queryBlock);
}
};
/**
* Similar to getBlockHeader but will include a list of txids
* @param {String|Number} block - A block hash or block height number
* @param {Function} callback
*/
Bitcoin.prototype.getBlockOverview = function(blockArg, callback) {
var self = this;
function queryBlock(err, blockhash) {
if (err) {
return callback(err);
}
var cachedBlock = self.blockOverviewCache.get(blockhash);
if (cachedBlock) {
return setImmediate(function() {
callback(null, cachedBlock);
});
} else {
self._tryAllClients(function(client, done) {
client.getBlock(blockhash, true, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var result = response.result;
var blockOverview = {
hash: result.hash,
version: result.version,
confirmations: result.confirmations,
height: result.height,
chainWork: result.chainwork,
prevHash: result.previousblockhash,
nextHash: result.nextblockhash,
merkleRoot: result.merkleroot,
time: result.time,
medianTime: result.mediantime,
nonce: result.nonce,
bits: result.bits,
difficulty: result.difficulty,
txids: result.tx
};
self.blockOverviewCache.set(blockhash, blockOverview);
done(null, blockOverview);
});
}, callback);
}
}
self._maybeGetBlockHash(blockArg, queryBlock);
};
/**
* Will retrieve a block as a Bitcore object
* @param {String|Number} block - A block hash or block height number
* @param {Function} callback
*/
Bitcoin.prototype.getBlock = function(blockArg, callback) {
// TODO apply performance patch to the RPC method for raw data
var self = this;
function queryBlock(err, blockhash) {
if (err) {
return callback(err);
}
var cachedBlock = self.blockCache.get(blockhash);
if (cachedBlock) {
return setImmediate(function() {
callback(null, cachedBlock);
});
} else {
self._tryAllClients(function(client, done) {
client.getBlock(blockhash, false, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var blockObj = bitcore.Block.fromString(response.result);
self.blockCache.set(blockhash, blockObj);
done(null, blockObj);
});
}, callback);
}
}
self._maybeGetBlockHash(blockArg, queryBlock);
};
/**
* Will retrieve an array of block hashes within a range of timestamps
* @param {Number} high - The more recent timestamp in seconds
* @param {Number} low - The older timestamp in seconds
* @param {Function} callback
*/
Bitcoin.prototype.getBlockHashesByTimestamp = function(high, low, options, callback) {
var self = this;
if (_.isFunction(options)) {
callback = options;
options = {};
}
self.client.getBlockHashes(high, low, options, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
callback(null, response.result);
});
};
/**
* Will return the block index information, the output will have the format:
* {
* hash: '0000000000000a817cd3a74aec2f2246b59eb2cbb1ad730213e6c4a1d68ec2f6',
* confirmations: 5,
* height: 828781,
* chainWork: '00000000000000000000000000000000000000000000000ad467352c93bc6a3b',
* prevHash: '0000000000000504235b2aff578a48470dbf6b94dafa9b3703bbf0ed554c9dd9',
* nextHash: '00000000000000eedd967ec155f237f033686f0924d574b946caf1b0e89551b8'
* version: 536870912,
* merkleRoot: '124e0f3fb5aa268f102b0447002dd9700988fc570efcb3e0b5b396ac7db437a9',
* time: 1462979126,
* medianTime: 1462976771,
* nonce: 2981820714,
* bits: '1a13ca10',
* difficulty: 847779.0710240941,
* }
* @param {String|Number} block - A block hash or block height
* @param {Function} callback
*/
Bitcoin.prototype.getBlockHeader = function(blockArg, callback) {
var self = this;
function queryHeader(err, blockhash) {
if (err) {
return callback(err);
}
self._tryAllClients(function(client, done) {
client.getBlockHeader(blockhash, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var result = response.result;
var header = {
hash: result.hash,
version: result.version,
confirmations: result.confirmations,
height: result.height,
chainWork: result.chainwork,
prevHash: result.previousblockhash,
nextHash: result.nextblockhash,
merkleRoot: result.merkleroot,
time: result.time,
medianTime: result.mediantime,
nonce: result.nonce,
bits: result.bits,
difficulty: result.difficulty
};
done(null, header);
});
}, callback);
}
self._maybeGetBlockHash(blockArg, queryHeader);
};
/**
* Will estimate the fee per kilobyte.
* @param {Number} blocks - The number of blocks for the transaction to be confirmed.
* @param {Function} callback
*/
Bitcoin.prototype.estimateFee = function(blocks, callback) {
var self = this;
this.client.estimateFee(blocks, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
callback(null, response.result);
});
};
/**
* Will add a transaction to the mempool and relay to connected peers
* @param {String|Transaction} transaction - The hex string of the transaction
* @param {Object=} options
* @param {Boolean=} options.allowAbsurdFees - Enable large fees
* @param {Function} callback
*/
Bitcoin.prototype.sendTransaction = function(tx, options, callback) {
var self = this;
var allowAbsurdFees = false;
if (_.isFunction(options) && _.isUndefined(callback)) {
callback = options;
} else if (_.isObject(options)) {
allowAbsurdFees = options.allowAbsurdFees;
}
this.client.sendRawTransaction(tx, allowAbsurdFees, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
callback(null, response.result);
});
};
/**
* Will get a transaction as a Node.js Buffer. Results include the mempool.
* @param {String} txid - The transaction hash
* @param {Function} callback
*/
Bitcoin.prototype.getRawTransaction = function(txid, callback) {
var self = this;
var tx = self.rawTransactionCache.get(txid);
if (tx) {
return setImmediate(function() {
callback(null, tx);
});
} else {
self._tryAllClients(function(client, done) {
client.getRawTransaction(txid, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var buffer = new Buffer(response.result, 'hex');
self.rawTransactionCache.set(txid, buffer);
done(null, buffer);
});
}, callback);
}
};
/**
* Will get a transaction as a Bitcore Transaction. Results include the mempool.
* @param {String} txid - The transaction hash
* @param {Boolean} queryMempool - Include the mempool
* @param {Function} callback
*/
Bitcoin.prototype.getTransaction = function(txid, callback) {
var self = this;
var tx = self.transactionCache.get(txid);
if (tx) {
return setImmediate(function() {
callback(null, tx);
});
} else {
self._tryAllClients(function(client, done) {
client.getRawTransaction(txid, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var tx = Transaction();
tx.fromString(response.result);
self.transactionCache.set(txid, tx);
done(null, tx);
});
}, callback);
}
};
/**
* Will get a detailed view of a transaction including addresses, amounts and fees.
*
* Example result:
* {
* blockHash: '000000000000000002cd0ba6e8fae058747d2344929ed857a18d3484156c9250',
* height: 411462,
* blockTimestamp: 1463070382,
* version: 1,
* hash: 'de184cc227f6d1dc0316c7484aa68b58186a18f89d853bb2428b02040c394479',
* locktime: 411451,
* coinbase: true,
* inputs: [
* {
* prevTxId: '3d003413c13eec3fa8ea1fe8bbff6f40718c66facffe2544d7516c9e2900cac2',
* outputIndex: 0,
* sequence: 123456789,
* script: [hexString],
* scriptAsm: [asmString],
* address: '1LCTmj15p7sSXv3jmrPfA6KGs6iuepBiiG',
* satoshis: 771146
* }
* ],
* outputs: [
* {
* satoshis: 811146,
* script: '76a914d2955017f4e3d6510c57b427cf45ae29c372c99088ac',
* scriptAsm: 'OP_DUP OP_HASH160 d2955017f4e3d6510c57b427cf45ae29c372c990 OP_EQUALVERIFY OP_CHECKSIG',
* address: '1LCTmj15p7sSXv3jmrPfA6KGs6iuepBiiG',
* spentTxId: '4316b98e7504073acd19308b4b8c9f4eeb5e811455c54c0ebfe276c0b1eb6315',
* spentIndex: 1,
* spentHeight: 100
* }
* ],
* inputSatoshis: 771146,
* outputSatoshis: 811146,
* feeSatoshis: 40000
* };
*
* @param {String} txid - The hex string of the transaction
* @param {Function} callback
*/
Bitcoin.prototype.getDetailedTransaction = function(txid, callback) {
var self = this;
var tx = self.transactionDetailedCache.get(txid);
function addInputsToTx(tx, result, counts) {
tx.inputs = [];
tx.inputSatoshis = 0;
for(var inputIndex = 0; inputIndex < result.vin.length; inputIndex++) {
var input = result.vin[inputIndex];
if (!tx.coinbase) {
tx.inputSatoshis += input.valueSat;
}
var script = null;
var scriptAsm = null;
if (input.scriptSig) {
script = input.scriptSig.hex;
scriptAsm = input.scriptSig.asm;
} else if (input.coinbase) {
script = input.coinbase;
}
tx.inputs.push({
type: input.type || null,
num_inputs: input.num_inputs || null,
ring_size: input.ring_size || null,
prevTxId: input.txid || null,
outputIndex: _.isUndefined(input.vout) ? null : input.vout,
script: script,
scriptAsm: scriptAsm || null,
sequence: input.sequence,
address: input.address || null,
satoshis: _.isUndefined(input.valueSat) ? null : input.valueSat,
witnessStack: input.txinwitness
});
}
}
function addOutputsToTx(tx, result, counts) {
tx.outputs = [];
tx.outputSatoshis = 0;
for(var outputIndex = 0; outputIndex < result.vout.length; outputIndex++) {
var out = result.vout[outputIndex];
var address = null;
if (out.scriptPubKey && out.scriptPubKey.addresses && out.scriptPubKey.addresses.length === 1) {
address = out.scriptPubKey.addresses[0];
}
if (out.type == 'standard')
{
tx.outputs.push({
type: out.type,
satoshis: out.valueSat,
script: out.scriptPubKey.hex,
scriptAsm: out.scriptPubKey.asm,
spentTxId: out.spentTxId,
spentIndex: out.spentIndex,
spentHeight: out.spentHeight,
address: address
});
tx.outputSatoshis += out.valueSat;
} else
if (out.type == 'data')
{
tx.outputs.push({
type: out.type,
satoshis: 0,
script: "",
scriptAsm: "",
spentTxId: "",
spentIndex: "",
spentHeight: "",
address: "",
data: out.data_hex
});
} else
if (out.type == 'blind')
{
counts.nct++;
tx.outputs.push({
type: out.type,
satoshis: 0,
script: out.scriptPubKey.hex,
scriptAsm: out.scriptPubKey.asm,
spentTxId: out.spentTxId,
spentIndex: out.spentIndex,
spentHeight: out.spentHeight,
address: address,
valueCommitment: out.valueCommitment,
data: out.data_hex,
rangeproof: out.rangeproof,
rp_exponent: out.rp_exponent,
rp_mantissa: out.rp_mantissa,
rp_min_value: out.rp_min_value,
rp_max_value: out.rp_max_value,
rp_size: out.rangeproof.length / 2
});
} else
if (out.type == 'anon')
{
var pk = new bitcore.PublicKey(out.pubkey);
tx.outputs.push({
type: out.type,
satoshis: 0,
//pubkey: out.pubkey,
address: bitcore.Address.fromPublicKey(pk, self.node.network).toString(),
valueCommitment: out.valueCommitment,
data: out.data_hex,
rangeproof: out.rangeproof,
rp_exponent: out.rp_exponent,
rp_mantissa: out.rp_mantissa,
rp_min_value: out.rp_min_value,
rp_max_value: out.rp_max_value,
rp_size: out.rangeproof.length / 2
});
counts.nrct++;
} else
{
process.stdout.write("Unknown output type: " + obj.type + "\n");
}
}
}
if (tx) {
return setImmediate(function() {
callback(null, tx);
});
} else {
self._tryAllClients(function(client, done) {
client.getRawTransaction(txid, 1, function(err, response) {
if (err) {
return done(self._wrapRPCError(err));
}
var result = response.result;
var tx = {
hex: result.hex,
blockHash: result.blockhash,
height: (result.height || result.confirmations) ? result.height : -1,
blockTimestamp: result.time,
version: result.version,
hash: txid,
locktime: result.locktime,
};
if (result.vin[0] && result.vin[0].coinbase) {
tx.coinbase = true;
}
var counts = {};
counts.nct = 0;
counts.nrct = 0;
addInputsToTx(tx, result, counts);
tx.feeSatoshis = -1;
addOutputsToTx(tx, result, counts);
if (!tx.coinbase) {
if (tx.feeSatoshis == -1)
{
if (counts.nct == 0 && counts.nrct == 0)
{
tx.feeSatoshis = tx.inputSatoshis - tx.outputSatoshis;
} else
{
// fee must be encoded in data output
}
}
} else {
tx.feeSatoshis = 0;
}
self.transactionDetailedCache.set(txid, tx);
done(null, tx);
});
}, callback);
}
};
/**
* Will get the best block hash for the chain.
* @param {Function} callback
*/
Bitcoin.prototype.getBestBlockHash = function(callback) {
var self = this;
this.client.getBestBlockHash(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
callback(null, response.result);
});
};
/**
* Will give the txid and inputIndex that spent an output
* @param {Function} callback
*/
Bitcoin.prototype.getSpentInfo = function(options, callback) {
var self = this;
this.client.getSpentInfo(options, function(err, response) {
if (err && err.code === -5) {
return callback(null, {});
} else if (err) {
return callback(self._wrapRPCError(err));
}
callback(null, response.result);
});
};
/**
* This will return information about the database in the format:
* {
* version: 110000,
* protocolVersion: 70002,
* blocks: 151,
* timeOffset: 0,
* connections: 0,
* difficulty: 4.6565423739069247e-10,
* testnet: false,
* network: 'testnet'
* relayFee: 1000,
* errors: ''
* }
* @param {Function} callback
Bitcoin.prototype.getInfo = function(callback) {
var self = this;
this.client.getInfo(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var result = response.result;
var info = {
version: result.version,
protocolVersion: result.protocolversion,
blocks: result.blocks,
moneysupply: result.moneysupply,
timeOffset: result.timeoffset,
connections: result.connections,
proxy: result.proxy,
difficulty: result.difficulty,
testnet: result.testnet,
relayFee: result.relayfee,
errors: result.errors,
network: self.node.getNetworkName()
};
callback(null, info);
});
};
*/
Bitcoin.prototype.getBlockchainInfo = function(callback) {
var self = this;
this.client.getBlockchainInfo(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var result = response.result;
var info = {
blocks: result.blocks,
headers: result.headers,
bestblockhash: result.bestblockhash,
moneysupply: result.moneysupply,
difficulty: result.difficulty,
testnet: result.testnet,
warnings: result.warnings,
chain: result.chain,
};
callback(null, info);
});
};
Bitcoin.prototype.getNetworkInfo = function(callback) {
var self = this;
this.client.getNetworkInfo(function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
var result = response.result;
var info = {
version: result.version,
protocolVersion: result.protocolversion,
timeOffset: result.timeoffset,
connections: result.connections,
relayFee: result.relayfee,
};
callback(null, info);
});
};
Bitcoin.prototype.generateBlock = function(num, callback) {
var self = this;
this.client.generate(num, function(err, response) {
if (err) {
return callback(self._wrapRPCError(err));
}
callback(null, response.result);
});
};
/**
* Called by Node to stop the service.
* @param {Function} callback
*/
Bitcoin.prototype.stop = function(callback) {
if (this.spawn && this.spawn.process) {
var exited = false;
this.spawn.process.once('exit', function(code) {
if (!exited) {
exited = true;
if (code !== 0) {
var error = new Error('bitcoind spawned process exited with status code: ' + code);
error.code = code;
return callback(error);
} else {
return callback();
}
}
});
this.spawn.process.kill('SIGINT');
setTimeout(function() {
if (!exited) {
exited = true;
return callback(new Error('bitcoind process did not exit'));
}
}, this.shutdownTimeout).unref();
} else {
callback();
}
};
module.exports = Bitcoin;
|
# MIT License
#
# Copyright (c) 2019 Tuomas Halvari, Juha Harviainen, Juha Mylläri, Antti Röyskö, Juuso Silvennoinen
#
# 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.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from dpemu.nodes import Array
from dpemu.filters.image import Blur, BlurGaussian, Brightness, JPEG_Compression, \
LensFlare, Rain, Resolution, Rotation, Saturation, Snow, StainArea
fig = plt.figure(figsize=(8, 8))
def visualize(title, ind, data, flt, params):
root_node = Array()
root_node.addfilter(flt)
result = root_node.generate_error(data, params)
sub = fig.add_subplot(3, 4, ind + 1)
sub.imshow(result)
sub.set_title(title)
def applyBlur(data, ind):
visualize("Blur", ind, data, Blur("rep", "rad"), {"rep": 3, "rad": 10})
def applyBlurGaussian(data, ind):
visualize("Gaussian Blur", ind, data, BlurGaussian("std"), {"std": 5})
def applyBrightness(data, ind):
visualize("Brightness", ind, data, Brightness("tar", "rat", "range"), {"tar": 1, "rat": 0.5, "range": 255})
def applyJPEGCompression(data, ind):
visualize("JPEG Compression", ind, data, JPEG_Compression("qual"), {"qual": 3})
def applyLensFlare(data, ind):
visualize("Lens Flare", ind, data, LensFlare(), {})
def applyRain(data, ind):
visualize("Rain", ind, data, Rain("prob", "range"), {"prob": 0.005, "range": 255})
def applyResolution(data, ind):
visualize("Resolution", ind, data, Resolution("k"), {"k": 10})
def applyRotation(data, ind):
visualize("Rotation", ind, data, Rotation("min_a", "max_a"), {"min_a": -30, "max_a": 30})
def applySaturation(data, ind):
visualize("Saturation", ind, data, Saturation("tar", "rat", "range"), {"tar": 0, "rat": 0.5, "range": 255})
def applySnow(data, ind):
visualize("Snow", ind, data, Snow("prob", "flake_a", "backg_a"), {"prob": 0.001, "flake_a": 0.9, "backg_a": 1})
def applyStainArea(data, ind):
class rd_gen():
def generate(self, random_state):
return random_state.randint(50, 100)
visualize("Stain Area", ind, data, StainArea("prob", "rd_gen", "tsp"),
{"prob": 0.00005, "rd_gen": rd_gen(), "tsp": 0})
def main():
img = Image.open("data/landscape.png")
data = np.array(img)
applyBlur(data, 0)
applyBlurGaussian(data, 1)
applyBrightness(data, 2)
applyJPEGCompression(data, 3)
applyLensFlare(data, 4)
applyRain(data, 5)
applyResolution(data, 6)
applyRotation(data, 7)
applySaturation(data, 8)
applySnow(data, 9)
applyStainArea(data, 10)
plt.show()
if __name__ == "__main__":
main()
|
/**
* @file The entry point for the web extension singleton process.
*/
// these need to run before anything else
import './lib/freezeGlobals'
import setupFetchDebugging from './lib/setupFetchDebugging'
setupFetchDebugging()
// polyfills
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
import endOfStream from 'end-of-stream'
import pump from 'pump'
import debounce from 'debounce-stream'
import log from 'loglevel'
import extension from 'extensionizer'
import ReadOnlyNetworkStore from './lib/network-store'
import LocalStore from './lib/local-store'
import storeTransform from 'obs-store/lib/transform'
import asStream from 'obs-store/lib/asStream'
import ExtensionPlatform from './platforms/extension'
import Migrator from './lib/migrator'
import migrations from './migrations'
import PortStream from 'extension-port-stream'
import createStreamSink from './lib/createStreamSink'
import NotificationManager from './lib/notification-manager.js'
import MetamaskController from './metamask-controller'
import rawFirstTimeState from './first-time-state'
import setupSentry from './lib/setupSentry'
import reportFailedTxToSentry from './lib/reportFailedTxToSentry'
import getFirstPreferredLangCode from './lib/get-first-preferred-lang-code'
import getObjStructure from './lib/getObjStructure'
import setupEnsIpfsResolver from './lib/ens-ipfs/setup'
import {
ENVIRONMENT_TYPE_POPUP,
ENVIRONMENT_TYPE_NOTIFICATION,
ENVIRONMENT_TYPE_FULLSCREEN,
} from './lib/enums'
// METAMASK_TEST_CONFIG is used in e2e tests to set the default network to localhost
const firstTimeState = Object.assign({}, rawFirstTimeState, global.METAMASK_TEST_CONFIG)
log.setDefaultLevel(process.env.METAMASK_DEBUG ? 'debug' : 'warn')
const platform = new ExtensionPlatform()
const notificationManager = new NotificationManager()
global.METAMASK_NOTIFIER = notificationManager
// setup sentry error reporting
const release = platform.getVersion()
const sentry = setupSentry({ release })
let popupIsOpen = false
let notificationIsOpen = false
const openMetamaskTabsIDs = {}
const requestAccountTabIds = {}
// state persistence
const inTest = process.env.IN_TEST === 'true'
const localStore = inTest
? new ReadOnlyNetworkStore()
: new LocalStore()
let versionedData
if (inTest || process.env.METAMASK_DEBUG) {
global.metamaskGetState = localStore.get.bind(localStore)
}
// initialization flow
initialize().catch(log.error)
/**
* An object representing a transaction, in whatever state it is in.
* @typedef TransactionMeta
*
* @property {number} id - An internally unique tx identifier.
* @property {number} time - Time the tx was first suggested, in unix epoch time (ms).
* @property {string} status - The current transaction status (unapproved, signed, submitted, dropped, failed, rejected), as defined in `tx-state-manager.js`.
* @property {string} metamaskNetworkId - The transaction's network ID, used for EIP-155 compliance.
* @property {boolean} loadingDefaults - TODO: Document
* @property {Object} txParams - The tx params as passed to the network provider.
* @property {Object[]} history - A history of mutations to this TransactionMeta object.
* @property {string} origin - A string representing the interface that suggested the transaction.
* @property {Object} nonceDetails - A metadata object containing information used to derive the suggested nonce, useful for debugging nonce issues.
* @property {string} rawTx - A hex string of the final signed transaction, ready to submit to the network.
* @property {string} hash - A hex string of the transaction hash, used to identify the transaction on the network.
* @property {number} submittedTime - The time the transaction was submitted to the network, in Unix epoch time (ms).
*/
/**
* The data emitted from the MetaMaskController.store EventEmitter, also used to initialize the MetaMaskController. Available in UI on React state as state.metamask.
* @typedef MetaMaskState
* @property {boolean} isInitialized - Whether the first vault has been created.
* @property {boolean} isUnlocked - Whether the vault is currently decrypted and accounts are available for selection.
* @property {boolean} isAccountMenuOpen - Represents whether the main account selection UI is currently displayed.
* @property {string} rpcTarget - DEPRECATED - The URL of the current RPC provider.
* @property {Object} identities - An object matching lower-case hex addresses to Identity objects with "address" and "name" (nickname) keys.
* @property {Object} unapprovedTxs - An object mapping transaction hashes to unapproved transactions.
* @property {Array} frequentRpcList - A list of frequently used RPCs, including custom user-provided ones.
* @property {Array} addressBook - A list of previously sent to addresses.
* @property {Object} contractExchangeRates - Info about current token prices.
* @property {Array} tokens - Tokens held by the current user, including their balances.
* @property {Object} send - TODO: Document
* @property {Object} coinOptions - TODO: Document
* @property {boolean} useBlockie - Indicates preferred user identicon format. True for blockie, false for Jazzicon.
* @property {Object} featureFlags - An object for optional feature flags.
* @property {string} networkEndpointType - TODO: Document
* @property {boolean} welcomeScreen - True if welcome screen should be shown.
* @property {string} currentLocale - A locale string matching the user's preferred display language.
* @property {Object} provider - The current selected network provider.
* @property {string} provider.rpcTarget - The address for the RPC API, if using an RPC API.
* @property {string} provider.type - An identifier for the type of network selected, allows MetaMask to use custom provider strategies for known networks.
* @property {string} network - A stringified number of the current network ID.
* @property {Object} accounts - An object mapping lower-case hex addresses to objects with "balance" and "address" keys, both storing hex string values.
* @property {hex} currentBlockGasLimit - The most recently seen block gas limit, in a lower case hex prefixed string.
* @property {TransactionMeta[]} currentNetworkTxList - An array of transactions associated with the currently selected network.
* @property {Object} unapprovedMsgs - An object of messages pending approval, mapping a unique ID to the options.
* @property {number} unapprovedMsgCount - The number of messages in unapprovedMsgs.
* @property {Object} unapprovedPersonalMsgs - An object of messages pending approval, mapping a unique ID to the options.
* @property {number} unapprovedPersonalMsgCount - The number of messages in unapprovedPersonalMsgs.
* @property {Object} unapprovedEncryptionPublicKeyMsgs - An object of messages pending approval, mapping a unique ID to the options.
* @property {number} unapprovedEncryptionPublicKeyMsgCount - The number of messages in EncryptionPublicKeyMsgs.
* @property {Object} unapprovedDecryptMsgs - An object of messages pending approval, mapping a unique ID to the options.
* @property {number} unapprovedDecryptMsgCount - The number of messages in unapprovedDecryptMsgs.
* @property {Object} unapprovedTypedMsgs - An object of messages pending approval, mapping a unique ID to the options.
* @property {number} unapprovedTypedMsgCount - The number of messages in unapprovedTypedMsgs.
* @property {string[]} keyringTypes - An array of unique keyring identifying strings, representing available strategies for creating accounts.
* @property {Keyring[]} keyrings - An array of keyring descriptions, summarizing the accounts that are available for use, and what keyrings they belong to.
* @property {string} selectedAddress - A lower case hex string of the currently selected address.
* @property {string} currentCurrency - A string identifying the user's preferred display currency, for use in showing conversion rates.
* @property {number} conversionRate - A number representing the current exchange rate from the user's preferred currency to Ether.
* @property {number} conversionDate - A unix epoch date (ms) for the time the current conversion rate was last retrieved.
* @property {Object} infuraNetworkStatus - An object of infura network status checks.
* @property {boolean} forgottenPassword - Returns true if the user has initiated the password recovery screen, is recovering from seed phrase.
*/
/**
* @typedef VersionedData
* @property {MetaMaskState} data - The data emitted from MetaMask controller, or used to initialize it.
* @property {Number} version - The latest migration version that has been run.
*/
/**
* Initializes the MetaMask controller, and sets up all platform configuration.
* @returns {Promise} - Setup complete.
*/
async function initialize () {
const initState = await loadStateFromPersistence()
const initLangCode = await getFirstPreferredLangCode()
await setupController(initState, initLangCode)
log.debug('MetaMask initialization complete.')
}
//
// State and Persistence
//
/**
* Loads any stored data, prioritizing the latest storage strategy.
* Migrates that data schema in case it was last loaded on an older version.
* @returns {Promise<MetaMaskState>} - Last data emitted from previous instance of MetaMask.
*/
async function loadStateFromPersistence () {
// migrations
const migrator = new Migrator({ migrations })
migrator.on('error', console.warn)
// read from disk
// first from preferred, async API:
versionedData = (await localStore.get()) ||
migrator.generateInitialState(firstTimeState)
// check if somehow state is empty
// this should never happen but new error reporting suggests that it has
// for a small number of users
// https://github.com/metamask/metamask-extension/issues/3919
if (versionedData && !versionedData.data) {
// unable to recover, clear state
versionedData = migrator.generateInitialState(firstTimeState)
sentry.captureMessage('MetaMask - Empty vault found - unable to recover')
}
// report migration errors to sentry
migrator.on('error', (err) => {
// get vault structure without secrets
const vaultStructure = getObjStructure(versionedData)
sentry.captureException(err, {
// "extra" key is required by Sentry
extra: { vaultStructure },
})
})
// migrate data
versionedData = await migrator.migrateData(versionedData)
if (!versionedData) {
throw new Error('MetaMask - migrator returned undefined')
}
// write to disk
if (localStore.isSupported) {
localStore.set(versionedData)
} else {
// throw in setTimeout so as to not block boot
setTimeout(() => {
throw new Error('MetaMask - Localstore not supported')
})
}
// return just the data
return versionedData.data
}
/**
* Initializes the MetaMask Controller with any initial state and default language.
* Configures platform-specific error reporting strategy.
* Streams emitted state updates to platform-specific storage strategy.
* Creates platform listeners for new Dapps/Contexts, and sets up their data connections to the controller.
*
* @param {Object} initState - The initial state to start the controller with, matches the state that is emitted from the controller.
* @param {string} initLangCode - The region code for the language preferred by the current user.
* @returns {Promise} - After setup is complete.
*/
function setupController (initState, initLangCode) {
//
// MetaMask Controller
//
const controller = new MetamaskController({
// User confirmation callbacks:
showUnconfirmedMessage: triggerUi,
showUnapprovedTx: triggerUi,
showPermissionRequest: triggerUi,
showUnlockRequest: triggerUi,
openPopup,
// initial state
initState,
// initial locale code
initLangCode,
// platform specific api
platform,
getRequestAccountTabIds: () => {
return requestAccountTabIds
},
getOpenMetamaskTabsIds: () => {
return openMetamaskTabsIDs
},
})
setupEnsIpfsResolver({
getCurrentNetwork: controller.getCurrentNetwork,
getIpfsGateway: controller.preferencesController.getIpfsGateway.bind(controller.preferencesController),
provider: controller.provider,
})
// report failed transactions to Sentry
controller.txController.on(`tx:status-update`, (txId, status) => {
if (status !== 'failed') {
return
}
const txMeta = controller.txController.txStateManager.getTx(txId)
try {
reportFailedTxToSentry({ sentry, txMeta })
} catch (e) {
console.error(e)
}
})
// setup state persistence
pump(
asStream(controller.store),
debounce(1000),
storeTransform(versionifyData),
createStreamSink(persistData),
(error) => {
log.error('MetaMask - Persistence pipeline failed', error)
}
)
/**
* Assigns the given state to the versioned object (with metadata), and returns that.
* @param {Object} state - The state object as emitted by the MetaMaskController.
* @returns {VersionedData} - The state object wrapped in an object that includes a metadata key.
*/
function versionifyData (state) {
versionedData.data = state
return versionedData
}
async function persistData (state) {
if (!state) {
throw new Error('MetaMask - updated state is missing')
}
if (!state.data) {
throw new Error('MetaMask - updated state does not have data')
}
if (localStore.isSupported) {
try {
await localStore.set(state)
} catch (err) {
// log error so we dont break the pipeline
log.error('error setting state in local store:', err)
}
}
}
//
// connect to other contexts
//
extension.runtime.onConnect.addListener(connectRemote)
extension.runtime.onConnectExternal.addListener(connectExternal)
const metamaskInternalProcessHash = {
[ENVIRONMENT_TYPE_POPUP]: true,
[ENVIRONMENT_TYPE_NOTIFICATION]: true,
[ENVIRONMENT_TYPE_FULLSCREEN]: true,
}
const metamaskBlacklistedPorts = [
'trezor-connect',
]
const isClientOpenStatus = () => {
return popupIsOpen || Boolean(Object.keys(openMetamaskTabsIDs).length) || notificationIsOpen
}
/**
* A runtime.Port object, as provided by the browser:
* @see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/Port
* @typedef Port
* @type Object
*/
/**
* Connects a Port to the MetaMask controller via a multiplexed duplex stream.
* This method identifies trusted (MetaMask) interfaces, and connects them differently from untrusted (web pages).
* @param {Port} remotePort - The port provided by a new context.
*/
function connectRemote (remotePort) {
const processName = remotePort.name
const isMetaMaskInternalProcess = metamaskInternalProcessHash[processName]
if (metamaskBlacklistedPorts.includes(remotePort.name)) {
return false
}
if (isMetaMaskInternalProcess) {
const portStream = new PortStream(remotePort)
// communication with popup
controller.isClientOpen = true
controller.setupTrustedCommunication(portStream, remotePort.sender)
if (processName === ENVIRONMENT_TYPE_POPUP) {
popupIsOpen = true
endOfStream(portStream, () => {
popupIsOpen = false
controller.isClientOpen = isClientOpenStatus()
})
}
if (processName === ENVIRONMENT_TYPE_NOTIFICATION) {
notificationIsOpen = true
endOfStream(portStream, () => {
notificationIsOpen = false
controller.isClientOpen = isClientOpenStatus()
})
}
if (processName === ENVIRONMENT_TYPE_FULLSCREEN) {
const tabId = remotePort.sender.tab.id
openMetamaskTabsIDs[tabId] = true
endOfStream(portStream, () => {
delete openMetamaskTabsIDs[tabId]
controller.isClientOpen = isClientOpenStatus()
})
}
} else {
if (remotePort.sender && remotePort.sender.tab && remotePort.sender.url) {
const tabId = remotePort.sender.tab.id
const url = new URL(remotePort.sender.url)
const { origin } = url
remotePort.onMessage.addListener((msg) => {
if (msg.data && msg.data.method === 'eth_requestAccounts') {
requestAccountTabIds[origin] = tabId
}
})
}
connectExternal(remotePort)
}
}
// communication with page or other extension
function connectExternal (remotePort) {
const portStream = new PortStream(remotePort)
controller.setupUntrustedCommunication(portStream, remotePort.sender)
}
//
// User Interface setup
//
updateBadge()
controller.txController.on('update:badge', updateBadge)
controller.messageManager.on('updateBadge', updateBadge)
controller.personalMessageManager.on('updateBadge', updateBadge)
controller.decryptMessageManager.on('updateBadge', updateBadge)
controller.encryptionPublicKeyManager.on('updateBadge', updateBadge)
controller.typedMessageManager.on('updateBadge', updateBadge)
controller.permissionsController.permissions.subscribe(updateBadge)
controller.appStateController.on('updateBadge', updateBadge)
/**
* Updates the Web Extension's "badge" number, on the little fox in the toolbar.
* The number reflects the current number of pending transactions or message signatures needing user approval.
*/
function updateBadge () {
let label = ''
const unapprovedTxCount = controller.txController.getUnapprovedTxCount()
const unapprovedMsgCount = controller.messageManager.unapprovedMsgCount
const unapprovedPersonalMsgCount = controller.personalMessageManager.unapprovedPersonalMsgCount
const unapprovedDecryptMsgCount = controller.decryptMessageManager.unapprovedDecryptMsgCount
const unapprovedEncryptionPublicKeyMsgCount = controller.encryptionPublicKeyManager.unapprovedEncryptionPublicKeyMsgCount
const unapprovedTypedMessagesCount = controller.typedMessageManager.unapprovedTypedMessagesCount
const pendingPermissionRequests = Object.keys(controller.permissionsController.permissions.state.permissionsRequests).length
const waitingForUnlockCount = controller.appStateController.waitingForUnlock.length
const count = unapprovedTxCount + unapprovedMsgCount + unapprovedPersonalMsgCount + unapprovedDecryptMsgCount + unapprovedEncryptionPublicKeyMsgCount +
unapprovedTypedMessagesCount + pendingPermissionRequests + waitingForUnlockCount
if (count) {
label = String(count)
}
extension.browserAction.setBadgeText({ text: label })
extension.browserAction.setBadgeBackgroundColor({ color: '#037DD6' })
}
return Promise.resolve()
}
//
// Etc...
//
/**
* Opens the browser popup for user confirmation
*/
async function triggerUi () {
const tabs = await platform.getActiveTabs()
const currentlyActiveMetamaskTab = Boolean(tabs.find((tab) => openMetamaskTabsIDs[tab.id]))
if (!popupIsOpen && !currentlyActiveMetamaskTab) {
await notificationManager.showPopup()
}
}
/**
* Opens the browser popup for user confirmation of watchAsset
* then it waits until user interact with the UI
*/
async function openPopup () {
await triggerUi()
await new Promise(
(resolve) => {
const interval = setInterval(() => {
if (!notificationIsOpen) {
clearInterval(interval)
resolve()
}
}, 1000)
}
)
}
// On first install, open a new tab with MetaMask
extension.runtime.onInstalled.addListener(({ reason }) => {
if (reason === 'install' && !(process.env.METAMASK_DEBUG || process.env.IN_TEST)) {
platform.openExtensionInBrowser()
}
})
|
import { shallowMount } from '@vue/test-utils';
import { createStore } from '~/monitoring/stores';
import { GlLink } from '@gitlab/ui';
import { GlAreaChart, GlLineChart, GlChartSeriesLabel } from '@gitlab/ui/dist/charts';
import { shallowWrapperContainsSlotText } from 'spec/helpers/vue_test_utils_helper';
import TimeSeries from '~/monitoring/components/charts/time_series.vue';
import * as types from '~/monitoring/stores/mutation_types';
import { TEST_HOST } from 'spec/test_constants';
import MonitoringMock, { deploymentData, mockProjectPath } from '../mock_data';
describe('Time series component', () => {
const mockSha = 'mockSha';
const mockWidgets = 'mockWidgets';
const mockSvgPathContent = 'mockSvgPathContent';
const projectPath = `${TEST_HOST}${mockProjectPath}`;
const commitUrl = `${projectPath}/commit/${mockSha}`;
let mockGraphData;
let makeTimeSeriesChart;
let spriteSpy;
let store;
beforeEach(() => {
store = createStore();
store.commit(`monitoringDashboard/${types.RECEIVE_METRICS_DATA_SUCCESS}`, MonitoringMock.data);
store.commit(`monitoringDashboard/${types.RECEIVE_DEPLOYMENTS_DATA_SUCCESS}`, deploymentData);
[mockGraphData] = store.state.monitoringDashboard.groups[0].metrics;
makeTimeSeriesChart = (graphData, type) =>
shallowMount(TimeSeries, {
propsData: {
graphData: { ...graphData, type },
containerWidth: 0,
deploymentData: store.state.monitoringDashboard.deploymentData,
projectPath,
},
slots: {
default: mockWidgets,
},
sync: false,
store,
});
spriteSpy = spyOnDependency(TimeSeries, 'getSvgIconPathContent').and.callFake(
() => new Promise(resolve => resolve(mockSvgPathContent)),
);
});
describe('general functions', () => {
let timeSeriesChart;
beforeEach(() => {
timeSeriesChart = makeTimeSeriesChart(mockGraphData, 'area-chart');
});
it('renders chart title', () => {
expect(timeSeriesChart.find('.js-graph-title').text()).toBe(mockGraphData.title);
});
it('contains graph widgets from slot', () => {
expect(timeSeriesChart.find('.js-graph-widgets').text()).toBe(mockWidgets);
});
it('allows user to override max value label text using prop', () => {
timeSeriesChart.setProps({ legendMaxText: 'legendMaxText' });
expect(timeSeriesChart.props().legendMaxText).toBe('legendMaxText');
});
it('allows user to override average value label text using prop', () => {
timeSeriesChart.setProps({ legendAverageText: 'averageText' });
expect(timeSeriesChart.props().legendAverageText).toBe('averageText');
});
describe('methods', () => {
describe('formatTooltipText', () => {
const mockDate = deploymentData[0].created_at;
const mockCommitUrl = deploymentData[0].commitUrl;
const generateSeriesData = type => ({
seriesData: [
{
seriesName: timeSeriesChart.vm.chartData[0].name,
componentSubType: type,
value: [mockDate, 5.55555],
seriesIndex: 0,
},
],
value: mockDate,
});
describe('when series is of line type', () => {
beforeEach(done => {
timeSeriesChart.vm.formatTooltipText(generateSeriesData('line'));
timeSeriesChart.vm.$nextTick(done);
});
it('formats tooltip title', () => {
expect(timeSeriesChart.vm.tooltip.title).toBe('31 May 2017, 9:23PM');
});
it('formats tooltip content', () => {
const name = 'Core Usage';
const value = '5.556';
const seriesLabel = timeSeriesChart.find(GlChartSeriesLabel);
expect(seriesLabel.vm.color).toBe('');
expect(shallowWrapperContainsSlotText(seriesLabel, 'default', name)).toBe(true);
expect(timeSeriesChart.vm.tooltip.content).toEqual([{ name, value, color: undefined }]);
expect(
shallowWrapperContainsSlotText(
timeSeriesChart.find(GlAreaChart),
'tooltipContent',
value,
),
).toBe(true);
});
});
describe('when series is of scatter type', () => {
beforeEach(() => {
timeSeriesChart.vm.formatTooltipText(generateSeriesData('scatter'));
});
it('formats tooltip title', () => {
expect(timeSeriesChart.vm.tooltip.title).toBe('31 May 2017, 9:23PM');
});
it('formats tooltip sha', () => {
expect(timeSeriesChart.vm.tooltip.sha).toBe('f5bcd1d9');
});
it('formats tooltip commit url', () => {
expect(timeSeriesChart.vm.tooltip.commitUrl).toBe(mockCommitUrl);
});
});
});
describe('setSvg', () => {
const mockSvgName = 'mockSvgName';
beforeEach(done => {
timeSeriesChart.vm.setSvg(mockSvgName);
timeSeriesChart.vm.$nextTick(done);
});
it('gets svg path content', () => {
expect(spriteSpy).toHaveBeenCalledWith(mockSvgName);
});
it('sets svg path content', () => {
timeSeriesChart.vm.$nextTick(() => {
expect(timeSeriesChart.vm.svgs[mockSvgName]).toBe(`path://${mockSvgPathContent}`);
});
});
it('contains an svg object within an array to properly render icon', () => {
timeSeriesChart.vm.$nextTick(() => {
expect(timeSeriesChart.vm.chartOptions.dataZoom).toEqual([
{
handleIcon: `path://${mockSvgPathContent}`,
},
]);
});
});
});
describe('onResize', () => {
const mockWidth = 233;
beforeEach(() => {
spyOn(Element.prototype, 'getBoundingClientRect').and.callFake(() => ({
width: mockWidth,
}));
timeSeriesChart.vm.onResize();
});
it('sets area chart width', () => {
expect(timeSeriesChart.vm.width).toBe(mockWidth);
});
});
});
describe('computed', () => {
describe('chartData', () => {
let chartData;
const seriesData = () => chartData[0];
beforeEach(() => {
({ chartData } = timeSeriesChart.vm);
});
it('utilizes all data points', () => {
const { values } = mockGraphData.queries[0].result[0];
expect(chartData.length).toBe(1);
expect(seriesData().data.length).toBe(values.length);
});
it('creates valid data', () => {
const { data } = seriesData();
expect(
data.filter(
([time, value]) => new Date(time).getTime() > 0 && typeof value === 'number',
).length,
).toBe(data.length);
});
it('formats line width correctly', () => {
expect(chartData[0].lineStyle.width).toBe(2);
});
});
describe('chartOptions', () => {
describe('yAxis formatter', () => {
let format;
beforeEach(() => {
format = timeSeriesChart.vm.chartOptions.yAxis.axisLabel.formatter;
});
it('rounds to 3 decimal places', () => {
expect(format(0.88888)).toBe('0.889');
});
});
});
describe('scatterSeries', () => {
it('utilizes deployment data', () => {
expect(timeSeriesChart.vm.scatterSeries.data).toEqual([
['2017-05-31T21:23:37.881Z', 0],
['2017-05-30T20:08:04.629Z', 0],
['2017-05-30T17:42:38.409Z', 0],
]);
expect(timeSeriesChart.vm.scatterSeries.symbolSize).toBe(14);
});
});
describe('yAxisLabel', () => {
it('constructs a label for the chart y-axis', () => {
expect(timeSeriesChart.vm.yAxisLabel).toBe('CPU');
});
});
});
afterEach(() => {
timeSeriesChart.destroy();
});
});
describe('wrapped components', () => {
const glChartComponents = [
{
chartType: 'area-chart',
component: GlAreaChart,
},
{
chartType: 'line-chart',
component: GlLineChart,
},
];
glChartComponents.forEach(dynamicComponent => {
describe(`GitLab UI: ${dynamicComponent.chartType}`, () => {
let timeSeriesAreaChart;
let glChart;
beforeEach(done => {
timeSeriesAreaChart = makeTimeSeriesChart(mockGraphData, dynamicComponent.chartType);
glChart = timeSeriesAreaChart.find(dynamicComponent.component);
timeSeriesAreaChart.vm.$nextTick(done);
});
it('is a Vue instance', () => {
expect(glChart.exists()).toBe(true);
expect(glChart.isVueInstance()).toBe(true);
});
it('receives data properties needed for proper chart render', () => {
const props = glChart.props();
expect(props.data).toBe(timeSeriesAreaChart.vm.chartData);
expect(props.option).toBe(timeSeriesAreaChart.vm.chartOptions);
expect(props.formatTooltipText).toBe(timeSeriesAreaChart.vm.formatTooltipText);
expect(props.thresholds).toBe(timeSeriesAreaChart.vm.thresholds);
});
it('recieves a tooltip title', done => {
const mockTitle = 'mockTitle';
timeSeriesAreaChart.vm.tooltip.title = mockTitle;
timeSeriesAreaChart.vm.$nextTick(() => {
expect(shallowWrapperContainsSlotText(glChart, 'tooltipTitle', mockTitle)).toBe(true);
done();
});
});
describe('when tooltip is showing deployment data', () => {
beforeEach(done => {
timeSeriesAreaChart.vm.tooltip.isDeployment = true;
timeSeriesAreaChart.vm.$nextTick(done);
});
it('uses deployment title', () => {
expect(shallowWrapperContainsSlotText(glChart, 'tooltipTitle', 'Deployed')).toBe(true);
});
it('renders clickable commit sha in tooltip content', done => {
timeSeriesAreaChart.vm.tooltip.sha = mockSha;
timeSeriesAreaChart.vm.tooltip.commitUrl = commitUrl;
timeSeriesAreaChart.vm.$nextTick(() => {
const commitLink = timeSeriesAreaChart.find(GlLink);
expect(shallowWrapperContainsSlotText(commitLink, 'default', mockSha)).toBe(true);
expect(commitLink.attributes('href')).toEqual(commitUrl);
done();
});
});
});
});
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.catchExitSignals = exports.prematureEnd = void 0;
var _signalExit = _interopRequireDefault(require("signal-exit"));
var _redux = require("./redux");
var _actions = require("./redux/actions");
var _constants = require("./constants");
var _reporter = require("./reporter");
/*
* This module is used to catch if the user kills the gatsby process via cmd+c
* When this happens, there is some clean up logic we need to fire offf
*/
const interruptActivities = () => {
const {
activities
} = (0, _redux.getStore)().getState().logs;
Object.keys(activities).forEach(activityId => {
const activity = activities[activityId];
if (activity.status === _constants.ActivityStatuses.InProgress || activity.status === _constants.ActivityStatuses.NotStarted) {
_reporter.reporter.completeActivity(activityId, _constants.ActivityStatuses.Interrupted);
}
});
};
const prematureEnd = () => {
// hack so at least one activity is surely failed, so
// we are guaranteed to generate FAILED status
// if none of activity did explicitly fail
(0, _actions.createPendingActivity)({
id: `panic`,
status: _constants.ActivityStatuses.Failed
});
interruptActivities();
};
exports.prematureEnd = prematureEnd;
const catchExitSignals = () => {
(0, _signalExit.default)((code, signal) => {
if (code !== 0 && signal !== `SIGINT` && signal !== `SIGTERM`) prematureEnd();else interruptActivities();
});
};
exports.catchExitSignals = catchExitSignals; |
angular.module('Angello.Dashboard')
.controller('DashboardCtrl',
function (StoriesModel, STORY_STATUSES, STORY_TYPES, $log) {
var dashboard = this;
dashboard.types = STORY_TYPES;
dashboard.statuses = STORY_STATUSES;
dashboard.stories = [];
StoriesModel.all()
.then(function (stories) {
var arr = [];
for (var key in stories) {
arr.push(stories[key]);
$log.debug("第" + key + "个元素为:" ,stories[key]);
}
dashboard.stories = arr;
});
});
|
const { PORT, NODE_ENV } = require('../conf/sys-config');
process.env.NODE_ENV = NODE_ENV;
const http = require('http');
const app = require('../app');
const logger = require('../utils/logger');
const fs = require('fs');
const path = require('path');
const { RTError, _P, mime, axios } = require('../utils/node');
const CONFIG_FILE_PATHS = [path.resolve('/', 'etc/op-config.json'), path.resolve(__dirname, '../conf/op-config.json')];
async function readConfig() {
for (const path of CONFIG_FILE_PATHS) {
if (fs.existsSync(path)) {
logger.log('read config from:' + path);
return JSON.parse(fs.readFileSync(path, 'utf8'));
}
}
throw new Error('configuration file not find');
}
async function writeConfig(config) {
const config_file_path = config.starter.x_node_config_path;
if (!CONFIG_FILE_PATHS.includes(config_file_path)) {
throw new Error('config-file-path is invalid: ' + config_file_path);
}
for (const path of CONFIG_FILE_PATHS) {
if (config_file_path === path) {
break;
}
if (fs.existsSync(path)) {
fs.unlinkSync(path);
}
}
fs.writeFileSync(config_file_path, JSON.stringify(config, null, 2));
}
async function downloadForProxy({ url, headers, body, method }, reqHeaders, resHeaders) {
const reqHttpRange = reqHeaders.range;
if (url.startsWith('file://')) {
const p = url.slice('file://'.length);
const stats = fs.statSync(p);
if (!stats.isFile()) {
throw new RTError(403, 'NotDownloadable', { name: path.basename(p) });
}
const size = stats.size;
const h = resHeaders;
h['content-type'] = mime.get(p);
h['accept-ranges'] = 'bytes';
h['content-disposition'] = 'attachment; filename=' + encodeURIComponent(path.basename(p));
if (reqHttpRange) {
const m = /bytes=(?<start>\d*)-(?<end>\d*)/.exec(reqHttpRange) || { groups: {} };
const start = Number(m.groups.start) || 0;
const end = Number(m.groups.start) || size - 1;
if (!(start <= end && end < size)) {
throw new RTError(403, 'InvalidHttpRange', { range: reqHttpRange, size });
}
h['content-length'] = end - start + 1;
h['content-range'] = `bytes ${start}-${end}/${size}`;
return [206, h, fs.createReadStream(p, { start, end })];
} else {
h['content-length'] = size;
return [200, h, fs.createReadStream(p)];
}
} else if (url.startsWith('http')) {
['accept', 'accept-encoding', 'range'].forEach((k) => {
if (reqHeaders[k]) {
headers[k] = reqHeaders[k];
}
});
return axios
.request({
method,
data: body,
headers,
url,
responseType: 'stream',
})
.then(({ status, data, headers }) => {
['content-type', 'content-disposition', 'content-length', 'content-range', 'content-encoding'].forEach((k) => {
if (headers[k]) {
resHeaders[k] = headers[k];
}
});
return [status, resHeaders, data];
});
} else {
throw new RTError(403, 'InvalidDownloadUrl');
}
}
app.initialize({
name: 'node-http',
readConfig,
writeConfig,
params: [_P('x_node_config_path', CONFIG_FILE_PATHS[1], '配置文件存放位置', 8, CONFIG_FILE_PATHS, false, true)],
});
const server = http
.createServer((req, res) => {
const s = process.hrtime.bigint();
new Promise((resolve) => {
const request = {
method: req.method,
path: req.url,
headers: req.headers,
body: '',
query: req.url,
ip: [req.connection.remoteAddress],
};
if (req.method === 'PUT') {
request.stream = req;
resolve(request);
} else {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
request.body = body;
resolve(request);
});
}
})
.then(async (request) => {
const response = await app.handleRequest(request);
if (response.callback_down) {
const r = await downloadForProxy(response.callback_down, req.headers, response.headers);
res.writeHead(r[0], r[1]);
r[2].pipe(res);
} else {
res.writeHead(response.status, response.headers);
res.end(response.body);
}
logger.debug(`time consume:${Number(process.hrtime.bigint() - s) / 1000000}`);
})
.catch((err) => {
res.writeHead(err.status || 500, {
'access-control-allow-origin': '*',
'content-type': 'application/json',
});
res.end(JSON.stringify({ error: err.type || 'UnknownError', data: err.data || {}, msg: err.message }));
});
})
.listen(PORT);
if (server.address()) {
logger.log(`Running on ${process.platform}, port:${server.address().port}`);
Object.values(require('os').networkInterfaces())
.map((e) => (e[0].family === 'IPv6' ? e[1].address : e[0].address))
.filter((e) => e)
.sort()
.forEach((e) => logger.log(`http://${e}:${PORT}`));
}
|
/**
*
* Copyright (c) 2020 Silicon Labs
*
* 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.
*
*
* @jest-environment node
*/
const path = require('path')
const genEngine = require('../src-electron/generator/generation-engine.js')
const env = require('../src-electron/util/env.ts')
const dbApi = require('../src-electron/db/db-api.js')
const zclLoader = require('../src-electron/zcl/zcl-loader.js')
const importJs = require('../src-electron/importexport/import.js')
const testUtil = require('./test-util.js')
const queryEndpoint = require('../src-electron/db/query-endpoint.js')
const queryEndpointType = require('../src-electron/db/query-endpoint-type.js')
const queryConfig = require('../src-electron/db/query-config.js')
const queryPackage = require('../src-electron/db/query-package.js')
const types = require('../src-electron/util/types.js')
const bin = require('../src-electron/util/bin.ts')
let db
const templateCount = testUtil.testTemplate.zigbeeCount
const testFile = path.join(__dirname, 'resource/three-endpoint-device.zap')
let sessionId
let templateContext
let zclContext
beforeAll(async () => {
env.setDevelopmentEnv()
let file = env.sqliteTestFile('endpointconfig')
db = await dbApi.initDatabaseAndLoadSchema(
file,
env.schemaFile(),
env.zapVersion()
)
}, testUtil.timeout.medium())
afterAll(() => dbApi.closeDatabase(db), testUtil.timeout.short())
test(
'Basic gen template parsing and generation',
async () => {
templateContext = await genEngine.loadTemplates(
db,
testUtil.testTemplate.zigbee
)
expect(templateContext.crc).not.toBeNull()
expect(templateContext.templateData).not.toBeNull()
expect(templateContext.templateData.name).toEqual('Test templates')
expect(templateContext.templateData.version).toEqual('test-v1')
expect(templateContext.templateData.templates.length).toEqual(templateCount)
expect(templateContext.packageId).not.toBeNull()
},
testUtil.timeout.medium()
)
test(
'Load ZCL stuff',
async () => {
zclContext = await zclLoader.loadZcl(db, env.builtinSilabsZclMetafile())
},
testUtil.timeout.medium()
)
test(
'Test file import',
async () => {
let importResult = await importJs.importDataFromFile(db, testFile);
sessionId = importResult.sessionId
expect(sessionId).not.toBeNull()
await queryPackage.insertSessionPackage(db, sessionId, zclContext.packageId);
},
testUtil.timeout.medium()
)
test(
'Test endpoint config queries',
() =>
queryEndpointType
.selectAllEndpointTypes(db, sessionId)
.then((epts) => {
expect(epts.length).toBe(3)
return epts
})
.then((epts) => {
let ps = []
epts.forEach((ept) => {
ps.push(queryEndpoint.selectEndpointClusters(db, ept.id))
})
return Promise.all(ps)
})
.then((clusterArray) => {
expect(clusterArray.length).toBe(3)
expect(clusterArray[0].length).toBe(28)
expect(clusterArray[1].length).toBe(5)
expect(clusterArray[2].length).toBe(7)
let promiseAttributes = []
let promiseCommands = []
clusterArray.forEach((clusters) => {
clusters.forEach((cluster) => {
promiseAttributes.push(
queryEndpoint.selectEndpointClusterAttributes(
db,
cluster.clusterId,
cluster.side,
cluster.endpointTypeId
)
)
promiseCommands.push(
queryEndpoint.selectEndpointClusterCommands(
db,
cluster.clusterId,
cluster.endpointTypeId
)
)
})
})
return Promise.all([
Promise.all(promiseAttributes),
Promise.all(promiseCommands),
])
})
.then((twoLists) => {
let attributeLists = twoLists[0]
let commandLists = twoLists[1]
expect(attributeLists.length).toBe(40)
expect(commandLists.length).toBe(40)
let atSums = {}
attributeLists.forEach((al) => {
let l = al.length
if (atSums[l]) {
atSums[l]++
} else {
atSums[l] = 1
}
})
expect(atSums[0]).toBe(18)
let cmdSums = {}
commandLists.forEach((cl) => {
let l = cl.length
if (cmdSums[l]) {
cmdSums[l]++
} else {
cmdSums[l] = 1
}
})
expect(cmdSums[0]).toBe(15)
}),
testUtil.timeout.medium()
)
test(
'Some intermediate queries',
async () => {
let size = await types.typeSize(db, zclContext.packageId, 'bitmap8')
expect(size).toBe(1)
},
testUtil.timeout.medium()
)
test(
'Test endpoint config generation',
async () => {
let genResult = await genEngine.generate(
db,
sessionId,
templateContext.packageId,
{},
{ disableDeprecationWarnings: true }
)
expect(genResult).not.toBeNull()
expect(genResult.partial).toBeFalsy()
expect(genResult.content).not.toBeNull()
if (genResult.hasErrors) {
console.log(genResult.errors)
}
expect(genResult.hasErrors).toBeFalsy();
let epc = genResult.content['zap-config.h']
let epcLines = epc.split(/\r?\n/)
expect(epc).toContain(
'#define FIXED_ENDPOINT_ARRAY { 0x0029, 0x002A, 0x002B }'
)
expect(epc).toContain(
"17, 'V', 'e', 'r', 'y', ' ', 'l', 'o', 'n', 'g', ' ', 'u', 's', 'e', 'r', ' ', 'i', 'd',"
)
expect(epc).toContain(
'{ ZAP_REPORT_DIRECTION(REPORTED), 0x0029, 0x0101, 0x0000, ZAP_CLUSTER_MASK(SERVER), 0x0000, {{ 0, 65534, 0 }} }, /* lock state */'
)
expect(epc).toContain(
'{ 0x0004, ZAP_TYPE(CHAR_STRING), 33, ZAP_ATTRIBUTE_MASK(TOKENIZE), ZAP_LONG_DEFAULTS_INDEX(0) }'
)
expect(epc.includes(bin.hexToCBytes(bin.stringToHex('Very long user id'))))
expect(epc).toContain('#define FIXED_NETWORKS { 1, 1, 2 }')
expect(epc).toContain(
'#define FIXED_PROFILE_IDS { 0x0107, 0x0104, 0x0104 }'
)
expect(epc).toContain('#define FIXED_ENDPOINT_TYPES { 0, 1, 2 }')
expect(epc).toContain('#define GENERATED_DEFAULTS_COUNT (12)')
expect(epc).toContain(
'{ ZAP_REPORT_DIRECTION(REPORTED), 0x002A, 0x0701, 0x0002, ZAP_CLUSTER_MASK(CLIENT), 0x0000, {{ 2, 12, 4 }} }'
)
expect(epc).toContain(
'{ ZAP_REPORT_DIRECTION(REPORTED), 0x002A, 0x0701, 0x0003, ZAP_CLUSTER_MASK(CLIENT), 0x0000, {{ 3, 13, 6 }} }'
)
expect(epc).toContain(
`17, 'T', 'e', 's', 't', ' ', 'm', 'a', 'n', 'u', 'f', 'a', 'c', 't', 'u', 'r', 'e', 'r',`
)
expect(epcLines.length).toBeGreaterThan(100)
let cnt = 0
epcLines.forEach((line) => {
if (line.includes('ZAP_TYPE(')) {
expect(line.includes('undefined')).toBeFalsy()
cnt++
}
})
expect(cnt).toBe(76)
expect(epc).toContain('#define EMBER_AF_MANUFACTURER_CODE 0x1002')
expect(epc).toContain('#define EMBER_AF_DEFAULT_RESPONSE_POLICY_ALWAYS')
},
testUtil.timeout.long()
)
|
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class WhatsAppIntegrationEntityListing(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
WhatsAppIntegrationEntityListing - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'entities': 'list[WhatsAppIntegration]',
'page_size': 'int',
'page_number': 'int',
'total': 'int',
'first_uri': 'str',
'self_uri': 'str',
'next_uri': 'str',
'last_uri': 'str',
'previous_uri': 'str',
'page_count': 'int'
}
self.attribute_map = {
'entities': 'entities',
'page_size': 'pageSize',
'page_number': 'pageNumber',
'total': 'total',
'first_uri': 'firstUri',
'self_uri': 'selfUri',
'next_uri': 'nextUri',
'last_uri': 'lastUri',
'previous_uri': 'previousUri',
'page_count': 'pageCount'
}
self._entities = None
self._page_size = None
self._page_number = None
self._total = None
self._first_uri = None
self._self_uri = None
self._next_uri = None
self._last_uri = None
self._previous_uri = None
self._page_count = None
@property
def entities(self):
"""
Gets the entities of this WhatsAppIntegrationEntityListing.
:return: The entities of this WhatsAppIntegrationEntityListing.
:rtype: list[WhatsAppIntegration]
"""
return self._entities
@entities.setter
def entities(self, entities):
"""
Sets the entities of this WhatsAppIntegrationEntityListing.
:param entities: The entities of this WhatsAppIntegrationEntityListing.
:type: list[WhatsAppIntegration]
"""
self._entities = entities
@property
def page_size(self):
"""
Gets the page_size of this WhatsAppIntegrationEntityListing.
:return: The page_size of this WhatsAppIntegrationEntityListing.
:rtype: int
"""
return self._page_size
@page_size.setter
def page_size(self, page_size):
"""
Sets the page_size of this WhatsAppIntegrationEntityListing.
:param page_size: The page_size of this WhatsAppIntegrationEntityListing.
:type: int
"""
self._page_size = page_size
@property
def page_number(self):
"""
Gets the page_number of this WhatsAppIntegrationEntityListing.
:return: The page_number of this WhatsAppIntegrationEntityListing.
:rtype: int
"""
return self._page_number
@page_number.setter
def page_number(self, page_number):
"""
Sets the page_number of this WhatsAppIntegrationEntityListing.
:param page_number: The page_number of this WhatsAppIntegrationEntityListing.
:type: int
"""
self._page_number = page_number
@property
def total(self):
"""
Gets the total of this WhatsAppIntegrationEntityListing.
:return: The total of this WhatsAppIntegrationEntityListing.
:rtype: int
"""
return self._total
@total.setter
def total(self, total):
"""
Sets the total of this WhatsAppIntegrationEntityListing.
:param total: The total of this WhatsAppIntegrationEntityListing.
:type: int
"""
self._total = total
@property
def first_uri(self):
"""
Gets the first_uri of this WhatsAppIntegrationEntityListing.
:return: The first_uri of this WhatsAppIntegrationEntityListing.
:rtype: str
"""
return self._first_uri
@first_uri.setter
def first_uri(self, first_uri):
"""
Sets the first_uri of this WhatsAppIntegrationEntityListing.
:param first_uri: The first_uri of this WhatsAppIntegrationEntityListing.
:type: str
"""
self._first_uri = first_uri
@property
def self_uri(self):
"""
Gets the self_uri of this WhatsAppIntegrationEntityListing.
:return: The self_uri of this WhatsAppIntegrationEntityListing.
:rtype: str
"""
return self._self_uri
@self_uri.setter
def self_uri(self, self_uri):
"""
Sets the self_uri of this WhatsAppIntegrationEntityListing.
:param self_uri: The self_uri of this WhatsAppIntegrationEntityListing.
:type: str
"""
self._self_uri = self_uri
@property
def next_uri(self):
"""
Gets the next_uri of this WhatsAppIntegrationEntityListing.
:return: The next_uri of this WhatsAppIntegrationEntityListing.
:rtype: str
"""
return self._next_uri
@next_uri.setter
def next_uri(self, next_uri):
"""
Sets the next_uri of this WhatsAppIntegrationEntityListing.
:param next_uri: The next_uri of this WhatsAppIntegrationEntityListing.
:type: str
"""
self._next_uri = next_uri
@property
def last_uri(self):
"""
Gets the last_uri of this WhatsAppIntegrationEntityListing.
:return: The last_uri of this WhatsAppIntegrationEntityListing.
:rtype: str
"""
return self._last_uri
@last_uri.setter
def last_uri(self, last_uri):
"""
Sets the last_uri of this WhatsAppIntegrationEntityListing.
:param last_uri: The last_uri of this WhatsAppIntegrationEntityListing.
:type: str
"""
self._last_uri = last_uri
@property
def previous_uri(self):
"""
Gets the previous_uri of this WhatsAppIntegrationEntityListing.
:return: The previous_uri of this WhatsAppIntegrationEntityListing.
:rtype: str
"""
return self._previous_uri
@previous_uri.setter
def previous_uri(self, previous_uri):
"""
Sets the previous_uri of this WhatsAppIntegrationEntityListing.
:param previous_uri: The previous_uri of this WhatsAppIntegrationEntityListing.
:type: str
"""
self._previous_uri = previous_uri
@property
def page_count(self):
"""
Gets the page_count of this WhatsAppIntegrationEntityListing.
:return: The page_count of this WhatsAppIntegrationEntityListing.
:rtype: int
"""
return self._page_count
@page_count.setter
def page_count(self, page_count):
"""
Sets the page_count of this WhatsAppIntegrationEntityListing.
:param page_count: The page_count of this WhatsAppIntegrationEntityListing.
:type: int
"""
self._page_count = page_count
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
"""
Returns the model as raw JSON
"""
return json.dumps(sanitize_for_serialization(self.to_dict()))
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
AJS.test.require(["jira.webresources:dialogs"], function () {
require([
'jira/dialog/error-dialog',
'jira/util/browser',
'jquery',
'underscore'
], function(
ErrorDialog,
Browser,
$,
_
) {
var ErrorDialogDriver = function () {};
_.extend(ErrorDialogDriver.prototype, {
isVisible: function () {
return this.el().is(":visible");
},
message: function() {
return $.trim(this.el().find(".aui-message").text());
},
refresh: function () {
var $refresh = this.el().find(".error-dialog-refresh");
if (!$refresh.length) {
throw "Could not find refresh button.";
} else {
$refresh.click();
}
},
el: function () {
return $("#error-dialog");
},
mode: function () {
var msg = this.el().find(".aui-message");
if (msg.length) {
if (msg.hasClass("warning")) {
return "warning";
} else if (msg.hasClass("info")) {
return "info";
} else if (msg.hasClass("error")) {
return "error";
}
}
return null;
}
});
module("JIRA.ErrorDialog", {
setup: function () {
this.driver = new ErrorDialogDriver();
this.sandbox = sinon.sandbox.create();
},
teardown: function () {
this.sandbox.restore();
}
});
var testMode = function (mode, message) {
var options = {
message : message
};
if (mode) {
options.mode = mode;
}
var dialog = new ErrorDialog(options);
dialog.show();
equal(this.driver.message(), message, "Dialog displaying correct error message.");
equal(this.driver.mode(), mode || "error", "Dialog displaying in correct mode.");
dialog.hide();
};
test("Dialog displays correct error message when no mode passed.", function () {
testMode.call(this, null, "Error");
});
test("Dialog displays correct message in info mode", function () {
testMode.call(this, "info", "Info");
});
test("Dialog displays correct message in warning mode", function () {
testMode.call(this, "warning", "Warning");
});
test("Dialog displays correct message in error mode", function () {
testMode.call(this, "warning", "Error");
});
test("Dialog displays correct message for bad mode", function () {
var message = "Message";
var dialog = new ErrorDialog({
message: message,
mode: "badMode"
});
dialog.show();
equal(this.driver.message(), message, "Dialog displaying correct error message.");
equal(this.driver.mode(), "error", "Dialog displaying in correct mode.");
dialog.hide();
});
test("Dialog hide/show.", function () {
var message = "Error";
var dialog = new ErrorDialog({
message : message
});
ok(!this.driver.isVisible(), "Dialog should be hidden by default.");
dialog.show();
ok(this.driver.isVisible(), "Dialog should now be visible.");
dialog.hide();
ok(!this.driver.isVisible(), "Dialog should be hidden again.");
});
test("openErrorDialogForXHR displays error dialog.", function () {
var dialog = ErrorDialog.openErrorDialogForXHR({
status: 401,
responseText: JSON.stringify({errorMessages: ["abc"]})
});
dialog.show();
equal(this.driver.message(), "abc", "Dialog displaying correct error message.");
dialog.hide();
});
test("refresh does page reload.", function () {
var reloader = this.sandbox.stub(Browser, "reloadViaWindowLocation");
var dialog = ErrorDialog.openErrorDialogForXHR({
status: 401,
responseText: JSON.stringify({errorMessages: ["abc"]})
}).show();
this.driver.refresh();
ok(reloader.calledOnce, "Refresh does a page pop.");
dialog.hide();
});
});
});
|
import template from './sw-cms-detail.html.twig';
import CMS from '../../constant/sw-cms.constant';
import './sw-cms-detail.scss';
const { Component, Mixin } = Shopware;
const { debounce } = Shopware.Utils;
const { cloneDeep, getObjectDiff } = Shopware.Utils.object;
const { warn } = Shopware.Utils.debug;
const Criteria = Shopware.Data.Criteria;
const debounceTimeout = 800;
Component.register('sw-cms-detail', {
template,
inject: [
'repositoryFactory',
'entityFactory',
'entityHydrator',
'loginService',
'cmsService',
'cmsDataResolverService',
'acl',
'appCmsService',
],
mixins: [
Mixin.getByName('cms-state'),
Mixin.getByName('notification'),
Mixin.getByName('placeholder'),
],
shortcuts: {
'SYSTEMKEY+S': 'onSave',
},
data() {
return {
pageId: null,
pageOrigin: null,
page: {
sections: [],
},
salesChannels: [],
isLoading: false,
isSaveSuccessful: false,
isSaveable: false,
currentSalesChannelKey: null,
selectedBlockSectionId: null,
currentMappingEntity: null,
currentMappingEntityRepo: null,
demoEntityId: null,
productDetailBlocks: [
{
type: 'cross-selling',
elements: [
{
slot: 'content',
type: 'cross-selling',
config: {},
},
],
},
{
type: 'product-description-reviews',
elements: [
{
slot: 'content',
type: 'product-description-reviews',
config: {},
},
],
},
{
type: 'gallery-buybox',
elements: [
{
slot: 'left',
type: 'image-gallery',
config: {},
},
{
slot: 'right',
type: 'buy-box',
config: {},
},
],
},
{
type: 'product-heading',
elements: [
{
slot: 'left',
type: 'product-name',
config: {},
},
{
slot: 'right',
type: 'manufacturer-logo',
config: {},
},
],
},
],
showLayoutAssignmentModal: false,
showMissingElementModal: false,
missingElements: [],
/** @deprecated tag:v6.5.0 data prop can be removed completely */
previousRoute: '',
};
},
metaInfo() {
return {
title: this.$createTitle(this.identifier),
};
},
/** @deprecated tag:v6.5.0 navigation guard can be removed completely */
beforeRouteEnter(to, from, next) {
next((vm) => {
vm.previousRoute = from.name;
});
},
computed: {
identifier() {
return this.placeholder(this.page, 'name');
},
pageRepository() {
return this.repositoryFactory.create('cms_page');
},
sectionRepository() {
return this.repositoryFactory.create('cms_section');
},
blockRepository() {
return this.repositoryFactory.create('cms_block');
},
slotRepository() {
return this.repositoryFactory.create('cms_slot');
},
salesChannelRepository() {
return this.repositoryFactory.create('sales_channel');
},
defaultFolderRepository() {
return this.repositoryFactory.create('media_default_folder');
},
cmsBlocks() {
return this.cmsService.getCmsBlockRegistry();
},
cmsStageClasses() {
return [
`is--${this.currentDeviceView}`,
];
},
cmsTypeMappingEntities() {
return {
product_detail: {
entity: 'product',
mode: 'single',
},
product_list: {
entity: 'category',
mode: 'single',
},
};
},
cmsPageTypes() {
return {
page: this.$tc('sw-cms.detail.label.pageTypeShopPage'),
landingpage: this.$tc('sw-cms.detail.label.pageTypeLandingpage'),
product_list: this.$tc('sw-cms.detail.label.pageTypeCategory'),
product_detail: this.$tc('sw-cms.detail.label.pageTypeProduct'),
};
},
cmsPageTypeSettings() {
if (this.cmsTypeMappingEntities[this.page.type]) {
return this.cmsTypeMappingEntities[this.page.type];
}
return {
entity: null,
mode: 'static',
};
},
blockConfigDefaults() {
return {
name: null,
marginBottom: null,
marginTop: null,
marginLeft: null,
marginRight: null,
sizingMode: 'boxed',
};
},
tooltipSave() {
if (!this.acl.can('cms.editor')) {
return {
message: this.$tc('sw-privileges.tooltip.warning'),
disabled: this.acl.can('cms.editor'),
showOnDisabledElements: true,
};
}
const systemKey = this.$device.getSystemKey();
return {
message: `${systemKey} + S`,
appearance: 'light',
};
},
addBlockTitle() {
if (!this.isSystemDefaultLanguage) {
return this.$tc('sw-cms.general.disabledAddingBlocksToolTip');
}
return this.$tc('sw-cms.detail.sidebar.titleBlockOverview');
},
pageHasSections() {
return this.page.sections.length > 0;
},
loadPageCriteria() {
const criteria = new Criteria(1, 1);
const sortCriteria = Criteria.sort('position', 'ASC', true);
criteria
.addAssociation('categories')
.addAssociation('landingPages')
.addAssociation('products.manufacturer')
.getAssociation('sections')
.addSorting(sortCriteria)
.addAssociation('backgroundMedia')
.getAssociation('blocks')
.addSorting(sortCriteria)
.addAssociation('backgroundMedia')
.addAssociation('slots');
return criteria;
},
currentDeviceView() {
return this.cmsPageState.currentCmsDeviceView;
},
demoProductCriteria() {
const criteria = new Criteria();
criteria.addAssociation('media');
criteria.addAssociation('deliveryTime');
criteria.addAssociation('manufacturer.media');
return criteria;
},
isProductPage() {
return this.page.type === CMS.PAGE_TYPES.PRODUCT_DETAIL;
},
},
created() {
this.createdComponent();
},
beforeDestroy() {
this.beforeDestroyedComponent();
},
methods: {
createdComponent() {
Shopware.State.commit('adminMenu/collapseSidebar');
const isSystemDefaultLanguage = Shopware.State.getters['context/isSystemDefaultLanguage'];
this.$store.commit('cmsPageState/setIsSystemDefaultLanguage', isSystemDefaultLanguage);
this.resetCmsPageState();
if (this.$route.params.id) {
this.pageId = this.$route.params.id;
this.isLoading = true;
const defaultStorefrontId = '8A243080F92E4C719546314B577CF82B';
const criteria = new Criteria();
criteria.addFilter(
Criteria.equals('typeId', defaultStorefrontId),
);
this.salesChannelRepository.search(criteria).then((response) => {
this.salesChannels = response;
if (this.salesChannels.length > 0) {
this.currentSalesChannelKey = this.salesChannels[0].id;
this.loadPage(this.pageId);
}
});
}
this.setPageContext();
},
setPageContext() {
this.getDefaultFolderId().then((folderId) => {
Shopware.State.commit('cmsPageState/setDefaultMediaFolderId', folderId);
});
},
resetCmsPageState() {
Shopware.State.dispatch('cmsPageState/resetCmsPageState');
},
getDefaultFolderId() {
const criteria = new Criteria(1, 1);
criteria.addAssociation('folder');
criteria.addFilter(Criteria.equals('entity', this.cmsPageState.pageEntityName));
return this.defaultFolderRepository.search(criteria).then((searchResult) => {
const defaultFolder = searchResult.first();
if (defaultFolder.folder?.id) {
return defaultFolder.folder.id;
}
return null;
});
},
beforeDestroyedComponent() {
Shopware.State.commit('cmsPageState/removeCurrentPage');
Shopware.State.commit('cmsPageState/removeSelectedBlock');
Shopware.State.commit('cmsPageState/removeSelectedSection');
},
onBlockNavigatorSort(isCrossSectionMove = false) {
if (isCrossSectionMove) {
this.loadPage(this.pageId);
return;
}
this.onPageUpdate();
this.debouncedPageSave();
},
loadPage(pageId) {
this.isLoading = true;
this.pageRepository.get(pageId, Shopware.Context.api, this.loadPageCriteria).then((page) => {
this.page = { sections: [] };
this.page = page;
this.cmsDataResolverService.resolve(this.page).then(() => {
this.updateSectionAndBlockPositions();
Shopware.State.commit('cmsPageState/setCurrentPage', this.page);
this.updateDataMapping();
this.pageOrigin = cloneDeep(this.page);
if (this.selectedBlock) {
const blockId = this.selectedBlock.id;
const blockSectionId = this.selectedBlock.sectionId;
this.page.sections.forEach((section) => {
if (section.id === blockSectionId) {
section.blocks.forEach((block) => {
if (block.id === blockId) {
this.setSelectedBlock(blockSectionId, block);
}
});
}
});
}
this.isLoading = false;
}).catch((exception) => {
this.isLoading = false;
this.createNotificationError({
title: exception.message,
message: exception.response,
});
warn(this._name, exception.message, exception.response);
});
}).catch((exception) => {
this.isLoading = false;
this.createNotificationError({
title: exception.message,
message: exception.response.statusText,
});
warn(this._name, exception.message, exception.response);
});
},
updateDataMapping() {
const mappingEntity = this.cmsPageTypeSettings.entity;
if (!mappingEntity) {
Shopware.State.commit('cmsPageState/removeCurrentMappingEntity');
Shopware.State.commit('cmsPageState/removeCurrentMappingTypes');
Shopware.State.commit('cmsPageState/removeCurrentDemoEntity');
this.currentMappingEntity = null;
this.currentMappingEntityRepo = null;
this.demoEntityId = null;
return;
}
if (this.cmsPageState.currentMappingEntity !== mappingEntity) {
Shopware.State.commit('cmsPageState/setCurrentMappingEntity', mappingEntity);
Shopware.State.commit(
'cmsPageState/setCurrentMappingTypes',
this.cmsService.getEntityMappingTypes(mappingEntity),
);
this.currentMappingEntity = mappingEntity;
this.currentMappingEntityRepo = this.repositoryFactory.create(mappingEntity);
this.loadFirstDemoEntity();
}
},
loadFirstDemoEntity() {
if (this.cmsPageState.currentMappingEntity === 'product') {
return;
}
const criteria = new Criteria();
if (this.cmsPageState.currentMappingEntity === 'category') {
criteria.addAssociation('media');
}
this.currentMappingEntityRepo.search(criteria).then((response) => {
this.demoEntityId = response[0].id;
Shopware.State.commit('cmsPageState/setCurrentDemoEntity', response[0]);
});
},
onDeviceViewChange(view) {
if (view === 'form' && !this.acl.can('cms.editor')) {
return;
}
Shopware.State.commit('cmsPageState/setCurrentCmsDeviceView', view);
if (view === 'form') {
this.setSelectedBlock(null, null);
}
},
setSelectedBlock(sectionId, block = null) {
this.selectedBlockSectionId = sectionId;
this.$store.dispatch('cmsPageState/setBlock', block);
},
onChangeLanguage() {
this.isLoading = true;
return this.salesChannelRepository.search(new Criteria()).then((response) => {
this.salesChannels = response;
const isSystemDefaultLanguage = Shopware.State.getters['context/isSystemDefaultLanguage'];
this.$store.commit('cmsPageState/setIsSystemDefaultLanguage', isSystemDefaultLanguage);
return this.loadPage(this.pageId);
});
},
abortOnLanguageChange() {
return Object.keys(getObjectDiff(this.page, this.pageOrigin)).length > 0;
},
saveOnLanguageChange() {
return this.onSave();
},
onDemoEntityChange(demoEntityId) {
Shopware.State.commit('cmsPageState/removeCurrentDemoEntity');
if (!demoEntityId) {
return;
}
const demoContext = this.cmsPageState.currentMappingEntity === 'product'
? { ...Shopware.Context.api, inheritance: true }
: Shopware.Context.api;
const demoCriteria = this.cmsPageState.currentMappingEntity === 'product'
? this.demoProductCriteria : new Criteria();
this.currentMappingEntityRepo.get(demoEntityId, demoContext, demoCriteria).then((entity) => {
if (!entity) {
return;
}
if (this.cmsPageState.currentMappingEntity === 'category' && entity.mediaId !== null) {
this.repositoryFactory.create('media').get(entity.mediaId).then((media) => {
entity.media = media;
Shopware.State.commit('cmsPageState/setCurrentDemoEntity', entity);
});
} else {
Shopware.State.commit('cmsPageState/setCurrentDemoEntity', entity);
}
});
},
addFirstSection(type, index) {
this.onAddSection(type, index);
},
addAdditionalSection(type, index) {
this.onAddSection(type, index);
this.onSave();
},
onAddSection(type, index) {
if (!type || index === 'undefined') {
return;
}
const section = this.sectionRepository.create();
section.type = type;
section.sizingMode = 'boxed';
section.position = index;
section.pageId = this.page.id;
this.page.sections.splice(index, 0, section);
this.updateSectionAndBlockPositions();
},
onCloseBlockConfig() {
this.$store.commit('cmsPageState/removeSelectedItem');
},
pageConfigOpen(mode = null) {
const sideBarRefs = this.$refs.cmsSidebar.$refs;
if (mode === 'blocks') {
if (!this.isSystemDefaultLanguage) {
return;
}
sideBarRefs.blockSelectionSidebar.openContent();
return;
}
if (mode === 'itemConfig') {
sideBarRefs.itemConfigSidebar.openContent();
return;
}
sideBarRefs.pageConfigSidebar.openContent();
},
saveFinish() {
this.isSaveSuccessful = false;
},
onSaveEntity() {
this.isLoading = true;
return this.pageRepository.save(this.page, Shopware.Context.api, false).then(() => {
this.isLoading = false;
this.isSaveSuccessful = true;
return this.loadPage(this.page.id);
}).catch((exception) => {
this.isLoading = false;
this.createNotificationError({
message: exception.message,
});
let hasEmptyConfig = false;
if (exception.response.data?.errors) {
exception.response.data.errors.forEach((error) => {
if (error.code === 'c1051bb4-d103-4f74-8988-acbcafc7fdc3') {
hasEmptyConfig = true;
}
});
}
if (hasEmptyConfig === true) {
const warningMessage = this.$tc('sw-cms.detail.notification.messageMissingElements');
this.createNotificationError({
message: warningMessage,
duration: 10000,
});
this.$store.commit('cmsPageState/removeSelectedItem');
this.pageConfigOpen();
}
return Promise.reject(exception);
});
},
getSlotValidations(sections) {
const foundEmptyRequiredField = [];
const foundProductPageElements = CMS.UNIQUE_SLOTS.reduce((accumulator, element) => {
accumulator[element] = 0;
return accumulator;
}, {});
sections.forEach((section) => {
section.blocks.forEach((block) => {
block.backgroundMedia = null;
block.slots.forEach((slot) => {
if (this.page.type === CMS.PAGE_TYPES.PRODUCT_DETAIL && this.isProductPageElement(slot)) {
if (slot.type === 'buy-box') {
foundProductPageElements.buyBox += 1;
} else if (slot.type === 'product-description-reviews') {
foundProductPageElements.productDescriptionReviews += 1;
} else if (slot.type === 'cross-selling') {
foundProductPageElements.crossSelling += 1;
}
return;
}
foundEmptyRequiredField.push(...this.checkRequiredSlotConfigField(slot));
});
});
});
return {
foundEmptyRequiredField,
foundProductPageElements,
};
},
getRedundantElementsWarning(foundProductPageElements) {
const warningMessages = [];
Object.entries(foundProductPageElements).forEach(([key, value]) => {
if (value > 1) {
warningMessages.push(
this.$tc('sw-cms.detail.notification.messageRedundantElements',
0, {
name: this.$tc(`sw-cms.elements.${key}.label`),
}),
);
}
});
return warningMessages;
},
getMissingElements(elements) {
return Object.keys(elements).filter((key) => elements[key] === 0);
},
onPageSave(debounced = false) {
this.onPageUpdate();
if (debounced) {
this.debouncedPageSave();
return;
}
this.onSave();
},
debouncedPageSave: debounce(function debouncedOnSave() {
this.onSave();
}, debounceTimeout),
onSave() {
this.isSaveSuccessful = false;
if ((this.isSystemDefaultLanguage && !this.page.name) || !this.page.type) {
this.pageConfigOpen();
const warningMessage = this.$tc('sw-cms.detail.notification.messageMissingFields');
this.createNotificationError({
message: warningMessage,
});
return Promise.reject();
}
const sections = this.page.sections;
if (this.page.type === CMS.PAGE_TYPES.LISTING) {
let foundListingBlock = false;
sections.forEach((section) => {
section.blocks.forEach((block) => {
if (block.type === 'product-listing') {
foundListingBlock = true;
}
});
});
if (!foundListingBlock) {
this.createNotificationError({
message: this.$tc('sw-cms.detail.notification.messageMissingProductListing'),
});
this.cmsBlocks['product-listing'].hidden = false;
this.pageConfigOpen('blocks');
return Promise.reject();
}
this.cmsBlocks['product-listing'].hidden = true;
}
if (sections.length < 1) {
this.createNotificationError({
message: this.$tc('sw-cms.detail.notification.messageMissingSections'),
});
return Promise.reject();
}
if (sections.length === 1 && sections[0].blocks.length === 0) {
this.createNotificationError({
message: this.$tc('sw-cms.detail.notification.messageMissingBlocks'),
});
this.pageConfigOpen('blocks');
return Promise.reject();
}
const { foundEmptyRequiredField, foundProductPageElements } = this.getSlotValidations(sections);
if (this.page.type === CMS.PAGE_TYPES.PRODUCT_DETAIL) {
const warningMessages = this.getRedundantElementsWarning(foundProductPageElements);
if (warningMessages.length > 0) {
warningMessages.forEach((message) => {
this.createNotificationError({
message,
});
});
return Promise.reject();
}
}
const missingElements = this.getMissingElements(foundProductPageElements);
if (this.page.type === CMS.PAGE_TYPES.PRODUCT_DETAIL && missingElements.length > 0 && !this.isSaveable) {
this.missingElements = missingElements;
this.showMissingElementModal = true;
return Promise.reject();
}
if (foundEmptyRequiredField.length > 0) {
const warningMessage = this.$tc('sw-cms.detail.notification.messageMissingBlockFields');
this.createNotificationError({
message: warningMessage,
});
return Promise.reject();
}
this.deleteEntityAndRequiredConfigKey(this.page.sections);
return this.onSaveEntity();
},
deleteEntityAndRequiredConfigKey(sections) {
sections.forEach((section) => {
section.blocks.forEach((block) => {
block.slots.forEach((slot) => {
Object.values(slot.config).forEach((configField) => {
if (configField.entity) {
delete configField.entity;
}
if (configField.hasOwnProperty('required')) {
delete configField.required;
}
});
});
});
});
},
checkRequiredSlotConfigField(slot) {
return Object.values(slot.config).filter((configField) => {
return !!configField.required &&
(configField.value === null || configField.value.length < 1);
});
},
updateSectionAndBlockPositions() {
this.page.sections.forEach((section, index) => {
section.position = index;
this.updateBlockPositions(section);
});
},
updateBlockPositions(section) {
section.blocks.forEach((block, index) => {
block.position = index;
});
},
onPageUpdate() {
this.updateSectionAndBlockPositions();
this.updateDataMapping();
},
onBlockDuplicate(block, section) {
this.cloneBlockInSection(block, section);
this.updateSectionAndBlockPositions();
this.debouncedPageSave();
},
cloneBlockInSection(block, section) {
const newBlock = this.blockRepository.create();
const blockClone = cloneDeep(block);
blockClone.id = newBlock.id;
blockClone.position = block.position + 1;
blockClone.sectionId = section.id;
blockClone.sectionPosition = block.sectionPosition;
blockClone.slots = [];
Object.assign(newBlock, blockClone);
this.cloneSlotsInBlock(block, newBlock);
section.blocks.splice(newBlock.position, 0, newBlock);
},
cloneSlotsInBlock(block, newBlock) {
block.slots.forEach((slot) => {
const element = this.slotRepository.create();
element.blockId = newBlock.id;
element.slot = slot.slot;
element.type = slot.type;
element.config = cloneDeep(slot.config);
element.data = cloneDeep(slot.data);
newBlock.slots.push(element);
});
},
onSectionDuplicate(section) {
this.prepareSectionClone(section);
this.onSave();
},
prepareSectionClone(section) {
const newSection = this.sectionRepository.create();
const sectionClone = cloneDeep(section);
sectionClone.id = newSection.id;
sectionClone.position = section.position + 1;
sectionClone.pageId = this.page.id;
sectionClone.blocks = [];
Object.assign(newSection, sectionClone);
section.blocks.forEach((block) => {
this.cloneBlockInSection(block, newSection);
});
this.page.sections.splice(newSection.position, 0, newSection);
this.updateSectionAndBlockPositions();
return newSection;
},
onPageTypeChange() {
if (this.page.type === CMS.PAGE_TYPES.LISTING) {
this.processProductListingType();
} else {
this.page.sections.forEach((section) => {
section.blocks.forEach((block) => {
if (block.type === 'product-listing') {
section.blocks.remove(block.id);
}
});
});
}
if (this.page.type === CMS.PAGE_TYPES.PRODUCT_DETAIL) {
this.processProductDetailType();
}
this.checkSlotMappings();
this.onPageUpdate();
},
processProductListingType() {
const listingBlock = this.blockRepository.create();
const listingElements = [
{
blockId: listingBlock.id,
slot: 'content',
type: 'product-listing',
config: {},
},
];
this.processBlock(listingBlock, 'product-listing');
this.processElements(listingBlock, listingElements);
},
processProductDetailType() {
this.productDetailBlocks.forEach(block => {
const newBlock = this.blockRepository.create();
block.elements.forEach(el => { el.blockId = newBlock.id; });
this.processBlock(newBlock, block.type);
this.processElements(newBlock, block.elements);
});
},
processBlock(block, blockType) {
const cmsBlock = this.cmsBlocks[blockType];
let defaultConfig = cmsBlock.defaultConfig;
if (this.isProductPage && defaultConfig) {
defaultConfig = {
...defaultConfig,
marginLeft: '0',
marginRight: '0',
marginTop: (blockType === 'gallery-buybox' || blockType === 'product-description-reviews')
? '20px' : '0',
marginBottom: (blockType === 'product-heading' || blockType === 'product-description-reviews')
? '20px' : '0',
};
}
block.type = blockType;
block.position = 0;
block.sectionId = this.page.sections[0].id;
block.sectionPosition = 'main';
Object.assign(
block,
cloneDeep(this.blockConfigDefaults),
cloneDeep(defaultConfig || {}),
);
},
processElements(block, elements) {
elements.forEach((element) => {
const slot = this.slotRepository.create();
slot.blockId = element.blockId;
slot.slot = element.slot;
slot.type = element.type;
slot.config = element.config;
block.slots.push(slot);
});
this.page.sections[0].blocks.splice(0, 0, block);
},
checkSlotMappings() {
this.page.sections.forEach((sections) => {
sections.blocks.forEach((block) => {
block.slots.forEach((slot) => {
Object.keys(slot.config).forEach((key) => {
if (slot.config[key].source && slot.config[key].source === 'mapped') {
const mappingPath = slot.config[key].value.split('.');
if (mappingPath[0] !== this.demoEntity) {
slot.config[key].value = null;
slot.config[key].source = 'static';
}
}
});
});
});
});
},
isProductPageElement(slot) {
return CMS.UNIQUE_SLOTS_KEBAB.includes(slot.type);
},
onOpenLayoutAssignment() {
this.openLayoutAssignmentModal();
},
openLayoutAssignmentModal() {
this.showLayoutAssignmentModal = true;
},
closeLayoutAssignmentModal() {
this.showLayoutAssignmentModal = false;
},
/** @deprecated tag:v6.5.0 method can be removed completely */
onConfirmLayoutAssignment() {
this.previousRoute = '';
},
onCloseMissingElementModal() {
this.showMissingElementModal = false;
this.$nextTick(() => {
this.loadPage(this.pageId);
});
},
onSaveMissingElementModal() {
this.showMissingElementModal = false;
this.isSaveable = true;
this.$nextTick(() => {
this.onSave().finally(() => {
this.isSaveable = false;
});
});
},
},
});
|
import * as swcHelpers from "@swc/helpers";
var A;
(function(A1) {
var Point = function Point() {
"use strict";
swcHelpers.classCallCheck(this, Point);
};
A1.Point = Point;
})(A || (A = {}));
(function(A) {
var Point = /*#__PURE__*/ function() {
"use strict";
function Point() {
swcHelpers.classCallCheck(this, Point);
}
swcHelpers.createClass(Point, [
{
key: "fromCarthesian",
value: function fromCarthesian(p1) {
return {
x: p1.x,
y: p1.y
};
}
}
]);
return Point;
}();
})(A || (A = {}));
// ensure merges as expected
var p;
var p;
var X;
(function(X1) {
var Y1;
(function(Y) {
var Z1;
(function(Z) {
var Line = function Line() {
"use strict";
swcHelpers.classCallCheck(this, Line);
};
Z.Line = Line;
})(Z1 = Y.Z || (Y.Z = {}));
})(Y1 = X1.Y || (X1.Y = {}));
})(X || (X = {}));
(function(X2) {
var Y2;
(function(Y) {
var Z;
(function(Z) {
var Line = function Line() {
"use strict";
swcHelpers.classCallCheck(this, Line);
};
})(Z = Y.Z || (Y.Z = {}));
})(Y2 = X2.Y || (X2.Y = {}));
})(X || (X = {}));
// ensure merges as expected
var l;
var l;
|
function changeNewsEntry(action, id, img, text) {
if(!document.getElementById(id).getAttribute('name')) {
if(action == '1') {
document.getElementById(id).style.width = '95%';
document.getElementById(id).style.backgroundColor = '#0c9a8c';
document.getElementById(text).style.color = '#fff';
var img1 = new Image();
var img2 = new Image();
img1.src = 'img/pencil_white.png';
img2.src = '../img/pencil_white.png';
img1.onload = function(){document.getElementById(img).src = img1.src;}
img2.onload = function(){document.getElementById(img).src = img2.src;}
}
if(action == 0) {
document.getElementById(id).style.width = '99%';
document.getElementById(id).style.backgroundColor = '#d0d0b5';
document.getElementById(text).style.color = '#404040';
var img1 = new Image();
var img2 = new Image();
img1.src = 'img/pencil_black.png';
img2.src = '../img/pencil_black.png';
img1.onload = function(){document.getElementById(img).src = img1.src;}
img2.onload = function(){document.getElementById(img).src = img2.src;}
}
}
} |
/*
* Please see the included README.md file for license terms and conditions.
*/
// This file is a suggested starting place for your code.
// It is completely optional and not required.
// Note the reference that includes it in the index.html file.
/*jslint browser:true, devel:true, white:true, vars:true */
/*global $:false, intel:false app:false, dev:false, cordova:false */
// For improved debugging and maintenance of your app, it is highly
// recommended that you separate your JavaScript from your HTML files.
// Use the addEventListener() method to associate events with DOM elements.
// For example:
// var el ;
// el = document.getElementById("id_myButton") ;
// el.addEventListener("click", myEventHandler, false) ;
// The function below is an example of the best way to "start" your app.
// This example is calling the standard Cordova "hide splashscreen" function.
// You can add other code to it or add additional functions that are triggered
// by the same event or other events.
var pictureSource;
var destinationType;
function onAppReady() {
if( navigator.splashscreen && navigator.splashscreen.hide ) { // Cordova API detected
navigator.splashscreen.hide() ;
}
var element = document.getElementById('deviceProperties');
element.innerHTML = 'Device Model: ' + device.model + "<br/>" +
'Device Cordova: ' + device.cordova + "<br/>" +
'Device Platform: ' + device.platform + "<br/>" +
'Device UUID: ' + device.uuid + "<br/>" +
'Device Version: ' + device.version + "<br/>";
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
document.addEventListener("app.Ready", onAppReady, false) ;
// document.addEventListener("deviceready", onAppReady, false) ;
// document.addEventListener("onload", onAppReady, false) ;
// The app.Ready event shown above is generated by the init-dev.js file; it
// unifies a variety of common "ready" events. See the init-dev.js file for
// more details. You can use a different event to start your app, instead of
// this event. A few examples are shown in the sample code above. If you are
// using Cordova plugins you need to either use this app.Ready event or the
// standard Crordova deviceready event. Others will either not work or will
// work poorly.
// NOTE: change "dev.LOG" in "init-dev.js" to "true" to enable some console.log
// messages that can help you debug Cordova app initialization issues.
function onPhotoDataSuccess(imageData){
var smallImage = document.getElementById("smallImage");
smallImage.style.display = "block";
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function capturePhoto(){
navigator.camera.getPicture(onPhotoDataSuccess, onFail,
{quality:50, destinationType: destinationType.DATA_URL});
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onFail(message){
alert("Error debido a:" + message);
}
function geolocate(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(position){
var element = document.getElementById("geolocation");
element.innerHTML = "Latitude: " + position.coords.latitude + "<br/>" +
"Longitude:" + position.coords.longitude + "<br/>" +
"Altitude:" + position.coords.altitude + "<br/>" +
"Accuracy:" + position.coords.accuracy + "<br/>" +
"Altitude Accuracy:" + position.coords.altitudeAccuracy + "<br/>" +
"Heading" + position.coords.heading + "<br/>" +
"Speed" + position.coords.speed + "<br/>" +
"Timestamp" + position.timestamp + "<br/>";
}
function onError(error){
alert("code:" + error.code + "\n" + "messsage:" + error.message + "\n")
} |
module.exports = [{"name":"path","attribs":{"d":"M42 6H6c-2.21 0-4 1.79-4 4v24c0 2.21 1.79 4 4 4h10v4h16v-4h10c2.21 0 3.98-1.79 3.98-4L46 10c0-2.21-1.79-4-4-4zm0 28H6V10h36v24zM32 20v4h-6v6h-4v-6h-6v-4h6v-6h4v6h6z"}}]; |
import os
from tinydb import TinyDB
from flask import Flask
from flask_cors import CORS
from flask_restful import Resource, Api
from iam_profile_faker import V2ProfileFactory
app = Flask(__name__)
api = Api(app)
CORS(app)
# Helper functions
def _load_db():
"""Load the saved db file."""
path = os.path.dirname(os.path.abspath(__file__))
for file in os.listdir(path):
if file.endswith('.json'):
return os.path.join(path, file)
class RandomUsers(Resource):
"""Return users from the profile faker."""
def get(self, count=100, export_json=True):
factory = V2ProfileFactory()
return factory.create_batch(count, export_json=True)
class RandomUser(Resource):
"""Return a single user."""
def get(self, export_json=True):
return V2ProfileFactory().create(export_json=export_json)
class PersistentUsers(Resource):
"""Return users stored in a file."""
def get(self):
"""Return all the users from the db."""
db = TinyDB(_load_db())
return db.all()
class PersistentUser(Resource):
"""Return a single user."""
def get(self, user_id):
"""Return a single user with id `user_id`."""
db = TinyDB(_load_db())
profiles = db.all()
for profile in profiles:
if profile["user_id"]["value"] == user_id:
return profile
return None
api.add_resource(RandomUsers, '/', '/users')
api.add_resource(RandomUser, '/user')
api.add_resource(PersistentUsers, '/persistent/users')
api.add_resource(PersistentUser, '/persistent/user/<string:user_id>')
def main():
app.run(host='0.0.0.0', debug=True)
if __name__ == '__main__':
main()
|
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
const BookmarkScreen = () => {
return (
<View style={styles.container}>
<Text> Bookmark Screen</Text>
</View>
)
}
export default BookmarkScreen
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:"center",
alignItems:"center"
}
})
|
module.exports = (model, frame) => {
const jsonModel = model.toJSON ? model.toJSON(frame.options) : model;
return jsonModel;
};
|
from mysql.connector import connect
import pandas as pd
# from sklearn.preprocessing import StandardScaler
# import numpy as np
# import scipy
# import matplotlib.pyplot as plt
# from sklearn.neighbors import KNeighborsClassifier
# from sklearn.metrics import accuracy_score
import mysql.connector
# import sys
# import math
connection = mysql.connector.connect(
host="database",
database="teamformationassistant",
user="dbuser",
password="dbuserpwd"
)
# for assignTeam
def persistTeamData(teamData):
""" Creates a dataframe containing the project ids and the members matched to that project """
if connection.is_connected():
cursor = connection.cursor()
for row in teamData.index:
sql = "INSERT INTO Team(ProjectId, ProjectName, \
MemberId, MemberName)VALUES(%s,%s,%s,%s);"
cursor.execute(
sql,
(
str(teamData.loc[row, "ProjectId"]),
str(teamData.loc[row, "ProjectName"]),
str(teamData.loc[row, "MemberId"]),
str(teamData.loc[row, "MemberName"]),
),
)
connection.commit()
# for memberToTeamMapping
def setEmployeeAssignement(employ):
""" Updates the member details in the database if he or she is assigned to a project """
if connection.is_connected():
cursor = connection.cursor()
sql = "UPDATE Member SET IsAssigned= %s WHERE MemberId = %s ;"
cursor.execute(sql, (1, employ))
connection.commit()
# for assignTeam
def memberToTeamMapping(MemberData, ProjectData, RequirementsData):
""" Matches the members to the project teams """
requirementsIDs = RequirementsData["RequirementsId"].tolist()
employee = MemberData.loc[MemberData["IsAssigned"] == 0]
employee = employee["MemberId"].tolist()
teamData = pd.DataFrame(
columns=["ProjectId", "ProjectName", "MemberId", "MemberName"]
)
for requirementsID in requirementsIDs:
Req = RequirementsData.loc[RequirementsData["RequirementsId"] == requirementsID]
reqLanguage = Req["LanguagePreferred"].tolist()[0]
skillweight = float(Req["SkillWeight"])
experienceWeight = float(Req["ExperienceWeight"])
hoursWeight = float(Req["HoursWeight"])
languageWeight = float(Req["LanguageWeight"])
budgetWeight = float(Req["BudgetWeight"])
ProjectId = Req["ProjectId"].tolist()[0]
Project = ProjectData.loc[ProjectData["ProjectId"] == ProjectId]
ProjectName = Project["ProjectName"].tolist()
if len(ProjectName) == 0:
ProjectName = "Not Provided22"
else:
ProjectName = Project["ProjectName"].tolist()[0]
highScore = 0
selectedEmploy = ""
for employ in employee:
employData = MemberData.loc[MemberData["MemberId"] == employ]
skillScore = float(employData["SkillScore"])
expScore = float(employData["Experience"])
availableHours = float(employData["AvailableHoursPerWeek"])
hourlyRate = float(employData["HourlyRate"])
languageScore = 0
if reqLanguage in employData["Languages"].tolist()[0].split(","):
languageScore = 1
memscore = (
(skillweight * skillScore) / 100
+ (experienceWeight * expScore) / 10
+ (hoursWeight * availableHours) / 40
+ (languageWeight * languageScore) / 5
+ (budgetWeight * hourlyRate) / 100
)
if memscore > highScore:
selectedEmploy = employ
highScore = memscore
if selectedEmploy not in employee:
continue
employee.remove(selectedEmploy)
setEmployeeAssignement(int(selectedEmploy))
Member = MemberData.loc[MemberData["MemberId"] == selectedEmploy]
MemberName = Member["MemberName"].tolist()[0]
teamData = teamData.append(
{
"ProjectId": ProjectId,
"ProjectName": ProjectName,
"MemberId": selectedEmploy,
"MemberName": MemberName,
},
ignore_index=True,
)
return teamData
def assignTeam():
""" Runner function which makes subsequeent function calls and fires SQL queries to perform the team matching """
if connection.is_connected():
Member_Query = pd.read_sql_query("""select * from Member""", connection)
Project_Query = pd.read_sql_query("""select * from Project""", connection)
Requirements_Query = pd.read_sql_query(
"""select * from Requirements""", connection
)
MemberData = pd.DataFrame(
Member_Query,
columns=[
"MemberId",
"MemberName",
"DOB",
"Languages",
"IsAssigned",
"HourlyRate",
"MemberRole",
"Experience",
"SkillScore",
"AvailableHoursPerWeek",
],
)
ProjectData = pd.DataFrame(
Project_Query,
columns=[
"ProjectId",
"ProjectName",
"ProjectEndDate",
"ProjectTeamSize",
"Budget",
"Tools",
"IsAssignmentComplete",
"Priority",
],
)
RequirementsData = pd.DataFrame(
Requirements_Query,
columns=[
"RequirementsId",
"ProjectId",
"LanguagePreferred",
"Skill",
"MemberRole",
"AvailableHoursPerWeek",
"SkillWeight",
"ExperienceWeight",
"HoursWeight",
"LanguageWeight",
"BudgetWeight",
],
)
teamData = memberToTeamMapping(MemberData, ProjectData, RequirementsData)
persistTeamData(teamData)
if __name__ == "__main__":
assignTeam()
|
import torch
import pickle
import argparse
import os
from tqdm import trange, tqdm
import torch
import torchtext
from torchtext import data
from torchtext import datasets
from torch import nn
import torch.nn.functional as F
import math
from models import SimpleLSTMModel, AttentionRNN
from models.components.binarization import (
Binarize,
)
from eval_args import get_arg_parser
import constants
from vocab import Vocabulary, load_vocab
import dataset as d
import utils
def eval_bleu(
train_loader: d.BatchedIterator,
valid_loader: d.BatchedIterator,
model: nn.Module,
en_vocab: Vocabulary,
fr_vocab: Vocabulary,
device: str,
multi_gpu: bool,
eval_fast: bool,
output_file: str,
) -> None:
model = model.to(device)
if output_file is not None:
output_file = open(output_file, 'w')
if multi_gpu and device == 'cuda':
print('Using multi gpu training')
model = torch.nn.DataParallel(model, device_ids=[0, 1]).cuda()
bleus = []
count = 0
with tqdm(train_loader, total=len(train_loader)) as pbar:
for i, data in enumerate(pbar):
if i == 0:
continue
src, src_lengths = data.src
trg, trg_lengths = data.trg
if eval_fast:
predicted = model.generate_max(src, src_lengths, 100, device)
else:
predicted = model.slow_generate(src, src_lengths, 100, device)
# predicted = (torch.Tensor(src.size(0), 100).uniform_() * (len(fr_vocab) - 1)).long()
# predicted = predicted *
# predicted = model.generate_beam(src, src_lengths, 100, 5, device)
pred_arr = utils.torchtext_convert_to_str(predicted.cpu().numpy(), fr_vocab)[0]
out_arr = utils.torchtext_convert_to_str(trg.cpu().numpy(), fr_vocab)[0]
pred_slim_arr = utils.get_raw_sentence(pred_arr)
out_slim_arr = utils.get_raw_sentence(out_arr)
curr_bleu = utils.compute_bleu(pred_slim_arr, out_slim_arr)
bleus.append(curr_bleu)
if output_file is not None:
src_arr = utils.torchtext_convert_to_str(src.cpu().numpy(), en_vocab)[0]
src_slim_arr = utils.get_raw_sentence(src_arr)
output = ' '.join(pred_slim_arr)
actual_out = ' '.join(out_slim_arr)
src = ' '.join(src_slim_arr)
entry_str ='''
{DELIM}
BLEU = {BLEU}
src = {src}
target = {target}
predicted = {pred}
'''
entry_str = entry_str.format(
DELIM=utils.create_entry_delim(),
BLEU=curr_bleu * 100,
src=src,
target=actual_out,
pred=output,
)
output_file.write(entry_str)
count += 1
pbar.set_postfix(
curr_bleu=curr_bleu * 100,
avg_bleu=(sum(bleus) / len(bleus) * 100)
)
pbar.refresh()
if output_file is not None:
output_file.write(
utils.create_entry_delim() + "\n"
)
output_file.write(
'Average BLEU: {}\n'.format((sum(bleus) / len(bleus) * 100))
)
output_file.close()
def main() -> None:
parser = get_arg_parser()
args = parser.parse_args()
device = "cuda" if torch.cuda.is_available() and args.cuda else "cpu"
print('using device {}'.format(device))
print('loading datasets...')
src = data.Field(include_lengths=True,
init_token='<sos>', eos_token='<eos>', batch_first=True, fix_length=200)
trg = data.Field(include_lengths=True,
init_token='<sos>', eos_token='<eos>', batch_first=True)
if args.dataset == 'WMT':
mt_train = datasets.TranslationDataset(
path=constants.WMT14_EN_FR_SMALL_TRAIN,
exts=('.en', '.fr'),
fields=(src, trg)
)
src_vocab, trg_vocab = utils.load_torchtext_wmt_small_vocab()
src.vocab = src_vocab
trg.vocab = trg_vocab
mt_valid = None
else:
if args.dataset == 'Multi30k':
mt_train, mt_valid, mt_test = datasets.Multi30k.splits(
exts=('.en', '.de'),
fields=(src, trg),
)
elif args.dataset == 'IWSLT':
mt_train, mt_valid, mt_test = datasets.IWSLT.splits(
exts=('.en', '.de'),
fields=(src, trg),
)
else:
raise Exception("Uknown dataset: {}".format(args.dataset))
print('loading vocabulary...')
# mt_dev shares the fields, so it shares their vocab objects
src.build_vocab(
mt_train,
min_freq=args.torchtext_unk,
max_size=args.torchtext_src_max_vocab,
)
trg.build_vocab(
mt_train,
max_size=args.torchtext_trg_max_vocab,
)
print('loaded vocabulary')
# determine the correct dataset to evaluate
eval_dataset = mt_train if args.eval_train else mt_valid
eval_dataset = mt_test if args.eval_test else eval_dataset
train_loader = data.BucketIterator(
dataset=eval_dataset,
batch_size=1,
sort_key=lambda x: len(x.src), # data.interleave_keys(len(x.src), len(x.trg)),
sort_within_batch=True,
device=device
)
print('model type: {}'.format(args.model_type))
model = utils.build_model(parser, src.vocab, trg.vocab)
model.load_state_dict(torch.load(args.load_path))
model = model.eval()
if args.binarize:
print('binarizing model')
binarized_model = Binarize(model)
binarized_model.binarization()
print('using model...')
print(model)
eval_bleu(
train_loader=train_loader,
valid_loader=None, # valid_loader,
model=model,
en_vocab=src.vocab,
fr_vocab=trg.vocab,
device=device,
multi_gpu=args.multi_gpu,
eval_fast=args.eval_fast,
output_file=args.output_file,
)
if __name__ == "__main__":
main() |
describe("Sisyphus", function() {
var sisyphus, targetForm, namedForm;
beforeEach( function() {
loadFixtures( "fixtures.html" );
sisyphus = Sisyphus.getInstance();
sisyphus.setOptions( {} );
targetForm = $( "#form1" );
namedForm = $( "#named" );
sisyphus.protect( targetForm );
} );
afterEach( function() {
sisyphus = Sisyphus.free();
} );
it( "should return an object on instantiating", function() {
var sisyphus1 = Sisyphus.getInstance();
expect( typeof sisyphus1 ).toEqual( "object" );
} );
it( "should return null on freeing", function() {
sisyphus = Sisyphus.free();
expect( sisyphus ).toEqual( null );
} );
it( "should return the same instance", function() {
var sisyphus1 = Sisyphus.getInstance(),
sisyphus2 = Sisyphus.getInstance();
expect( sisyphus1 ).toEqual( sisyphus2 );
} );
it( "should have instances with common options, i.e. be a Singleton", function() {
var sisyphus1 = Sisyphus.getInstance(),
sisyphus2 = Sisyphus.getInstance();
sisyphus1.setOptions( {
timeout: 5
} );
sisyphus2.setOptions( {
timeout: 15
} );
expect( sisyphus1.options ).toEqual( sisyphus2.options );
} );
it( "should return false if Local Storage is unavailable", function() {
spyOn( sisyphus.browserStorage, "isAvailable" ).andCallFake( function() {
return false;
} );
expect( sisyphus.protect( targetForm ) ).toEqual( false );
} );
it( "should bind saving data only once", function() {
sisyphus = Sisyphus.free();
sisyphus = Sisyphus.getInstance();
spyOn( sisyphus, "bindSaveData" );
sisyphus.protect( "form" );
expect( sisyphus.bindSaveData.callCount ).toEqual( 1 );
} );
it( "should bind saving data only once - if new call is done it should just add new targets to protect", function() {
// #form1 is already being protected from 'beforeEach' method
spyOn( sisyphus, "bindSaveData" );
sisyphus.protect( $("#form2") );
expect( sisyphus.bindSaveData.callCount ).toEqual( 0 );
} );
it( "if new call is done it should just add new targets to protect", function() {
// #form1 is already being protected from 'beforeEach' method
var targets1 = sisyphus.targets.length,
targets2;
sisyphus.protect( $("#form2") );
targets2 = sisyphus.targets.length;
expect( targets1 ).toBeLessThan( targets2 );
} );
it( "should allow a custom name for the form", function() {
sisyphus = Sisyphus.getInstance();
sisyphus.setOptions( { name: "something" } );
sisyphus.protect( namedForm );
expect ( sisyphus.href ).toEqual( "something" );
} );
it( "should not protect the same form twice and more times", function() {
// #form1 is already being protected from 'beforeEach' method
var targets1 = sisyphus.targets.length,
targets2;
sisyphus.protect( $("#form1") );
sisyphus.protect( $("#form1") );
targets2 = sisyphus.targets.length;
expect( targets1 ).toEqual( targets2 );
} );
it( "should save textfield data on key input, if options.timeout is not set", function() {
spyOn( sisyphus, "saveToBrowserStorage" );
$( ":text:first", targetForm ).trigger( "oninput" );
expect( sisyphus.saveToBrowserStorage ).toHaveBeenCalled();
} );
it( "should not save all data, but textfield only on key input, if options.timeout is not set", function() {
spyOn( sisyphus, "saveAllData" );
$( ":text:first", targetForm ).trigger( "oninput" );
expect( sisyphus.saveAllData.callCount ).toEqual( 0 );
} );
it( "should save textarea data on key input, if options.timeout is not set", function() {
spyOn( sisyphus, "saveToBrowserStorage" );
$( "textarea:first", targetForm ).trigger( "oninput" );
expect( sisyphus.saveToBrowserStorage ).toHaveBeenCalled();
} );
it( "should not save all data, but textarea only on key input, if options.timeout is not set", function() {
spyOn( sisyphus, "saveAllData" );
$( "textarea:first", targetForm ).trigger( "oninput" );
expect( sisyphus.saveAllData.callCount ).toEqual( 0 );
} );
it( "should save all data on checkbox change", function() {
spyOn( sisyphus, "saveAllData" );
$( ":checkbox:first", targetForm ).trigger( "change" );
expect( sisyphus.saveAllData ).toHaveBeenCalled();
} );
it( "should save all data on radio change", function() {
spyOn( sisyphus, "saveAllData" );
$( ":radio:first", targetForm ).trigger( "change" );
expect( sisyphus.saveAllData ).toHaveBeenCalled();
} );
it( "should save all data on select change", function() {
spyOn( sisyphus, "saveAllData" );
$( "select:first", targetForm ).trigger( "change" );
expect( sisyphus.saveAllData ).toHaveBeenCalled();
} );
it( "should fire callback once on saving all data to Local Storage", function() {
spyOn( sisyphus.options, "onSave" );
sisyphus.saveAllData();
expect( sisyphus.options.onSave.callCount ).toEqual( 1 );
} );
it( "should fire callback on saving data to Local Storage", function() {
spyOn( sisyphus.options, "onSave" );
sisyphus.saveToBrowserStorage( "key", "value" );
expect( sisyphus.options.onSave ).toHaveBeenCalled();
} );
it( "should fire callback on removing data from Local Storage", function() {
spyOn( sisyphus.options, "onRelease" );
sisyphus.releaseData( targetForm.attr( "id" ), targetForm.find( ":text" ) );
expect( sisyphus.options.onRelease ).toHaveBeenCalled();
} );
it( "should fire callback on restoring data from Local Storage", function() {
spyOn( sisyphus.options, "onRestore" );
sisyphus.restoreAllData();
expect( sisyphus.options.onRestore ).toHaveBeenCalled();
} );
it( "should not store excluded fields data", function() {
sisyphus.setOptions( {
excludeFields: $( "textarea:first" )
})
$( "textarea:first" ).val( "should not store" );
sisyphus.saveAllData();
$( "textarea:first" ).val( "" );
sisyphus.restoreAllData();
expect( $( "textarea:first" ).val() ).toEqual( "" );
} );
});
describe("jQuery.sisyphus", function() {
beforeEach( function() {
loadFixtures( "fixtures.html" );
} );
it( "should return a Sisyphus instance", function() {
var form = $( "#form1");
var identifier = form.attr( "id" ) + form.attr( "name" );
var o = $( "#form1" ).sisyphus(),
sisyphus = Sisyphus.getInstance( identifier );
expect( o ).toEqual( sisyphus );
} );
it( "should set the custom name on the Sisyphus instance", function() {
Sisyphus.free()
var o = $(" #named" ).sisyphus( { name: "custom-name" } );
sisyphus = Sisyphus.getInstance();
expect( o.href ).toEqual( "custom-name" );
} );
it( "should protect matched forms with Sisyphus", function() {
var form = $( "#form1");
var identifier = form.attr( "id" ) + form.attr( "name" );
spyOn( Sisyphus.getInstance( identifier ), "protect" );
$( "#form1" ).sisyphus(),
expect( Sisyphus.getInstance( identifier ).protect ).toHaveBeenCalled();
} );
});
|
from manga_py.provider import Provider
from .helpers.std import Std
import re
RE_IMAGES = re.compile(r'images\s*=\s*({.+});')
class MangaWindowNet(Provider, Std):
__url = None
def get_chapter_index(self) -> str:
return self.chapter[0].replace('.', '-')
def get_content(self):
return self.http_get(self.__url)
def get_manga_name(self) -> str:
title = self.html_fromstring(self.get_url(), '.item-title > a, .nav-title > a', 0)
self.__url = self.http().normalize_uri(title.get('href'))
return title.text_content().strip()
def get_chapters(self):
items = self._elements('.chapter-list a.chapt')
result = []
re = self.re.compile(r'[Cc]h\.(\d+(?:\.\d+)?)')
n = self.http().normalize_uri
for i in items:
text = i.cssselect('b')[0].text_content()
if 'deleted' not in text.casefold():
result.append((
re.search(text).group(1),
n(i.get('href')),
))
return result
def get_files(self):
content = self.http_get(self.chapter[1])
items = self.json.loads(RE_IMAGES.search(content).group(1))
return [items[i] for i in sorted(items, key=lambda i: int(i))]
def get_cover(self) -> str:
return self._cover_from_content('.attr-cover > img')
def book_meta(self) -> dict:
pass
def chapter_for_json(self) -> str:
return self.chapter[1]
def prepare_cookies(self):
self.cf_scrape(self.get_url())
main = MangaWindowNet
|
define(["js/core/Component", "srv/auth/AuthenticationProvider", "flow", "srv/auth/Authentication", "js/data/Collection", 'srv/auth/AuthenticationError'], function (Component, AuthenticationProvider, flow, Authentication, Collection, AuthenticationError) {
var generateId = function () {
var d = new Date().getTime();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
};
return Component.inherit({
defaults: {
/**
* The data source where to store the token
*/
dataSource: null,
/**
* The data source which contains the user
*/
userDataSource: null,
/**
* The User mmodel class name
*/
userModelClassName: null,
/**
* Token life time in seconds
*/
tokenLifeTime: 600
},
ctor: function () {
this.$providers = [];
this.callBase();
},
addChild: function (child) {
if (child instanceof AuthenticationProvider) {
this.$providers.push(child);
} else {
throw new Error("Child for Providers must be an AuthenticationProvider");
}
this.callBase();
},
stop: function (callback) {
flow()
.seqEach(this.$providers, function (provider, cb) {
// ignore errors during stop
provider.stop(function () {
cb();
});
})
.exec(callback);
},
start: function (server, callback) {
if (this.$.userModelClassName) {
this.$.userModelClassName = require(this.$.userModelClassName.replace(/\./g, "/"));
}
flow()
.seqEach(this.$providers, function (provider, cb) {
provider.start(server, cb);
})
.exec(callback);
},
/**
* Returns the authentication provider for a given request
*
* @param authenticationRequest
* @returns {*}
*/
getAuthenticationProviderForRequest: function (authenticationRequest) {
var authenticationProviders = this.$providers,
provider;
for (var i = 0; i < authenticationProviders.length; i++) {
provider = authenticationProviders[i];
if (provider.isResponsibleForAuthenticationRequest(authenticationRequest)) {
return provider;
}
}
return null;
},
getRegistrationProviderForRequest: function (registrationRequest) {
var authenticationProviders = this.$providers,
provider;
for (var i = 0; i < authenticationProviders.length; i++) {
provider = authenticationProviders[i];
if (provider.isResponsibleForRegistrationRequest(registrationRequest)) {
return provider;
}
}
return null;
},
/**
* Checks token against a database
*
* @param token
* @param callback
*/
authenticateByToken: function (context, token, callback) {
var authentication = this.$.dataSource.createEntity(Authentication, token),
self = this;
// setup authentication
this.$stage.$bus.setUp(authentication);
flow()
.seq("authentication", function (cb) {
authentication.fetch({noCache: true}, function (err) {
if (!err) {
var now = new Date();
if (authentication.$.updated.getTime() < now.getTime() - (1000 * self.$.tokenLifeTime)) {
// remove token
authentication.remove();
// return error
err = AuthenticationError.AUTHENTICATION_EXPIRED;
}
} else {
// TODO: change to authentication not found
err = AuthenticationError.AUTHENTICATION_EXPIRED;
}
cb(err, authentication);
});
})
.seq(function (cb) {
this.vars.authentication.set('updated', new Date());
this.vars.authentication.save(null, cb);
})
.seq(function (cb) {
// init authentication
this.vars.authentication.init(cb);
})
.exec(function (err, results) {
authentication = results.authentication;
if (!err && authentication) {
context.user.addAuthentication(authentication);
}
callback && callback(err, authentication);
});
},
deauthenticateToken: function (token, callback) {
var authentication = this.$.dataSource.createEntity(Authentication, token);
authentication.remove(null, callback);
},
/***
* Creates an authentication for a authenticationRequest
*
* @param authenticationRequest
* @param callback
*/
authenticateByRequest: function (context, authenticationRequest, callback) {
//
var authProvider = this.getAuthenticationProviderForRequest(authenticationRequest);
if (authProvider) {
flow()
.seq("authentication", function (cb) {
// authenticate
authProvider.authenticate(authenticationRequest, cb);
})
.seq(function (cb) {
// init authentication
this.vars.authentication.init(cb);
})
.exec(function (err, results) {
var authentication = results.authentication;
if (!err && authentication) {
context.user.addAuthentication(authentication);
}
// return authentication with user id
callback(err, authentication);
})
} else {
callback(AuthenticationError.NO_PROVIDER_FOUND, null);
}
},
/**
* Creates a new user instance for a registration request
* Can be overridden to change how a user is created.
*
* @param registrationRequest
* @returns {*}
* @private
*/
_createUserForRegistrationRequest: function (registrationRequest) {
return this.$.userDataSource.createCollection(Collection.of(this.$.userModelClassName)).createItem();
},
registerByRequest: function (registrationRequest, callback) {
var provider = this.getRegistrationProviderForRequest(registrationRequest);
if (provider) {
var self = this,
user,
identityService = this.$.identityService;
flow()
// check if user already exists
.seq(function (cb) {
provider.checkRegistrationRequest(registrationRequest, cb);
})
// validates the registration request and returns authentication data from the provider
.seq("registrationData", function (cb) {
provider.loadRegistrationDataForRequest(registrationRequest, cb);
})
// creates a new user and sets the user data
.seq(function () {
user = self._createUserForRegistrationRequest(registrationRequest);
// TODO: find another way to extend user with data
// user.set(registrationRequest.$.userData);
})
// extends the user with the authentication data
.seq(function () {
provider.extendUserWithRegistrationData(user, this.vars.registrationData);
})
// validates and saves user
.seq("user", function (cb) {
user.validateAndSave({upsert: true}, cb)
})
// creates an identity for the user
.seq(function (cb) {
identityService.createAndSaveIdentity(user.identifier(), provider.$.name, this.vars.registrationData.providerUserId, cb);
})
.exec(function (err, results) {
callback(err, results.user);
});
}
},
changeAuthenticationByRequest: function (context, changeAuthenticationRequest, callback) {
var authProvider = this.getAuthenticationProviderForRequest(changeAuthenticationRequest);
if (authProvider) {
flow()
// check authentication request
.seq("authentication", function (cb) {
// change authentication
authProvider.changeAuthentication(changeAuthenticationRequest, cb);
})
.exec(callback)
} else {
callback(AuthenticationError.NO_PROVIDER_FOUND, null);
}
},
/**
* Saves an authentication and adds an token to it
*
* @param authentication
* @param callback
*/
saveAuthentication: function (authentication, callback) {
/***
* Let's save the authentication and so the user is logged in
*
*/
var token = generateId();
var authenticationInstance = this.$.dataSource.createEntity(Authentication, token);
authenticationInstance.set(authentication.$);
authenticationInstance.save(null, callback);
}
});
}); |
/*! Buefy v0.8.8 | MIT License | github.com/buefy/buefy */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) :
typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) :
(global = global || self, factory(global.Buefy = {}, global.Vue));
}(this, function (exports, Vue) { 'use strict';
Vue = Vue && Vue.hasOwnProperty('default') ? Vue['default'] : Vue;
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
/**
* Get value of an object property/path even if it's nested
*/
function getValueByPath(obj, path) {
var value = path.split('.').reduce(function (o, i) {
return o ? o[i] : null;
}, obj);
return value;
}
/**
* Extension of indexOf method by equality function if specified
*/
function indexOf(array, obj, fn) {
if (!array) return -1;
if (!fn || typeof fn !== 'function') return array.indexOf(obj);
for (var i = 0; i < array.length; i++) {
if (fn(array[i], obj)) {
return i;
}
}
return -1;
}
/**
* Merge function to replace Object.assign with deep merging possibility
*/
var isObject = function isObject(item) {
return _typeof(item) === 'object' && !Array.isArray(item);
};
var mergeFn = function mergeFn(target, source) {
var deep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (deep || !Object.assign) {
var isDeep = function isDeep(prop) {
return isObject(source[prop]) && target !== null && target.hasOwnProperty(prop) && isObject(target[prop]);
};
var replaced = Object.getOwnPropertyNames(source).map(function (prop) {
return _defineProperty({}, prop, isDeep(prop) ? mergeFn(target[prop], source[prop], deep) : source[prop]);
}).reduce(function (a, b) {
return _objectSpread2({}, a, {}, b);
}, {});
return _objectSpread2({}, target, {}, replaced);
} else {
return Object.assign(target, source);
}
};
var merge = mergeFn;
/**
* Mobile detection
* https://www.abeautifulsite.net/detecting-mobile-devices-with-javascript
*/
var isMobile = {
Android: function Android() {
return typeof window !== 'undefined' && window.navigator.userAgent.match(/Android/i);
},
BlackBerry: function BlackBerry() {
return typeof window !== 'undefined' && window.navigator.userAgent.match(/BlackBerry/i);
},
iOS: function iOS() {
return typeof window !== 'undefined' && window.navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function Opera() {
return typeof window !== 'undefined' && window.navigator.userAgent.match(/Opera Mini/i);
},
Windows: function Windows() {
return typeof window !== 'undefined' && window.navigator.userAgent.match(/IEMobile/i);
},
any: function any() {
return isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows();
}
};
function removeElement(el) {
if (typeof el.remove !== 'undefined') {
el.remove();
} else if (typeof el.parentNode !== 'undefined') {
el.parentNode.removeChild(el);
}
}
var config = {
defaultContainerElement: null,
defaultIconPack: 'mdi',
defaultIconComponent: null,
defaultIconPrev: 'chevron-left',
defaultIconNext: 'chevron-right',
defaultDialogConfirmText: null,
defaultDialogCancelText: null,
defaultSnackbarDuration: 3500,
defaultSnackbarPosition: null,
defaultToastDuration: 2000,
defaultToastPosition: null,
defaultNotificationDuration: 2000,
defaultNotificationPosition: null,
defaultTooltipType: 'is-primary',
defaultTooltipAnimated: false,
defaultTooltipDelay: 0,
defaultInputAutocomplete: 'on',
defaultDateFormatter: null,
defaultDateParser: null,
defaultDateCreator: null,
defaultTimeCreator: null,
defaultDayNames: null,
defaultMonthNames: null,
defaultFirstDayOfWeek: null,
defaultUnselectableDaysOfWeek: null,
defaultTimeFormatter: null,
defaultTimeParser: null,
defaultModalCanCancel: ['escape', 'x', 'outside', 'button'],
defaultModalScroll: null,
defaultDatepickerMobileNative: true,
defaultTimepickerMobileNative: true,
defaultNoticeQueue: true,
defaultInputHasCounter: true,
defaultTaginputHasCounter: true,
defaultUseHtml5Validation: true,
defaultDropdownMobileModal: true,
defaultFieldLabelPosition: null,
defaultDatepickerYearsRange: [-100, 3],
defaultDatepickerNearbyMonthDays: true,
defaultDatepickerNearbySelectableMonthDays: false,
defaultDatepickerShowWeekNumber: false,
defaultDatepickerMobileModal: true,
defaultTrapFocus: false,
defaultButtonRounded: false,
defaultCarouselInterval: 3500,
customIconPacks: null
}; // TODO defaultTrapFocus to true in the next breaking change
var setOptions = function setOptions(options) {
config = options;
};
var FormElementMixin = {
props: {
size: String,
expanded: Boolean,
loading: Boolean,
rounded: Boolean,
icon: String,
iconPack: String,
// Native options to use in HTML5 validation
autocomplete: String,
maxlength: [Number, String],
useHtml5Validation: {
type: Boolean,
default: function _default() {
return config.defaultUseHtml5Validation;
}
},
validationMessage: String
},
data: function data() {
return {
isValid: true,
isFocused: false,
newIconPack: this.iconPack || config.defaultIconPack
};
},
computed: {
/**
* Find parent Field, max 3 levels deep.
*/
parentField: function parentField() {
var parent = this.$parent;
for (var i = 0; i < 3; i++) {
if (parent && !parent.$data._isField) {
parent = parent.$parent;
}
}
return parent;
},
/**
* Get the type prop from parent if it's a Field.
*/
statusType: function statusType() {
if (!this.parentField) return;
if (!this.parentField.newType) return;
if (typeof this.parentField.newType === 'string') {
return this.parentField.newType;
} else {
for (var key in this.parentField.newType) {
if (this.parentField.newType[key]) {
return key;
}
}
}
},
/**
* Get the message prop from parent if it's a Field.
*/
statusMessage: function statusMessage() {
if (!this.parentField) return;
return this.parentField.newMessage;
},
/**
* Fix icon size for inputs, large was too big
*/
iconSize: function iconSize() {
switch (this.size) {
case 'is-small':
return this.size;
case 'is-medium':
return;
case 'is-large':
return this.newIconPack === 'mdi' ? 'is-medium' : '';
}
}
},
methods: {
/**
* Focus method that work dynamically depending on the component.
*/
focus: function focus() {
var _this = this;
if (this.$data._elementRef === undefined) return;
this.$nextTick(function () {
var el = _this.$el.querySelector(_this.$data._elementRef);
if (el) el.focus();
});
},
onBlur: function onBlur($event) {
this.isFocused = false;
this.$emit('blur', $event);
this.checkHtml5Validity();
},
onFocus: function onFocus($event) {
this.isFocused = true;
this.$emit('focus', $event);
},
getElement: function getElement() {
return this.$el.querySelector(this.$data._elementRef);
},
setInvalid: function setInvalid() {
var type = 'is-danger';
var message = this.validationMessage || this.getElement().validationMessage;
this.setValidity(type, message);
},
setValidity: function setValidity(type, message) {
var _this2 = this;
this.$nextTick(function () {
if (_this2.parentField) {
// Set type only if not defined
if (!_this2.parentField.type) {
_this2.parentField.newType = type;
} // Set message only if not defined
if (!_this2.parentField.message) {
_this2.parentField.newMessage = message;
}
}
});
},
/**
* Check HTML5 validation, set isValid property.
* If validation fail, send 'is-danger' type,
* and error message to parent if it's a Field.
*/
checkHtml5Validity: function checkHtml5Validity() {
if (!this.useHtml5Validation) return;
if (this.$refs[this.$data._elementRef] === undefined) return;
if (!this.getElement().checkValidity()) {
this.setInvalid();
this.isValid = false;
} else {
this.setValidity(null, null);
this.isValid = true;
}
return this.isValid;
}
}
};
var mdiIcons = {
sizes: {
'default': 'mdi-24px',
'is-small': null,
'is-medium': 'mdi-36px',
'is-large': 'mdi-48px'
},
iconPrefix: 'mdi-'
};
var faIcons = function faIcons() {
var faIconPrefix = config && config.defaultIconComponent ? '' : 'fa-';
return {
sizes: {
'default': faIconPrefix + 'lg',
'is-small': null,
'is-medium': faIconPrefix + '2x',
'is-large': faIconPrefix + '3x'
},
iconPrefix: faIconPrefix,
internalIcons: {
'information': 'info-circle',
'alert': 'exclamation-triangle',
'alert-circle': 'exclamation-circle',
'chevron-right': 'angle-right',
'chevron-left': 'angle-left',
'chevron-down': 'angle-down',
'eye-off': 'eye-slash',
'menu-down': 'caret-down',
'menu-up': 'caret-up'
}
};
};
var getIcons = function getIcons() {
var icons = {
mdi: mdiIcons,
fa: faIcons(),
fas: faIcons(),
far: faIcons(),
fad: faIcons(),
fab: faIcons(),
fal: faIcons()
};
if (config && config.customIconPacks) {
icons = merge(icons, config.customIconPacks, true);
}
return icons;
};
//
var script = {
name: 'BIcon',
props: {
type: [String, Object],
component: String,
pack: String,
icon: String,
size: String,
customSize: String,
customClass: String,
both: Boolean // This is used internally to show both MDI and FA icon
},
computed: {
iconConfig: function iconConfig() {
var allIcons = getIcons();
return allIcons[this.newPack];
},
iconPrefix: function iconPrefix() {
if (this.iconConfig && this.iconConfig.iconPrefix) {
return this.iconConfig.iconPrefix;
}
return '';
},
/**
* Internal icon name based on the pack.
* If pack is 'fa', gets the equivalent FA icon name of the MDI,
* internal icons are always MDI.
*/
newIcon: function newIcon() {
return "".concat(this.iconPrefix).concat(this.getEquivalentIconOf(this.icon));
},
newPack: function newPack() {
return this.pack || config.defaultIconPack;
},
newType: function newType() {
if (!this.type) return;
var splitType = [];
if (typeof this.type === 'string') {
splitType = this.type.split('-');
} else {
for (var key in this.type) {
if (this.type[key]) {
splitType = key.split('-');
break;
}
}
}
if (splitType.length <= 1) return;
return "has-text-".concat(splitType[1]);
},
newCustomSize: function newCustomSize() {
return this.customSize || this.customSizeByPack;
},
customSizeByPack: function customSizeByPack() {
if (this.iconConfig && this.iconConfig.sizes) {
if (this.size && this.iconConfig.sizes[this.size] !== undefined) {
return this.iconConfig.sizes[this.size];
} else if (this.iconConfig.sizes.default) {
return this.iconConfig.sizes.default;
}
}
return null;
},
useIconComponent: function useIconComponent() {
return this.component || config.defaultIconComponent;
}
},
methods: {
/**
* Equivalent icon name of the MDI.
*/
getEquivalentIconOf: function getEquivalentIconOf(value) {
// Only transform the class if the both prop is set to true
if (!this.both) {
return value;
}
if (this.iconConfig && this.iconConfig.internalIcons && this.iconConfig.internalIcons[value]) {
return this.iconConfig.internalIcons[value];
}
return value;
}
}
};
function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier
/* server only */
, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
} // Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script; // render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true; // functional template
if (isFunctionalTemplate) {
options.functional = true;
}
} // scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function hook(context) {
// 2.3 injection
context = context || // cached call
this.$vnode && this.$vnode.ssrContext || // stateful
this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
} // inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
} // register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
}; // used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
} else if (style) {
hook = shadowMode ? function () {
style.call(this, createInjectorShadow(this.$root.$options.shadowRoot));
} : function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}
var normalizeComponent_1 = normalizeComponent;
/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('span',{staticClass:"icon",class:[_vm.newType, _vm.size]},[(!_vm.useIconComponent)?_c('i',{class:[_vm.newPack, _vm.newIcon, _vm.newCustomSize, _vm.customClass]}):_c(_vm.useIconComponent,{tag:"component",class:[_vm.customClass],attrs:{"icon":[_vm.newPack, _vm.newIcon],"size":_vm.newCustomSize}})],1)};
var __vue_staticRenderFns__ = [];
/* style */
const __vue_inject_styles__ = undefined;
/* scoped */
const __vue_scope_id__ = undefined;
/* module identifier */
const __vue_module_identifier__ = undefined;
/* functional template */
const __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var Icon = normalizeComponent_1(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
var script$1 = {
name: 'BInput',
components: _defineProperty({}, Icon.name, Icon),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: [Number, String],
type: {
type: String,
default: 'text'
},
passwordReveal: Boolean,
iconClickable: Boolean,
hasCounter: {
type: Boolean,
default: function _default() {
return config.defaultInputHasCounter;
}
},
customClass: {
type: String,
default: ''
}
},
data: function data() {
return {
newValue: this.value,
newType: this.type,
newAutocomplete: this.autocomplete || config.defaultInputAutocomplete,
isPasswordVisible: false,
_elementRef: this.type === 'textarea' ? 'textarea' : 'input'
};
},
computed: {
computedValue: {
get: function get() {
return this.newValue;
},
set: function set(value) {
this.newValue = value;
this.$emit('input', value);
!this.isValid && this.checkHtml5Validity();
}
},
rootClasses: function rootClasses() {
return [this.iconPosition, this.size, {
'is-expanded': this.expanded,
'is-loading': this.loading,
'is-clearfix': !this.hasMessage
}];
},
inputClasses: function inputClasses() {
return [this.statusType, this.size, {
'is-rounded': this.rounded
}];
},
hasIconRight: function hasIconRight() {
return this.passwordReveal || this.loading || this.statusTypeIcon;
},
/**
* Position of the icon or if it's both sides.
*/
iconPosition: function iconPosition() {
if (this.icon && this.hasIconRight) {
return 'has-icons-left has-icons-right';
} else if (!this.icon && this.hasIconRight) {
return 'has-icons-right';
} else if (this.icon) {
return 'has-icons-left';
}
},
/**
* Icon name (MDI) based on the type.
*/
statusTypeIcon: function statusTypeIcon() {
switch (this.statusType) {
case 'is-success':
return 'check';
case 'is-danger':
return 'alert-circle';
case 'is-info':
return 'information';
case 'is-warning':
return 'alert';
}
},
/**
* Check if have any message prop from parent if it's a Field.
*/
hasMessage: function hasMessage() {
return !!this.statusMessage;
},
/**
* Current password-reveal icon name.
*/
passwordVisibleIcon: function passwordVisibleIcon() {
return !this.isPasswordVisible ? 'eye' : 'eye-off';
},
/**
* Get value length
*/
valueLength: function valueLength() {
if (typeof this.computedValue === 'string') {
return this.computedValue.length;
} else if (typeof this.computedValue === 'number') {
return this.computedValue.toString().length;
}
return 0;
}
},
watch: {
/**
* When v-model is changed:
* 1. Set internal value.
*/
value: function value(_value) {
this.newValue = _value;
}
},
methods: {
/**
* Toggle the visibility of a password-reveal input
* by changing the type and focus the input right away.
*/
togglePasswordVisibility: function togglePasswordVisibility() {
var _this = this;
this.isPasswordVisible = !this.isPasswordVisible;
this.newType = this.isPasswordVisible ? 'text' : 'password';
this.$nextTick(function () {
_this.$refs.input.focus();
});
},
/**
* Input's 'input' event listener, 'nextTick' is used to prevent event firing
* before ui update, helps when using masks (Cleavejs and potentially others).
*/
onInput: function onInput(event) {
var _this2 = this;
this.$nextTick(function () {
if (event.target) {
_this2.computedValue = event.target.value;
}
});
},
iconClick: function iconClick(event) {
var _this3 = this;
this.$emit('icon-click', event);
this.$nextTick(function () {
_this3.$refs.input.focus();
});
}
}
};
/* script */
const __vue_script__$1 = script$1;
/* template */
var __vue_render__$1 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"control",class:_vm.rootClasses},[(_vm.type !== 'textarea')?_c('input',_vm._b({ref:"input",staticClass:"input",class:[_vm.inputClasses, _vm.customClass],attrs:{"type":_vm.newType,"autocomplete":_vm.newAutocomplete,"maxlength":_vm.maxlength},domProps:{"value":_vm.computedValue},on:{"input":_vm.onInput,"blur":_vm.onBlur,"focus":_vm.onFocus}},'input',_vm.$attrs,false)):_c('textarea',_vm._b({ref:"textarea",staticClass:"textarea",class:[_vm.inputClasses, _vm.customClass],attrs:{"maxlength":_vm.maxlength},domProps:{"value":_vm.computedValue},on:{"input":_vm.onInput,"blur":_vm.onBlur,"focus":_vm.onFocus}},'textarea',_vm.$attrs,false)),_vm._v(" "),(_vm.icon)?_c('b-icon',{staticClass:"is-left",class:{'is-clickable': _vm.iconClickable},attrs:{"icon":_vm.icon,"pack":_vm.iconPack,"size":_vm.iconSize},nativeOn:{"click":function($event){return _vm.iconClick($event)}}}):_vm._e(),_vm._v(" "),(!_vm.loading && (_vm.passwordReveal || _vm.statusTypeIcon))?_c('b-icon',{staticClass:"is-right",class:{ 'is-clickable': _vm.passwordReveal },attrs:{"icon":_vm.passwordReveal ? _vm.passwordVisibleIcon : _vm.statusTypeIcon,"pack":_vm.iconPack,"size":_vm.iconSize,"type":!_vm.passwordReveal ? _vm.statusType : 'is-primary',"both":""},nativeOn:{"click":function($event){return _vm.togglePasswordVisibility($event)}}}):_vm._e(),_vm._v(" "),(_vm.maxlength && _vm.hasCounter && _vm.type !== 'number')?_c('small',{staticClass:"help counter",class:{ 'is-invisible': !_vm.isFocused }},[_vm._v("\n "+_vm._s(_vm.valueLength)+" / "+_vm._s(_vm.maxlength)+"\n ")]):_vm._e()],1)};
var __vue_staticRenderFns__$1 = [];
/* style */
const __vue_inject_styles__$1 = undefined;
/* scoped */
const __vue_scope_id__$1 = undefined;
/* module identifier */
const __vue_module_identifier__$1 = undefined;
/* functional template */
const __vue_is_functional_template__$1 = false;
/* style inject */
/* style inject SSR */
var Input = normalizeComponent_1(
{ render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
__vue_inject_styles__$1,
__vue_script__$1,
__vue_scope_id__$1,
__vue_is_functional_template__$1,
__vue_module_identifier__$1,
undefined,
undefined
);
var script$2 = {
name: 'BAutocomplete',
components: _defineProperty({}, Input.name, Input),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: [Number, String],
data: {
type: Array,
default: function _default() {
return [];
}
},
field: {
type: String,
default: 'value'
},
keepFirst: Boolean,
clearOnSelect: Boolean,
openOnFocus: Boolean,
customFormatter: Function
},
data: function data() {
return {
selected: null,
hovered: null,
isActive: false,
newValue: this.value,
newAutocomplete: this.autocomplete || 'off',
isListInViewportVertically: true,
hasFocus: false,
_isAutocomplete: true,
_elementRef: 'input'
};
},
computed: {
/**
* White-listed items to not close when clicked.
* Add input, dropdown and all children.
*/
whiteList: function whiteList() {
var whiteList = [];
whiteList.push(this.$refs.input.$el.querySelector('input'));
whiteList.push(this.$refs.dropdown); // Add all chidren from dropdown
if (this.$refs.dropdown !== undefined) {
var children = this.$refs.dropdown.querySelectorAll('*');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var child = _step.value;
whiteList.push(child);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
if (this.$parent.$data._isTaginput) {
// Add taginput container
whiteList.push(this.$parent.$el); // Add .tag and .delete
var tagInputChildren = this.$parent.$el.querySelectorAll('*');
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = tagInputChildren[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var tagInputChild = _step2.value;
whiteList.push(tagInputChild);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
return whiteList;
},
/**
* Check if exists default slot
*/
hasDefaultSlot: function hasDefaultSlot() {
return !!this.$scopedSlots.default;
},
/**
* Check if exists "empty" slot
*/
hasEmptySlot: function hasEmptySlot() {
return !!this.$slots.empty;
},
/**
* Check if exists "header" slot
*/
hasHeaderSlot: function hasHeaderSlot() {
return !!this.$slots.header;
},
/**
* Check if exists "footer" slot
*/
hasFooterSlot: function hasFooterSlot() {
return !!this.$slots.footer;
}
},
watch: {
/**
* When dropdown is toggled, check the visibility to know when
* to open upwards.
*/
isActive: function isActive(active) {
var _this = this;
if (active) {
this.calcDropdownInViewportVertical();
} else {
this.$nextTick(function () {
return _this.setHovered(null);
}); // Timeout to wait for the animation to finish before recalculating
setTimeout(function () {
_this.calcDropdownInViewportVertical();
}, 100);
}
},
/**
* When updating input's value
* 1. Emit changes
* 2. If value isn't the same as selected, set null
* 3. Close dropdown if value is clear or else open it
*/
newValue: function newValue(value) {
this.$emit('input', value); // Check if selected is invalid
var currentValue = this.getValue(this.selected);
if (currentValue && currentValue !== value) {
this.setSelected(null, false);
} // Close dropdown if input is clear or else open it
if (this.hasFocus && (!this.openOnFocus || value)) {
this.isActive = !!value;
}
},
/**
* When v-model is changed:
* 1. Update internal value.
* 2. If it's invalid, validate again.
*/
value: function value(_value) {
this.newValue = _value;
!this.isValid && this.$refs.input.checkHtml5Validity();
},
/**
* Select first option if "keep-first
*/
data: function data(value) {
// Keep first option always pre-selected
if (this.keepFirst) {
this.selectFirstOption(value);
}
}
},
methods: {
/**
* Set which option is currently hovered.
*/
setHovered: function setHovered(option) {
if (option === undefined) return;
this.hovered = option;
},
/**
* Set which option is currently selected, update v-model,
* update input value and close dropdown.
*/
setSelected: function setSelected(option) {
var _this2 = this;
var closeDropdown = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (option === undefined) return;
this.selected = option;
this.$emit('select', this.selected);
if (this.selected !== null) {
this.newValue = this.clearOnSelect ? '' : this.getValue(this.selected);
}
closeDropdown && this.$nextTick(function () {
_this2.isActive = false;
});
},
/**
* Select first option
*/
selectFirstOption: function selectFirstOption(options) {
var _this3 = this;
this.$nextTick(function () {
if (options.length) {
// If has visible data or open on focus, keep updating the hovered
if (_this3.openOnFocus || _this3.newValue !== '' && _this3.hovered !== options[0]) {
_this3.setHovered(options[0]);
}
} else {
_this3.setHovered(null);
}
});
},
/**
* Enter key listener.
* Select the hovered option.
*/
enterPressed: function enterPressed() {
if (this.hovered === null) return;
this.setSelected(this.hovered);
},
/**
* Tab key listener.
* Select hovered option if it exists, close dropdown, then allow
* native handling to move to next tabbable element.
*/
tabPressed: function tabPressed() {
if (this.hovered === null) {
this.isActive = false;
return;
}
this.setSelected(this.hovered);
},
/**
* Close dropdown if clicked outside.
*/
clickedOutside: function clickedOutside(event) {
if (this.whiteList.indexOf(event.target) < 0) this.isActive = false;
},
/**
* Return display text for the input.
* If object, get value from path, or else just the value.
*/
getValue: function getValue(option) {
if (option === null) return;
if (typeof this.customFormatter !== 'undefined') {
return this.customFormatter(option);
}
return _typeof(option) === 'object' ? getValueByPath(option, this.field) : option;
},
/**
* Calculate if the dropdown is vertically visible when activated,
* otherwise it is openened upwards.
*/
calcDropdownInViewportVertical: function calcDropdownInViewportVertical() {
var _this4 = this;
this.$nextTick(function () {
/**
* this.$refs.dropdown may be undefined
* when Autocomplete is conditional rendered
*/
if (_this4.$refs.dropdown === undefined) return;
var rect = _this4.$refs.dropdown.getBoundingClientRect();
_this4.isListInViewportVertically = rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight);
});
},
/**
* Arrows keys listener.
* If dropdown is active, set hovered option, or else just open.
*/
keyArrows: function keyArrows(direction) {
var sum = direction === 'down' ? 1 : -1;
if (this.isActive) {
var index = this.data.indexOf(this.hovered) + sum;
index = index > this.data.length - 1 ? this.data.length : index;
index = index < 0 ? 0 : index;
this.setHovered(this.data[index]);
var list = this.$refs.dropdown.querySelector('.dropdown-content');
var element = list.querySelectorAll('a.dropdown-item:not(.is-disabled)')[index];
if (!element) return;
var visMin = list.scrollTop;
var visMax = list.scrollTop + list.clientHeight - element.clientHeight;
if (element.offsetTop < visMin) {
list.scrollTop = element.offsetTop;
} else if (element.offsetTop >= visMax) {
list.scrollTop = element.offsetTop - list.clientHeight + element.clientHeight;
}
} else {
this.isActive = true;
}
},
/**
* Focus listener.
* If value is the same as selected, select all text.
*/
focused: function focused(event) {
if (this.getValue(this.selected) === this.newValue) {
this.$el.querySelector('input').select();
}
if (this.openOnFocus) {
this.isActive = true;
if (this.keepFirst) {
this.selectFirstOption(this.data);
}
}
this.hasFocus = true;
this.$emit('focus', event);
},
/**
* Blur listener.
*/
onBlur: function onBlur(event) {
this.hasFocus = false;
this.$emit('blur', event);
},
onInput: function onInput(event) {
var currentValue = this.getValue(this.selected);
if (currentValue && currentValue === this.newValue) return;
this.$emit('typing', this.newValue);
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('click', this.clickedOutside);
window.addEventListener('resize', this.calcDropdownInViewportVertical);
}
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('click', this.clickedOutside);
window.removeEventListener('resize', this.calcDropdownInViewportVertical);
}
}
};
/* script */
const __vue_script__$2 = script$2;
/* template */
var __vue_render__$2 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"autocomplete control",class:{'is-expanded': _vm.expanded}},[_c('b-input',_vm._b({ref:"input",attrs:{"type":"text","size":_vm.size,"loading":_vm.loading,"rounded":_vm.rounded,"icon":_vm.icon,"icon-pack":_vm.iconPack,"maxlength":_vm.maxlength,"autocomplete":_vm.newAutocomplete,"use-html5-validation":_vm.useHtml5Validation},on:{"input":_vm.onInput,"focus":_vm.focused,"blur":_vm.onBlur},nativeOn:{"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"esc",27,$event.key,["Esc","Escape"])){ return null; }$event.preventDefault();_vm.isActive = false;},"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"tab",9,$event.key,"Tab")){ return null; }return _vm.tabPressed($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.enterPressed($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"up",38,$event.key,["Up","ArrowUp"])){ return null; }$event.preventDefault();return _vm.keyArrows('up')},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"down",40,$event.key,["Down","ArrowDown"])){ return null; }$event.preventDefault();return _vm.keyArrows('down')}]},model:{value:(_vm.newValue),callback:function ($$v) {_vm.newValue=$$v;},expression:"newValue"}},'b-input',_vm.$attrs,false)),_vm._v(" "),_c('transition',{attrs:{"name":"fade"}},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive && (_vm.data.length > 0 || _vm.hasEmptySlot || _vm.hasHeaderSlot)),expression:"isActive && (data.length > 0 || hasEmptySlot || hasHeaderSlot)"}],ref:"dropdown",staticClass:"dropdown-menu",class:{ 'is-opened-top': !_vm.isListInViewportVertically }},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"dropdown-content"},[(_vm.hasHeaderSlot)?_c('div',{staticClass:"dropdown-item"},[_vm._t("header")],2):_vm._e(),_vm._v(" "),_vm._l((_vm.data),function(option,index){return _c('a',{key:index,staticClass:"dropdown-item",class:{ 'is-hovered': option === _vm.hovered },on:{"click":function($event){return _vm.setSelected(option)}}},[(_vm.hasDefaultSlot)?_vm._t("default",null,{"option":option,"index":index}):_c('span',[_vm._v("\n "+_vm._s(_vm.getValue(option, true))+"\n ")])],2)}),_vm._v(" "),(_vm.data.length === 0 && _vm.hasEmptySlot)?_c('div',{staticClass:"dropdown-item is-disabled"},[_vm._t("empty")],2):_vm._e(),_vm._v(" "),(_vm.hasFooterSlot)?_c('div',{staticClass:"dropdown-item"},[_vm._t("footer")],2):_vm._e()],2)])])],1)};
var __vue_staticRenderFns__$2 = [];
/* style */
const __vue_inject_styles__$2 = undefined;
/* scoped */
const __vue_scope_id__$2 = undefined;
/* module identifier */
const __vue_module_identifier__$2 = undefined;
/* functional template */
const __vue_is_functional_template__$2 = false;
/* style inject */
/* style inject SSR */
var Autocomplete = normalizeComponent_1(
{ render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 },
__vue_inject_styles__$2,
__vue_script__$2,
__vue_scope_id__$2,
__vue_is_functional_template__$2,
__vue_module_identifier__$2,
undefined,
undefined
);
var use = function use(plugin) {
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}
};
var registerComponent = function registerComponent(Vue, component) {
Vue.component(component.name, component);
};
var registerComponentProgrammatic = function registerComponentProgrammatic(Vue, property, component) {
if (!Vue.prototype.$buefy) Vue.prototype.$buefy = {};
Vue.prototype.$buefy[property] = component;
};
var Plugin = {
install: function install(Vue) {
registerComponent(Vue, Autocomplete);
}
};
use(Plugin);
var script$3 = {
name: 'BButton',
components: _defineProperty({}, Icon.name, Icon),
inheritAttrs: false,
props: {
type: [String, Object],
size: String,
label: String,
iconPack: String,
iconLeft: String,
iconRight: String,
rounded: {
type: Boolean,
default: function _default() {
return config.defaultButtonRounded;
}
},
loading: Boolean,
outlined: Boolean,
expanded: Boolean,
inverted: Boolean,
focused: Boolean,
active: Boolean,
hovered: Boolean,
selected: Boolean,
nativeType: {
type: String,
default: 'button',
validator: function validator(value) {
return ['button', 'submit', 'reset'].indexOf(value) >= 0;
}
},
tag: {
type: String,
default: 'button',
validator: function validator(value) {
return ['button', 'a', 'input', 'router-link', 'nuxt-link', 'n-link', 'NuxtLink', 'NLink'].indexOf(value) >= 0;
}
}
},
computed: {
iconSize: function iconSize() {
if (!this.size || this.size === 'is-medium') {
return 'is-small';
} else if (this.size === 'is-large') {
return 'is-medium';
}
return this.size;
}
}
};
/* script */
const __vue_script__$3 = script$3;
/* template */
var __vue_render__$3 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,_vm._g(_vm._b({tag:"component",staticClass:"button",class:[_vm.size, _vm.type, {
'is-rounded': _vm.rounded,
'is-loading': _vm.loading,
'is-outlined': _vm.outlined,
'is-fullwidth': _vm.expanded,
'is-inverted': _vm.inverted,
'is-focused': _vm.focused,
'is-active': _vm.active,
'is-hovered': _vm.hovered,
'is-selected': _vm.selected
}],attrs:{"type":_vm.nativeType}},'component',_vm.$attrs,false),_vm.$listeners),[(_vm.iconLeft)?_c('b-icon',{attrs:{"pack":_vm.iconPack,"icon":_vm.iconLeft,"size":_vm.iconSize}}):_vm._e(),_vm._v(" "),(_vm.label)?_c('span',[_vm._v(_vm._s(_vm.label))]):(_vm.$slots.default)?_c('span',[_vm._t("default")],2):_vm._e(),_vm._v(" "),(_vm.iconRight)?_c('b-icon',{attrs:{"pack":_vm.iconPack,"icon":_vm.iconRight,"size":_vm.iconSize}}):_vm._e()],1)};
var __vue_staticRenderFns__$3 = [];
/* style */
const __vue_inject_styles__$3 = undefined;
/* scoped */
const __vue_scope_id__$3 = undefined;
/* module identifier */
const __vue_module_identifier__$3 = undefined;
/* functional template */
const __vue_is_functional_template__$3 = false;
/* style inject */
/* style inject SSR */
var Button = normalizeComponent_1(
{ render: __vue_render__$3, staticRenderFns: __vue_staticRenderFns__$3 },
__vue_inject_styles__$3,
__vue_script__$3,
__vue_scope_id__$3,
__vue_is_functional_template__$3,
__vue_module_identifier__$3,
undefined,
undefined
);
var Plugin$1 = {
install: function install(Vue) {
registerComponent(Vue, Button);
}
};
use(Plugin$1);
var script$4 = {
name: 'BCarousel',
components: _defineProperty({}, Icon.name, Icon),
props: {
value: {
type: Number,
default: 0
},
animated: {
type: String,
default: 'slide'
},
interval: Number,
autoplay: {
type: Boolean,
default: true
},
pauseHover: {
type: Boolean,
default: true
},
pauseInfo: {
type: Boolean,
default: true
},
arrow: {
type: Boolean,
default: true
},
arrowBoth: {
type: Boolean,
default: true
},
arrowHover: {
type: Boolean,
default: true
},
iconPack: String,
iconSize: String,
iconPrev: {
type: String,
default: config.defaultIconPrev
},
iconNext: {
type: String,
default: config.defaultIconNext
},
indicator: {
type: Boolean,
default: true
},
indicatorInside: {
type: Boolean,
default: true
},
indicatorMode: {
type: String,
default: 'click'
},
indicatorStyle: {
type: String,
default: 'is-dots'
}
},
data: function data() {
return {
_isCarousel: true,
activeItem: this.value,
carouselItems: [],
isPause: false,
timer: null
};
},
watch: {
/**
* When v-model is changed set the new active tab.
*/
value: function value(_value) {
this.changeItem(_value, false);
},
/**
* When tab-items are updated, set active one.
*/
carouselItems: function carouselItems() {
if (this.activeItem < this.carouselItems.length) {
this.carouselItems[this.activeItem].isActive = true;
}
},
/**
* When autoplay is change, set by status
*/
autoplay: function autoplay(status) {
status ? this.startTimer() : this.pauseTimer();
}
},
methods: {
startTimer: function startTimer() {
var _this = this;
if (!this.autoplay || this.timer) return;
this.isPause = false;
this.timer = setInterval(function () {
_this.next();
}, this.interval || config.defaultCarouselInterval);
},
pauseTimer: function pauseTimer() {
if (!this.pauseHover && this.autoplay) return;
this.isPause = true;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
},
/**
* Change the active item and emit change event.
* action only for animated slide, there true = next, false = prev
*/
changeItem: function changeItem(newIndex, action) {
if (this.activeItem === newIndex) return;
this.carouselItems[this.activeItem].status(false, action);
this.carouselItems[newIndex].status(true, action);
this.activeItem = newIndex;
this.$emit('change', newIndex);
},
// Indicator trigger, emit input event and change active item.
modeChange: function modeChange(trigger, value) {
if (this.indicatorMode === trigger) {
this.$emit('input', value);
this.changeItem(value, false);
}
},
prev: function prev() {
return this.activeItem === 0 ? this.changeItem(this.carouselItems.length - 1, true) : this.changeItem(this.activeItem - 1, true);
},
next: function next() {
return this.activeItem === this.carouselItems.length - 1 ? this.changeItem(0, false) : this.changeItem(this.activeItem + 1, false);
},
// checking arrow between both
checkArrow: function checkArrow(value) {
if (this.arrowBoth) return true;
if (this.activeItem !== value) return true;
},
touchStart: function touchStart(event) {
this.startX = event.changedTouches[0].pageX;
},
touchEnd: function touchEnd(event) {
var diffX = event.changedTouches[0].pageX - this.startX;
if (Math.abs(diffX) > 50) {
if (diffX < 0) {
this.next();
} else {
this.prev();
}
}
}
},
mounted: function mounted() {
if (this.activeItem < this.carouselItems.length) {
this.carouselItems[this.activeItem].isActive = true;
}
this.startTimer();
},
beforeDestroy: function beforeDestroy() {
this.pauseTimer();
}
};
/* script */
const __vue_script__$4 = script$4;
/* template */
var __vue_render__$4 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"carousel",on:{"mouseenter":_vm.pauseTimer,"mouseleave":_vm.startTimer,"touchstart":function($event){$event.stopPropagation();return _vm.touchStart($event)},"touchend":function($event){$event.stopPropagation();return _vm.touchEnd($event)}}},[_c('div',{staticClass:"carousel-list"},[_vm._t("default"),_vm._v(" "),(_vm.arrow)?_c('div',{staticClass:"carousel-arrow",class:{'is-hovered': _vm.arrowHover}},[(_vm.checkArrow(0))?_c('b-icon',{staticClass:"has-icons-left",attrs:{"pack":_vm.iconPack,"icon":_vm.iconPrev,"size":_vm.iconSize,"both":""},nativeOn:{"click":function($event){$event.preventDefault();return _vm.prev($event)}}}):_vm._e(),_vm._v(" "),(_vm.checkArrow(_vm.carouselItems.length - 1))?_c('b-icon',{staticClass:"has-icons-right",attrs:{"pack":_vm.iconPack,"icon":_vm.iconNext,"size":_vm.iconSize,"both":""},nativeOn:{"click":function($event){$event.preventDefault();return _vm.next($event)}}}):_vm._e()],1):_vm._e()],2),_vm._v(" "),(_vm.autoplay && _vm.pauseHover && _vm.pauseInfo && _vm.isPause)?_c('div',{staticClass:"carousel-pause"},[_c('span',{staticClass:"tag"},[_vm._v("Pause")])]):_vm._e(),_vm._v(" "),(_vm.indicator)?_c('div',{staticClass:"carousel-indicator",class:{'is-inside': _vm.indicatorInside}},_vm._l((_vm.carouselItems),function(item,index){return _c('a',{key:index,staticClass:"indicator-item",class:{'is-active': index === _vm.activeItem},on:{"mouseover":function($event){return _vm.modeChange('hover', index)},"click":function($event){return _vm.modeChange('click', index)}}},[_vm._t("indicators",[_c('span',{staticClass:"indicator-style",class:_vm.indicatorStyle})],{"i":index})],2)}),0):_vm._e()])};
var __vue_staticRenderFns__$4 = [];
/* style */
const __vue_inject_styles__$4 = undefined;
/* scoped */
const __vue_scope_id__$4 = undefined;
/* module identifier */
const __vue_module_identifier__$4 = undefined;
/* functional template */
const __vue_is_functional_template__$4 = false;
/* style inject */
/* style inject SSR */
var Carousel = normalizeComponent_1(
{ render: __vue_render__$4, staticRenderFns: __vue_staticRenderFns__$4 },
__vue_inject_styles__$4,
__vue_script__$4,
__vue_scope_id__$4,
__vue_is_functional_template__$4,
__vue_module_identifier__$4,
undefined,
undefined
);
//
//
//
//
//
//
//
//
var script$5 = {
name: 'BCarouselItem',
data: function data() {
return {
isActive: false,
transitionName: null
};
},
computed: {
transition: function transition() {
if (this.$parent.animated === 'fade') {
return 'fade';
} else {
return this.transitionName;
}
}
},
methods: {
/**
* Status of item, alter animation name based on action.
*/
status: function status(value, action) {
this.transitionName = action ? 'slide-next' : 'slide-prev';
this.isActive = value;
}
},
created: function created() {
if (!this.$parent.$data._isCarousel) {
this.$destroy();
throw new Error('You should wrap bCarouselItem on a bCarousel');
}
this.$parent.carouselItems.push(this);
},
beforeDestroy: function beforeDestroy() {
var index = this.$parent.carouselItems.indexOf(this);
if (index >= 0) {
this.$parent.carouselItems.splice(index, 1);
}
}
};
/* script */
const __vue_script__$5 = script$5;
/* template */
var __vue_render__$5 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":_vm.transition}},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"carousel-item"},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$5 = [];
/* style */
const __vue_inject_styles__$5 = undefined;
/* scoped */
const __vue_scope_id__$5 = undefined;
/* module identifier */
const __vue_module_identifier__$5 = undefined;
/* functional template */
const __vue_is_functional_template__$5 = false;
/* style inject */
/* style inject SSR */
var CarouselItem = normalizeComponent_1(
{ render: __vue_render__$5, staticRenderFns: __vue_staticRenderFns__$5 },
__vue_inject_styles__$5,
__vue_script__$5,
__vue_scope_id__$5,
__vue_is_functional_template__$5,
__vue_module_identifier__$5,
undefined,
undefined
);
var Plugin$2 = {
install: function install(Vue) {
registerComponent(Vue, Carousel);
registerComponent(Vue, CarouselItem);
}
};
use(Plugin$2);
var CheckRadioMixin = {
props: {
value: [String, Number, Boolean, Function, Object, Array],
nativeValue: [String, Number, Boolean, Function, Object, Array],
type: String,
disabled: Boolean,
required: Boolean,
name: String,
size: String
},
data: function data() {
return {
newValue: this.value
};
},
computed: {
computedValue: {
get: function get() {
return this.newValue;
},
set: function set(value) {
this.newValue = value;
this.$emit('input', value);
}
}
},
watch: {
/**
* When v-model change, set internal value.
*/
value: function value(_value) {
this.newValue = _value;
}
},
methods: {
focus: function focus() {
// MacOS FireFox and Safari do not focus when clicked
this.$refs.input.focus();
}
}
};
//
var script$6 = {
name: 'BCheckbox',
mixins: [CheckRadioMixin],
props: {
indeterminate: Boolean,
trueValue: {
type: [String, Number, Boolean, Function, Object, Array],
default: true
},
falseValue: {
type: [String, Number, Boolean, Function, Object, Array],
default: false
}
}
};
/* script */
const __vue_script__$6 = script$6;
/* template */
var __vue_render__$6 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('label',{ref:"label",staticClass:"b-checkbox checkbox",class:[_vm.size, { 'is-disabled': _vm.disabled }],attrs:{"disabled":_vm.disabled},on:{"click":_vm.focus,"keydown":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.$refs.label.click()}}},[_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.computedValue),expression:"computedValue"}],ref:"input",attrs:{"type":"checkbox","disabled":_vm.disabled,"required":_vm.required,"name":_vm.name,"true-value":_vm.trueValue,"false-value":_vm.falseValue},domProps:{"indeterminate":_vm.indeterminate,"value":_vm.nativeValue,"checked":Array.isArray(_vm.computedValue)?_vm._i(_vm.computedValue,_vm.nativeValue)>-1:_vm._q(_vm.computedValue,_vm.trueValue)},on:{"click":function($event){$event.stopPropagation();},"change":function($event){var $$a=_vm.computedValue,$$el=$event.target,$$c=$$el.checked?(_vm.trueValue):(_vm.falseValue);if(Array.isArray($$a)){var $$v=_vm.nativeValue,$$i=_vm._i($$a,$$v);if($$el.checked){$$i<0&&(_vm.computedValue=$$a.concat([$$v]));}else{$$i>-1&&(_vm.computedValue=$$a.slice(0,$$i).concat($$a.slice($$i+1)));}}else{_vm.computedValue=$$c;}}}}),_vm._v(" "),_c('span',{staticClass:"check",class:_vm.type}),_vm._v(" "),_c('span',{staticClass:"control-label"},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$6 = [];
/* style */
const __vue_inject_styles__$6 = undefined;
/* scoped */
const __vue_scope_id__$6 = undefined;
/* module identifier */
const __vue_module_identifier__$6 = undefined;
/* functional template */
const __vue_is_functional_template__$6 = false;
/* style inject */
/* style inject SSR */
var Checkbox = normalizeComponent_1(
{ render: __vue_render__$6, staticRenderFns: __vue_staticRenderFns__$6 },
__vue_inject_styles__$6,
__vue_script__$6,
__vue_scope_id__$6,
__vue_is_functional_template__$6,
__vue_module_identifier__$6,
undefined,
undefined
);
//
var script$7 = {
name: 'BCheckboxButton',
mixins: [CheckRadioMixin],
props: {
type: {
type: String,
default: 'is-primary'
},
expanded: Boolean
},
data: function data() {
return {
isFocused: false
};
},
computed: {
checked: function checked() {
if (Array.isArray(this.newValue)) {
return this.newValue.indexOf(this.nativeValue) >= 0;
}
return this.newValue === this.nativeValue;
}
}
};
/* script */
const __vue_script__$7 = script$7;
/* template */
var __vue_render__$7 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"control",class:{ 'is-expanded': _vm.expanded }},[_c('label',{ref:"label",staticClass:"b-checkbox checkbox button",class:[_vm.checked ? _vm.type : null, _vm.size, {
'is-disabled': _vm.disabled,
'is-focused': _vm.isFocused
}],attrs:{"disabled":_vm.disabled},on:{"click":_vm.focus,"keydown":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.$refs.label.click()}}},[_vm._t("default"),_vm._v(" "),_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.computedValue),expression:"computedValue"}],ref:"input",attrs:{"type":"checkbox","disabled":_vm.disabled,"required":_vm.required,"name":_vm.name},domProps:{"value":_vm.nativeValue,"checked":Array.isArray(_vm.computedValue)?_vm._i(_vm.computedValue,_vm.nativeValue)>-1:(_vm.computedValue)},on:{"click":function($event){$event.stopPropagation();},"focus":function($event){_vm.isFocused = true;},"blur":function($event){_vm.isFocused = false;},"change":function($event){var $$a=_vm.computedValue,$$el=$event.target,$$c=$$el.checked?(true):(false);if(Array.isArray($$a)){var $$v=_vm.nativeValue,$$i=_vm._i($$a,$$v);if($$el.checked){$$i<0&&(_vm.computedValue=$$a.concat([$$v]));}else{$$i>-1&&(_vm.computedValue=$$a.slice(0,$$i).concat($$a.slice($$i+1)));}}else{_vm.computedValue=$$c;}}}})],2)])};
var __vue_staticRenderFns__$7 = [];
/* style */
const __vue_inject_styles__$7 = undefined;
/* scoped */
const __vue_scope_id__$7 = undefined;
/* module identifier */
const __vue_module_identifier__$7 = undefined;
/* functional template */
const __vue_is_functional_template__$7 = false;
/* style inject */
/* style inject SSR */
var CheckboxButton = normalizeComponent_1(
{ render: __vue_render__$7, staticRenderFns: __vue_staticRenderFns__$7 },
__vue_inject_styles__$7,
__vue_script__$7,
__vue_scope_id__$7,
__vue_is_functional_template__$7,
__vue_module_identifier__$7,
undefined,
undefined
);
var Plugin$3 = {
install: function install(Vue) {
registerComponent(Vue, Checkbox);
registerComponent(Vue, CheckboxButton);
}
};
use(Plugin$3);
var script$8 = {
name: 'BCollapse',
props: {
open: {
type: Boolean,
default: true
},
animation: {
type: String,
default: 'fade'
},
ariaId: {
type: String,
default: ''
},
position: {
type: String,
default: 'is-top',
validator: function validator(value) {
return ['is-top', 'is-bottom'].indexOf(value) > -1;
}
}
},
data: function data() {
return {
isOpen: this.open
};
},
watch: {
open: function open(value) {
this.isOpen = value;
}
},
methods: {
/**
* Toggle and emit events
*/
toggle: function toggle() {
this.isOpen = !this.isOpen;
this.$emit('update:open', this.isOpen);
this.$emit(this.isOpen ? 'open' : 'close');
}
},
render: function render(createElement) {
var trigger = createElement('div', {
staticClass: 'collapse-trigger',
on: {
click: this.toggle
}
}, this.$scopedSlots.trigger ? [this.$scopedSlots.trigger({
open: this.isOpen
})] : [this.$slots.trigger]);
var content = createElement('transition', {
props: {
name: this.animation
}
}, [createElement('div', {
staticClass: 'collapse-content',
attrs: {
'id': this.ariaId,
'aria-expanded': this.isOpen
},
directives: [{
name: 'show',
value: this.isOpen
}]
}, this.$slots.default)]);
return createElement('div', {
staticClass: 'collapse'
}, this.position === 'is-top' ? [trigger, content] : [content, trigger]);
}
};
/* script */
const __vue_script__$8 = script$8;
/* template */
/* style */
const __vue_inject_styles__$8 = undefined;
/* scoped */
const __vue_scope_id__$8 = undefined;
/* module identifier */
const __vue_module_identifier__$8 = undefined;
/* functional template */
const __vue_is_functional_template__$8 = undefined;
/* style inject */
/* style inject SSR */
var Collapse = normalizeComponent_1(
{},
__vue_inject_styles__$8,
__vue_script__$8,
__vue_scope_id__$8,
__vue_is_functional_template__$8,
__vue_module_identifier__$8,
undefined,
undefined
);
var Plugin$4 = {
install: function install(Vue) {
registerComponent(Vue, Collapse);
}
};
use(Plugin$4);
var AM = 'AM';
var PM = 'PM';
var HOUR_FORMAT_24 = '24';
var HOUR_FORMAT_12 = '12';
var defaultTimeFormatter = function defaultTimeFormatter(date, vm) {
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var period = '';
if (vm.hourFormat === HOUR_FORMAT_12) {
period = ' ' + (hours < 12 ? AM : PM);
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
}
return vm.pad(hours) + ':' + vm.pad(minutes) + (vm.enableSeconds ? ':' + vm.pad(seconds) : '') + period;
};
var defaultTimeParser = function defaultTimeParser(timeString, vm) {
if (timeString) {
var am = false;
if (vm.hourFormat === HOUR_FORMAT_12) {
var dateString12 = timeString.split(' ');
timeString = dateString12[0];
am = dateString12[1] === AM;
}
var time = timeString.split(':');
var hours = parseInt(time[0], 10);
var minutes = parseInt(time[1], 10);
var seconds = vm.enableSeconds ? parseInt(time[2], 10) : 0;
if (isNaN(hours) || hours < 0 || hours > 23 || vm.hourFormat === HOUR_FORMAT_12 && (hours < 1 || hours > 12) || isNaN(minutes) || minutes < 0 || minutes > 59) {
return null;
}
var d = null;
if (vm.computedValue && !isNaN(vm.computedValue)) {
d = new Date(vm.computedValue);
} else {
d = vm.timeCreator();
d.setMilliseconds(0);
}
d.setSeconds(seconds);
d.setMinutes(minutes);
if (vm.hourFormat === HOUR_FORMAT_12) {
if (am && hours === 12) {
hours = 0;
} else if (!am && hours !== 12) {
hours += 12;
}
}
d.setHours(hours);
return new Date(d.getTime());
}
return null;
};
var TimepickerMixin = {
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: Date,
inline: Boolean,
minTime: Date,
maxTime: Date,
placeholder: String,
editable: Boolean,
disabled: Boolean,
hourFormat: {
type: String,
default: HOUR_FORMAT_24,
validator: function validator(value) {
return value === HOUR_FORMAT_24 || value === HOUR_FORMAT_12;
}
},
incrementMinutes: {
type: Number,
default: 1
},
incrementSeconds: {
type: Number,
default: 1
},
timeFormatter: {
type: Function,
default: function _default(date, vm) {
if (typeof config.defaultTimeFormatter === 'function') {
return config.defaultTimeFormatter(date);
} else {
return defaultTimeFormatter(date, vm);
}
}
},
timeParser: {
type: Function,
default: function _default(date, vm) {
if (typeof config.defaultTimeParser === 'function') {
return config.defaultTimeParser(date);
} else {
return defaultTimeParser(date, vm);
}
}
},
mobileNative: {
type: Boolean,
default: function _default() {
return config.defaultTimepickerMobileNative;
}
},
timeCreator: {
type: Function,
default: function _default() {
if (typeof config.defaultTimeCreator === 'function') {
return config.defaultTimeCreator();
} else {
return new Date();
}
}
},
position: String,
unselectableTimes: Array,
openOnFocus: Boolean,
enableSeconds: Boolean,
defaultMinutes: Number,
defaultSeconds: Number
},
data: function data() {
return {
dateSelected: this.value,
hoursSelected: null,
minutesSelected: null,
secondsSelected: null,
meridienSelected: null,
_elementRef: 'input',
AM: AM,
PM: PM,
HOUR_FORMAT_24: HOUR_FORMAT_24,
HOUR_FORMAT_12: HOUR_FORMAT_12
};
},
computed: {
computedValue: {
get: function get() {
return this.dateSelected;
},
set: function set(value) {
this.dateSelected = value;
this.$emit('input', value);
}
},
hours: function hours() {
var hours = [];
var numberOfHours = this.isHourFormat24 ? 24 : 12;
for (var i = 0; i < numberOfHours; i++) {
var value = i;
var label = value;
if (!this.isHourFormat24) {
value = i + 1;
label = value;
if (this.meridienSelected === this.AM) {
if (value === 12) {
value = 0;
}
} else if (this.meridienSelected === this.PM) {
if (value !== 12) {
value += 12;
}
}
}
hours.push({
label: this.formatNumber(label),
value: value
});
}
return hours;
},
minutes: function minutes() {
var minutes = [];
for (var i = 0; i < 60; i += this.incrementMinutes) {
minutes.push({
label: this.formatNumber(i, true),
value: i
});
}
return minutes;
},
seconds: function seconds() {
var seconds = [];
for (var i = 0; i < 60; i += this.incrementSeconds) {
seconds.push({
label: this.formatNumber(i, true),
value: i
});
}
return seconds;
},
meridiens: function meridiens() {
return [AM, PM];
},
isMobile: function isMobile$1() {
return this.mobileNative && isMobile.any();
},
isHourFormat24: function isHourFormat24() {
return this.hourFormat === HOUR_FORMAT_24;
}
},
watch: {
hourFormat: function hourFormat() {
if (this.hoursSelected !== null) {
this.meridienSelected = this.hoursSelected >= 12 ? PM : AM;
}
},
/**
* When v-model is changed:
* 1. Update internal value.
* 2. If it's invalid, validate again.
*/
value: {
handler: function handler(value) {
this.updateInternalState(value);
!this.isValid && this.$refs.input.checkHtml5Validity();
},
immediate: true
}
},
methods: {
onMeridienChange: function onMeridienChange(value) {
if (this.hoursSelected !== null) {
if (value === PM) {
this.hoursSelected += 12;
} else if (value === AM) {
this.hoursSelected -= 12;
}
}
this.updateDateSelected(this.hoursSelected, this.minutesSelected, this.enableSeconds ? this.secondsSelected : 0, value);
},
onHoursChange: function onHoursChange(value) {
if (!this.minutesSelected && typeof this.defaultMinutes !== 'undefined') {
this.minutesSelected = this.defaultMinutes;
}
if (!this.secondsSelected && typeof this.defaultSeconds !== 'undefined') {
this.secondsSelected = this.defaultSeconds;
}
this.updateDateSelected(parseInt(value, 10), this.minutesSelected, this.enableSeconds ? this.secondsSelected : 0, this.meridienSelected);
},
onMinutesChange: function onMinutesChange(value) {
if (!this.secondsSelected && this.defaultSeconds) {
this.secondsSelected = this.defaultSeconds;
}
this.updateDateSelected(this.hoursSelected, parseInt(value, 10), this.enableSeconds ? this.secondsSelected : 0, this.meridienSelected);
},
onSecondsChange: function onSecondsChange(value) {
this.updateDateSelected(this.hoursSelected, this.minutesSelected, parseInt(value, 10), this.meridienSelected);
},
updateDateSelected: function updateDateSelected(hours, minutes, seconds, meridiens) {
if (hours != null && minutes != null && (!this.isHourFormat24 && meridiens !== null || this.isHourFormat24)) {
var time = null;
if (this.computedValue && !isNaN(this.computedValue)) {
time = new Date(this.computedValue);
} else {
time = this.timeCreator();
time.setMilliseconds(0);
}
time.setHours(hours);
time.setMinutes(minutes);
time.setSeconds(seconds);
this.computedValue = new Date(time.getTime());
}
},
updateInternalState: function updateInternalState(value) {
if (value) {
this.hoursSelected = value.getHours();
this.minutesSelected = value.getMinutes();
this.secondsSelected = value.getSeconds();
this.meridienSelected = value.getHours() >= 12 ? PM : AM;
} else {
this.hoursSelected = null;
this.minutesSelected = null;
this.secondsSelected = null;
this.meridienSelected = AM;
}
this.dateSelected = value;
},
isHourDisabled: function isHourDisabled(hour) {
var _this = this;
var disabled = false;
if (this.minTime) {
var minHours = this.minTime.getHours();
var noMinutesAvailable = this.minutes.every(function (minute) {
return _this.isMinuteDisabledForHour(hour, minute.value);
});
disabled = hour < minHours || noMinutesAvailable;
}
if (this.maxTime) {
if (!disabled) {
var maxHours = this.maxTime.getHours();
disabled = hour > maxHours;
}
}
if (this.unselectableTimes) {
if (!disabled) {
var unselectable = this.unselectableTimes.filter(function (time) {
if (_this.enableSeconds && _this.secondsSelected !== null) {
return time.getHours() === hour && time.getMinutes() === _this.minutesSelected && time.getSeconds() === _this.secondsSelected;
} else if (_this.minutesSelected !== null) {
return time.getHours() === hour && time.getMinutes() === _this.minutesSelected;
} else {
return time.getHours() === hour;
}
});
disabled = unselectable.length > 0;
}
}
return disabled;
},
isMinuteDisabledForHour: function isMinuteDisabledForHour(hour, minute) {
var disabled = false;
if (this.minTime) {
var minHours = this.minTime.getHours();
var minMinutes = this.minTime.getMinutes();
disabled = hour === minHours && minute < minMinutes;
}
if (this.maxTime) {
if (!disabled) {
var maxHours = this.maxTime.getHours();
var maxMinutes = this.maxTime.getMinutes();
disabled = hour === maxHours && minute > maxMinutes;
}
}
return disabled;
},
isMinuteDisabled: function isMinuteDisabled(minute) {
var _this2 = this;
var disabled = false;
if (this.hoursSelected !== null) {
if (this.isHourDisabled(this.hoursSelected)) {
disabled = true;
} else {
disabled = this.isMinuteDisabledForHour(this.hoursSelected, minute);
}
if (this.unselectableTimes) {
if (!disabled) {
var unselectable = this.unselectableTimes.filter(function (time) {
if (_this2.enableSeconds && _this2.secondsSelected !== null) {
return time.getHours() === _this2.hoursSelected && time.getMinutes() === minute && time.getSeconds() === _this2.secondsSelected;
} else {
return time.getHours() === _this2.hoursSelected && time.getMinutes() === minute;
}
});
disabled = unselectable.length > 0;
}
}
}
return disabled;
},
isSecondDisabled: function isSecondDisabled(second) {
var _this3 = this;
var disabled = false;
if (this.minutesSelected !== null) {
if (this.isMinuteDisabled(this.minutesSelected)) {
disabled = true;
} else {
if (this.minTime) {
var minHours = this.minTime.getHours();
var minMinutes = this.minTime.getMinutes();
var minSeconds = this.minTime.getSeconds();
disabled = this.hoursSelected === minHours && this.minutesSelected === minMinutes && second < minSeconds;
}
if (this.maxTime) {
if (!disabled) {
var maxHours = this.maxTime.getHours();
var maxMinutes = this.maxTime.getMinutes();
var maxSeconds = this.maxTime.getSeconds();
disabled = this.hoursSelected === maxHours && this.minutesSelected === maxMinutes && second > maxSeconds;
}
}
}
if (this.unselectableTimes) {
if (!disabled) {
var unselectable = this.unselectableTimes.filter(function (time) {
return time.getHours() === _this3.hoursSelected && time.getMinutes() === _this3.minutesSelected && time.getSeconds() === second;
});
disabled = unselectable.length > 0;
}
}
}
return disabled;
},
/*
* Parse string into date
*/
onChange: function onChange(value) {
var date = this.timeParser(value, this);
this.updateInternalState(date);
if (date && !isNaN(date)) {
this.computedValue = date;
} else {
// Force refresh input value when not valid date
this.computedValue = null;
this.$refs.input.newValue = this.computedValue;
}
},
/*
* Toggle timepicker
*/
toggle: function toggle(active) {
if (this.$refs.dropdown) {
this.$refs.dropdown.isActive = typeof active === 'boolean' ? active : !this.$refs.dropdown.isActive;
}
},
/*
* Close timepicker
*/
close: function close() {
this.toggle(false);
},
/*
* Call default onFocus method and show timepicker
*/
handleOnFocus: function handleOnFocus() {
this.onFocus();
if (this.openOnFocus) {
this.toggle(true);
}
},
/*
* Format date into string 'HH-MM-SS'
*/
formatHHMMSS: function formatHHMMSS(value) {
var date = new Date(value);
if (value && !isNaN(date)) {
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
return this.formatNumber(hours, true) + ':' + this.formatNumber(minutes, true) + ':' + this.formatNumber(seconds, true);
}
return '';
},
/*
* Parse time from string
*/
onChangeNativePicker: function onChangeNativePicker(event) {
var date = event.target.value;
if (date) {
var time = null;
if (this.computedValue && !isNaN(this.computedValue)) {
time = new Date(this.computedValue);
} else {
time = new Date();
time.setMilliseconds(0);
}
var t = date.split(':');
time.setHours(parseInt(t[0], 10));
time.setMinutes(parseInt(t[1], 10));
time.setSeconds(t[2] ? parseInt(t[2], 10) : 0);
this.computedValue = new Date(time.getTime());
} else {
this.computedValue = null;
}
},
formatNumber: function formatNumber(value, prependZero) {
return this.isHourFormat24 || prependZero ? this.pad(value) : value;
},
pad: function pad(value) {
return (value < 10 ? '0' : '') + value;
},
/*
* Format date into string
*/
formatValue: function formatValue(date) {
if (date && !isNaN(date)) {
return this.timeFormatter(date, this);
} else {
return null;
}
},
/**
* Keypress event that is bound to the document.
*/
keyPress: function keyPress(event) {
// Esc key
if (this.$refs.dropdown && this.$refs.dropdown.isActive && event.keyCode === 27) {
this.toggle(false);
}
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('keyup', this.keyPress);
}
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('keyup', this.keyPress);
}
}
};
var findFocusable = function findFocusable(element) {
if (!element) {
return null;
}
return element.querySelectorAll("a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n *[tabindex],\n *[contenteditable]");
};
var onKeyDown;
var bind = function bind(el, _ref) {
var _ref$value = _ref.value,
value = _ref$value === void 0 ? true : _ref$value;
if (value) {
var focusable = findFocusable(el);
if (focusable && focusable.length > 0) {
var firstFocusable = focusable[0];
var lastFocusable = focusable[focusable.length - 1];
onKeyDown = function onKeyDown(event) {
if (event.target === firstFocusable && event.shiftKey && event.key === 'Tab') {
event.preventDefault();
lastFocusable.focus();
} else if (event.target === lastFocusable && !event.shiftKey && event.key === 'Tab') {
event.preventDefault();
firstFocusable.focus();
}
};
el.addEventListener('keydown', onKeyDown);
}
}
};
var unbind = function unbind(el) {
el.removeEventListener('keydown', onKeyDown);
};
var directive = {
bind: bind,
unbind: unbind
};
//
var DEFAULT_CLOSE_OPTIONS = ['escape', 'outside'];
var script$9 = {
name: 'BDropdown',
directives: {
trapFocus: directive
},
props: {
value: {
type: [String, Number, Boolean, Object, Array, Function],
default: null
},
disabled: Boolean,
hoverable: Boolean,
inline: Boolean,
position: {
type: String,
validator: function validator(value) {
return ['is-top-right', 'is-top-left', 'is-bottom-left'].indexOf(value) > -1;
}
},
mobileModal: {
type: Boolean,
default: function _default() {
return config.defaultDropdownMobileModal;
}
},
ariaRole: {
type: String,
default: ''
},
animation: {
type: String,
default: 'fade'
},
multiple: Boolean,
trapFocus: {
type: Boolean,
default: config.defaultTrapFocus
},
closeOnClick: {
type: Boolean,
default: true
},
canClose: {
type: [Array, Boolean],
default: true
},
expanded: Boolean
},
data: function data() {
return {
selected: this.value,
isActive: false,
isHoverable: this.hoverable,
_isDropdown: true // Used internally by DropdownItem
};
},
computed: {
rootClasses: function rootClasses() {
return [this.position, {
'is-disabled': this.disabled,
'is-hoverable': this.hoverable,
'is-inline': this.inline,
'is-active': this.isActive || this.inline,
'is-mobile-modal': this.isMobileModal,
'is-expanded': this.expanded
}];
},
isMobileModal: function isMobileModal() {
return this.mobileModal && !this.inline && !this.hoverable;
},
cancelOptions: function cancelOptions() {
return typeof this.canClose === 'boolean' ? this.canClose ? DEFAULT_CLOSE_OPTIONS : [] : this.canClose;
},
ariaRoleMenu: function ariaRoleMenu() {
return this.ariaRole === 'menu' || this.ariaRole === 'list' ? this.ariaRole : null;
}
},
watch: {
/**
* When v-model is changed set the new selected item.
*/
value: function value(_value) {
this.selected = _value;
},
/**
* Emit event when isActive value is changed.
*/
isActive: function isActive(value) {
this.$emit('active-change', value);
}
},
methods: {
/**
* Click listener from DropdownItem.
* 1. Set new selected item.
* 2. Emit input event to update the user v-model.
* 3. Close the dropdown.
*/
selectItem: function selectItem(value) {
var _this = this;
if (this.multiple) {
if (this.selected) {
var index = this.selected.indexOf(value);
if (index === -1) {
this.selected.push(value);
} else {
this.selected.splice(index, 1);
}
} else {
this.selected = [value];
}
this.$emit('change', this.selected);
} else {
if (this.selected !== value) {
this.selected = value;
this.$emit('change', this.selected);
}
}
this.$emit('input', this.selected);
if (!this.multiple) {
this.isActive = !this.closeOnClick;
if (this.hoverable && this.closeOnClick) {
this.isHoverable = false; // Timeout for the animation complete before destroying
setTimeout(function () {
_this.isHoverable = true;
}, 250);
}
}
},
/**
* White-listed items to not close when clicked.
*/
isInWhiteList: function isInWhiteList(el) {
if (el === this.$refs.dropdownMenu) return true;
if (el === this.$refs.trigger) return true; // All chidren from dropdown
if (this.$refs.dropdownMenu !== undefined) {
var children = this.$refs.dropdownMenu.querySelectorAll('*');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var child = _step.value;
if (el === child) {
return true;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
} // All children from trigger
if (this.$refs.trigger !== undefined) {
var _children = this.$refs.trigger.querySelectorAll('*');
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = _children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _child = _step2.value;
if (el === _child) {
return true;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
return false;
},
/**
* Close dropdown if clicked outside.
*/
clickedOutside: function clickedOutside(event) {
if (this.cancelOptions.indexOf('outside') < 0) return;
if (this.inline) return;
if (!this.isInWhiteList(event.target)) this.isActive = false;
},
/**
* Keypress event that is bound to the document
*/
keyPress: function keyPress(event) {
// Esc key
if (this.isActive && event.keyCode === 27) {
if (this.cancelOptions.indexOf('escape') < 0) return;
this.isActive = false;
}
},
/**
* Toggle dropdown if it's not disabled.
*/
toggle: function toggle() {
var _this2 = this;
if (this.disabled) return;
if (!this.isActive) {
// if not active, toggle after clickOutside event
// this fixes toggling programmatic
this.$nextTick(function () {
var value = !_this2.isActive;
_this2.isActive = value; // Vue 2.6.x ???
setTimeout(function () {
return _this2.isActive = value;
});
});
} else {
this.isActive = !this.isActive;
}
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('click', this.clickedOutside);
document.addEventListener('keyup', this.keyPress);
}
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('click', this.clickedOutside);
document.removeEventListener('keyup', this.keyPress);
}
}
};
/* script */
const __vue_script__$9 = script$9;
/* template */
var __vue_render__$8 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"dropdown",class:_vm.rootClasses},[(!_vm.inline)?_c('div',{ref:"trigger",staticClass:"dropdown-trigger",attrs:{"role":"button","aria-haspopup":"true"},on:{"click":_vm.toggle}},[_vm._t("trigger")],2):_vm._e(),_vm._v(" "),_c('transition',{attrs:{"name":_vm.animation}},[(_vm.isMobileModal)?_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"background",attrs:{"aria-hidden":!_vm.isActive}}):_vm._e()]),_vm._v(" "),_c('transition',{attrs:{"name":_vm.animation}},[_c('div',{directives:[{name:"show",rawName:"v-show",value:((!_vm.disabled && (_vm.isActive || _vm.isHoverable)) || _vm.inline),expression:"(!disabled && (isActive || isHoverable)) || inline"},{name:"trap-focus",rawName:"v-trap-focus",value:(_vm.trapFocus),expression:"trapFocus"}],ref:"dropdownMenu",staticClass:"dropdown-menu",attrs:{"aria-hidden":!_vm.isActive}},[_c('div',{staticClass:"dropdown-content",attrs:{"role":_vm.ariaRoleMenu}},[_vm._t("default")],2)])])],1)};
var __vue_staticRenderFns__$8 = [];
/* style */
const __vue_inject_styles__$9 = undefined;
/* scoped */
const __vue_scope_id__$9 = undefined;
/* module identifier */
const __vue_module_identifier__$9 = undefined;
/* functional template */
const __vue_is_functional_template__$9 = false;
/* style inject */
/* style inject SSR */
var Dropdown = normalizeComponent_1(
{ render: __vue_render__$8, staticRenderFns: __vue_staticRenderFns__$8 },
__vue_inject_styles__$9,
__vue_script__$9,
__vue_scope_id__$9,
__vue_is_functional_template__$9,
__vue_module_identifier__$9,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$a = {
name: 'BDropdownItem',
props: {
value: {
type: [String, Number, Boolean, Object, Array, Function],
default: null
},
separator: Boolean,
disabled: Boolean,
custom: Boolean,
focusable: {
type: Boolean,
default: true
},
paddingless: Boolean,
hasLink: Boolean,
ariaRole: {
type: String,
default: ''
}
},
computed: {
anchorClasses: function anchorClasses() {
return {
'is-disabled': this.$parent.disabled || this.disabled,
'is-paddingless': this.paddingless,
'is-active': this.isActive
};
},
itemClasses: function itemClasses() {
return {
'dropdown-item': !this.hasLink,
'is-disabled': this.disabled,
'is-paddingless': this.paddingless,
'is-active': this.isActive,
'has-link': this.hasLink
};
},
ariaRoleItem: function ariaRoleItem() {
return this.ariaRole === 'menuitem' || this.ariaRole === 'listitem' ? this.ariaRole : null;
},
/**
* Check if item can be clickable.
*/
isClickable: function isClickable() {
return !this.$parent.disabled && !this.separator && !this.disabled && !this.custom;
},
isActive: function isActive() {
if (this.$parent.selected === null) return false;
if (this.$parent.multiple) return this.$parent.selected.indexOf(this.value) >= 0;
return this.value === this.$parent.selected;
}
},
methods: {
/**
* Click listener, select the item.
*/
selectItem: function selectItem() {
if (!this.isClickable) return;
this.$parent.selectItem(this.value);
this.$emit('click');
}
},
created: function created() {
if (!this.$parent.$data._isDropdown) {
this.$destroy();
throw new Error('You should wrap bDropdownItem on a bDropdown');
}
}
};
/* script */
const __vue_script__$a = script$a;
/* template */
var __vue_render__$9 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return (_vm.separator)?_c('hr',{staticClass:"dropdown-divider"}):(!_vm.custom && !_vm.hasLink)?_c('a',{staticClass:"dropdown-item",class:_vm.anchorClasses,attrs:{"role":_vm.ariaRoleItem,"tabindex":_vm.focusable ? 0 : null},on:{"click":_vm.selectItem}},[_vm._t("default")],2):_c('div',{class:_vm.itemClasses,attrs:{"role":_vm.ariaRoleItem,"tabindex":_vm.focusable ? 0 : null},on:{"click":_vm.selectItem}},[_vm._t("default")],2)};
var __vue_staticRenderFns__$9 = [];
/* style */
const __vue_inject_styles__$a = undefined;
/* scoped */
const __vue_scope_id__$a = undefined;
/* module identifier */
const __vue_module_identifier__$a = undefined;
/* functional template */
const __vue_is_functional_template__$a = false;
/* style inject */
/* style inject SSR */
var DropdownItem = normalizeComponent_1(
{ render: __vue_render__$9, staticRenderFns: __vue_staticRenderFns__$9 },
__vue_inject_styles__$a,
__vue_script__$a,
__vue_scope_id__$a,
__vue_is_functional_template__$a,
__vue_module_identifier__$a,
undefined,
undefined
);
var script$b = {
name: 'BFieldBody',
props: {
message: {
type: String
},
type: {
type: [String, Object]
}
},
render: function render(createElement) {
var _this = this;
return createElement('div', {
attrs: {
'class': 'field-body'
}
}, this.$slots.default.map(function (element) {
// skip returns and comments
if (!element.tag) {
return element;
}
if (_this.message) {
return createElement('b-field', {
attrs: {
message: _this.message,
'type': _this.type
}
}, [element]);
}
return createElement('b-field', {
attrs: {
'type': _this.type
}
}, [element]);
}));
}
};
/* script */
const __vue_script__$b = script$b;
/* template */
/* style */
const __vue_inject_styles__$b = undefined;
/* scoped */
const __vue_scope_id__$b = undefined;
/* module identifier */
const __vue_module_identifier__$b = undefined;
/* functional template */
const __vue_is_functional_template__$b = undefined;
/* style inject */
/* style inject SSR */
var FieldBody = normalizeComponent_1(
{},
__vue_inject_styles__$b,
__vue_script__$b,
__vue_scope_id__$b,
__vue_is_functional_template__$b,
__vue_module_identifier__$b,
undefined,
undefined
);
var script$c = {
name: 'BField',
components: _defineProperty({}, FieldBody.name, FieldBody),
props: {
type: [String, Object],
label: String,
labelFor: String,
message: [String, Array, Object],
grouped: Boolean,
groupMultiline: Boolean,
position: String,
expanded: Boolean,
horizontal: Boolean,
addons: {
type: Boolean,
default: true
},
customClass: String,
labelPosition: {
type: String,
default: function _default() {
return config.defaultFieldLabelPosition;
}
}
},
data: function data() {
return {
newType: this.type,
newMessage: this.message,
fieldLabelSize: null,
_isField: true // Used internally by Input and Select
};
},
computed: {
rootClasses: function rootClasses() {
return [this.newPosition, {
'is-expanded': this.expanded,
'is-grouped-multiline': this.groupMultiline,
'is-horizontal': this.horizontal,
'is-floating-in-label': this.hasLabel && !this.horizontal && this.labelPosition === 'inside',
'is-floating-label': this.hasLabel && !this.horizontal && this.labelPosition === 'on-border'
}, this.numberInputClasses];
},
/**
* Correct Bulma class for the side of the addon or group.
*
* This is not kept like the others (is-small, etc.),
* because since 'has-addons' is set automatically it
* doesn't make sense to teach users what addons are exactly.
*/
newPosition: function newPosition() {
if (this.position === undefined) return;
var position = this.position.split('-');
if (position.length < 1) return;
var prefix = this.grouped ? 'is-grouped-' : 'has-addons-';
if (this.position) return prefix + position[1];
},
/**
* Formatted message in case it's an array
* (each element is separated by <br> tag)
*/
formattedMessage: function formattedMessage() {
if (typeof this.newMessage === 'string') {
return this.newMessage;
} else {
var messages = [];
if (Array.isArray(this.newMessage)) {
this.newMessage.forEach(function (message) {
if (typeof message === 'string') {
messages.push(message);
} else {
for (var key in message) {
if (message[key]) {
messages.push(key);
}
}
}
});
} else {
for (var key in this.newMessage) {
if (this.newMessage[key]) {
messages.push(key);
}
}
}
return messages.filter(function (m) {
if (m) return m;
}).join(' <br> ');
}
},
hasLabel: function hasLabel() {
return this.label || this.$slots.label;
},
numberInputClasses: function numberInputClasses() {
if (this.$slots.default) {
var numberinput = this.$slots.default.filter(function (node) {
return node.tag && node.tag.toLowerCase().indexOf('numberinput') >= 0;
})[0];
if (numberinput) {
var classes = ['has-numberinput'];
var controlsPosition = numberinput.componentOptions.propsData.controlsPosition;
var size = numberinput.componentOptions.propsData.size;
if (controlsPosition) {
classes.push("has-numberinput-".concat(controlsPosition));
}
if (size) {
classes.push("has-numberinput-".concat(size));
}
return classes;
}
}
return null;
}
},
watch: {
/**
* Set internal type when prop change.
*/
type: function type(value) {
this.newType = value;
},
/**
* Set internal message when prop change.
*/
message: function message(value) {
this.newMessage = value;
}
},
methods: {
/**
* Field has addons if there are more than one slot
* (element / component) in the Field.
* Or is grouped when prop is set.
* Is a method to be called when component re-render.
*/
fieldType: function fieldType() {
if (this.grouped) return 'is-grouped';
var renderedNode = 0;
if (this.$slots.default) {
renderedNode = this.$slots.default.reduce(function (i, node) {
return node.tag ? i + 1 : i;
}, 0);
}
if (renderedNode > 1 && this.addons && !this.horizontal) {
return 'has-addons';
}
}
},
mounted: function mounted() {
if (this.horizontal) {
// Bulma docs: .is-normal for any .input or .button
var elements = this.$el.querySelectorAll('.input, .select, .button, .textarea, .b-slider');
if (elements.length > 0) {
this.fieldLabelSize = 'is-normal';
}
}
}
};
/* script */
const __vue_script__$c = script$c;
/* template */
var __vue_render__$a = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"field",class:[_vm.rootClasses, _vm.fieldType()]},[(_vm.horizontal)?_c('div',{staticClass:"field-label",class:[_vm.customClass, _vm.fieldLabelSize]},[(_vm.hasLabel)?_c('label',{staticClass:"label",class:_vm.customClass,attrs:{"for":_vm.labelFor}},[(_vm.$slots.label)?_vm._t("label"):[_vm._v(_vm._s(_vm.label))]],2):_vm._e()]):[(_vm.hasLabel)?_c('label',{staticClass:"label",class:_vm.customClass,attrs:{"for":_vm.labelFor}},[(_vm.$slots.label)?_vm._t("label"):[_vm._v(_vm._s(_vm.label))]],2):_vm._e()],_vm._v(" "),(_vm.horizontal)?_c('b-field-body',{attrs:{"message":_vm.newMessage ? _vm.formattedMessage : '',"type":_vm.newType}},[_vm._t("default")],2):[_vm._t("default")],_vm._v(" "),(_vm.newMessage && !_vm.horizontal)?_c('p',{staticClass:"help",class:_vm.newType,domProps:{"innerHTML":_vm._s(_vm.formattedMessage)}}):_vm._e()],2)};
var __vue_staticRenderFns__$a = [];
/* style */
const __vue_inject_styles__$c = undefined;
/* scoped */
const __vue_scope_id__$c = undefined;
/* module identifier */
const __vue_module_identifier__$c = undefined;
/* functional template */
const __vue_is_functional_template__$c = false;
/* style inject */
/* style inject SSR */
var Field = normalizeComponent_1(
{ render: __vue_render__$a, staticRenderFns: __vue_staticRenderFns__$a },
__vue_inject_styles__$c,
__vue_script__$c,
__vue_scope_id__$c,
__vue_is_functional_template__$c,
__vue_module_identifier__$c,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// These should match the variables in clockpicker.scss
var indicatorSize = 40;
var paddingInner = 5;
var script$d = {
name: 'BClockpickerFace',
props: {
pickerSize: Number,
min: Number,
max: Number,
double: Boolean,
value: Number,
faceNumbers: Array,
disabledValues: Function
},
data: function data() {
return {
isDragging: false,
inputValue: this.value,
prevAngle: 720
};
},
computed: {
/**
* How many number indicators are shown on the face
*/
count: function count() {
return this.max - this.min + 1;
},
/**
* How many number indicators are shown per ring on the face
*/
countPerRing: function countPerRing() {
return this.double ? this.count / 2 : this.count;
},
/**
* Radius of the clock face
*/
radius: function radius() {
return this.pickerSize / 2;
},
/**
* Radius of the outer ring of number indicators
*/
outerRadius: function outerRadius() {
return this.radius - paddingInner - indicatorSize / 2;
},
/**
* Radius of the inner ring of number indicators
*/
innerRadius: function innerRadius() {
return Math.max(this.outerRadius * 0.6, this.outerRadius - paddingInner - indicatorSize); // 48px gives enough room for the outer ring of numbers
},
/**
* The angle for each selectable value
* For hours this ends up being 30 degrees, for minutes 6 degrees
*/
degreesPerUnit: function degreesPerUnit() {
return 360 / this.countPerRing;
},
/**
* Used for calculating x/y grid location based on degrees
*/
degrees: function degrees() {
return this.degreesPerUnit * Math.PI / 180;
},
/**
* Calculates the angle the clock hand should be rotated for the
* selected value
*/
handRotateAngle: function handRotateAngle() {
var currentAngle = this.prevAngle;
while (currentAngle < 0) {
currentAngle += 360;
}
var targetAngle = this.calcHandAngle(this.displayedValue);
var degreesDiff = this.shortestDistanceDegrees(currentAngle, targetAngle);
var angle = this.prevAngle + degreesDiff;
return angle;
},
/**
* Determines how long the selector hand is based on if the
* selected value is located along the outer or inner ring
*/
handScale: function handScale() {
return this.calcHandScale(this.displayedValue);
},
handStyle: function handStyle() {
return {
transform: "rotate(".concat(this.handRotateAngle, "deg) scaleY(").concat(this.handScale, ")"),
transition: '.3s cubic-bezier(.25,.8,.50,1)'
};
},
/**
* The value the hand should be pointing at
*/
displayedValue: function displayedValue() {
return this.inputValue == null ? this.min : this.inputValue;
}
},
watch: {
value: function value(_value) {
if (_value !== this.inputValue) {
this.prevAngle = this.handRotateAngle;
}
this.inputValue = _value;
}
},
methods: {
isDisabled: function isDisabled(value) {
return this.disabledValues && this.disabledValues(value);
},
/**
* Calculates the distance between two points
*/
euclidean: function euclidean(p0, p1) {
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
return Math.sqrt(dx * dx + dy * dy);
},
shortestDistanceDegrees: function shortestDistanceDegrees(start, stop) {
var modDiff = (stop - start) % 360;
var shortestDistance = 180 - Math.abs(Math.abs(modDiff) - 180);
return (modDiff + 360) % 360 < 180 ? shortestDistance * 1 : shortestDistance * -1;
},
/**
* Calculates the angle of the line from the center point
* to the given point.
*/
coordToAngle: function coordToAngle(center, p1) {
var value = 2 * Math.atan2(p1.y - center.y - this.euclidean(center, p1), p1.x - center.x);
return Math.abs(value * 180 / Math.PI);
},
/**
* Generates the inline style translate() property for a
* number indicator, which determines it's location on the
* clock face
*/
getNumberTranslate: function getNumberTranslate(value) {
var _this$getNumberCoords = this.getNumberCoords(value),
x = _this$getNumberCoords.x,
y = _this$getNumberCoords.y;
return "translate(".concat(x, "px, ").concat(y, "px)");
},
/***
* Calculates the coordinates on the clock face for a number
* indicator value
*/
getNumberCoords: function getNumberCoords(value) {
var radius = this.isInnerRing(value) ? this.innerRadius : this.outerRadius;
return {
x: Math.round(radius * Math.sin((value - this.min) * this.degrees)),
y: Math.round(-radius * Math.cos((value - this.min) * this.degrees))
};
},
getFaceNumberClasses: function getFaceNumberClasses(num) {
return {
'active': num.value === this.displayedValue,
'disabled': this.isDisabled(num.value)
};
},
/**
* Determines if a value resides on the inner ring
*/
isInnerRing: function isInnerRing(value) {
return this.double && value - this.min >= this.countPerRing;
},
calcHandAngle: function calcHandAngle(value) {
var angle = this.degreesPerUnit * (value - this.min);
if (this.isInnerRing(value)) angle -= 360;
return angle;
},
calcHandScale: function calcHandScale(value) {
return this.isInnerRing(value) ? this.innerRadius / this.outerRadius : 1;
},
onMouseDown: function onMouseDown(e) {
e.preventDefault();
this.isDragging = true;
this.onDragMove(e);
},
onMouseUp: function onMouseUp() {
this.isDragging = false;
if (!this.isDisabled(this.inputValue)) {
this.$emit('change', this.inputValue);
}
},
onDragMove: function onDragMove(e) {
e.preventDefault();
if (!this.isDragging && e.type !== 'click') return;
var _this$$refs$clock$get = this.$refs.clock.getBoundingClientRect(),
width = _this$$refs$clock$get.width,
top = _this$$refs$clock$get.top,
left = _this$$refs$clock$get.left;
var _ref = 'touches' in e ? e.touches[0] : e,
clientX = _ref.clientX,
clientY = _ref.clientY;
var center = {
x: width / 2,
y: -width / 2
};
var coords = {
x: clientX - left,
y: top - clientY
};
var handAngle = Math.round(this.coordToAngle(center, coords) + 360) % 360;
var insideClick = this.double && this.euclidean(center, coords) < (this.outerRadius + this.innerRadius) / 2 - 16;
var value = Math.round(handAngle / this.degreesPerUnit) + this.min + (insideClick ? this.countPerRing : 0); // Necessary to fix edge case when selecting left part of max value
if (handAngle >= 360 - this.degreesPerUnit / 2) {
value = insideClick ? this.max : this.min;
}
this.update(value);
},
update: function update(value) {
if (this.inputValue !== value && !this.isDisabled(value)) {
this.prevAngle = this.handRotateAngle;
this.inputValue = value;
this.$emit('input', value);
}
}
}
};
/* script */
const __vue_script__$d = script$d;
/* template */
var __vue_render__$b = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-clockpicker-face",on:{"mousedown":_vm.onMouseDown,"mouseup":_vm.onMouseUp,"mousemove":_vm.onDragMove,"touchstart":_vm.onMouseDown,"touchend":_vm.onMouseUp,"touchmove":_vm.onDragMove}},[_c('div',{ref:"clock",staticClass:"b-clockpicker-face-outer-ring"},[_c('div',{staticClass:"b-clockpicker-face-hand",style:(_vm.handStyle)}),_vm._v(" "),_vm._l((_vm.faceNumbers),function(num,index){return _c('span',{key:index,staticClass:"b-clockpicker-face-number",class:_vm.getFaceNumberClasses(num),style:({ transform: _vm.getNumberTranslate(num.value) })},[_c('span',[_vm._v(_vm._s(num.label))])])})],2)])};
var __vue_staticRenderFns__$b = [];
/* style */
const __vue_inject_styles__$d = undefined;
/* scoped */
const __vue_scope_id__$d = undefined;
/* module identifier */
const __vue_module_identifier__$d = undefined;
/* functional template */
const __vue_is_functional_template__$d = false;
/* style inject */
/* style inject SSR */
var ClockpickerFace = normalizeComponent_1(
{ render: __vue_render__$b, staticRenderFns: __vue_staticRenderFns__$b },
__vue_inject_styles__$d,
__vue_script__$d,
__vue_scope_id__$d,
__vue_is_functional_template__$d,
__vue_module_identifier__$d,
undefined,
undefined
);
var _components;
var outerPadding = 12;
var script$e = {
name: 'BClockpicker',
components: (_components = {}, _defineProperty(_components, ClockpickerFace.name, ClockpickerFace), _defineProperty(_components, Input.name, Input), _defineProperty(_components, Field.name, Field), _defineProperty(_components, Icon.name, Icon), _defineProperty(_components, Dropdown.name, Dropdown), _defineProperty(_components, DropdownItem.name, DropdownItem), _components),
mixins: [TimepickerMixin],
props: {
pickerSize: {
type: Number,
default: 290
},
hourFormat: {
type: String,
default: '12',
validator: function validator(value) {
return value === '24' || value === '12';
}
},
incrementMinutes: {
type: Number,
default: 5
},
autoSwitch: {
type: Boolean,
default: true
},
type: {
type: String,
default: 'is-primary'
},
hoursLabel: {
type: String,
default: function _default() {
return config.defaultClockpickerHoursLabel || 'Hours';
}
},
minutesLabel: {
type: String,
default: function _default() {
return config.defaultClockpickerMinutesLabel || 'Min';
}
}
},
data: function data() {
return {
isSelectingHour: true,
isDragging: false,
_isClockpicker: true
};
},
computed: {
hoursDisplay: function hoursDisplay() {
if (this.hoursSelected == null) return '--';
if (this.isHourFormat24) return this.pad(this.hoursSelected);
var display = this.hoursSelected;
if (this.meridienSelected === this.PM) display -= 12;
if (display === 0) display = 12;
return display;
},
minutesDisplay: function minutesDisplay() {
return this.minutesSelected == null ? '--' : this.pad(this.minutesSelected);
},
minFaceValue: function minFaceValue() {
return this.isSelectingHour && !this.isHourFormat24 && this.meridienSelected === this.PM ? 12 : 0;
},
maxFaceValue: function maxFaceValue() {
return this.isSelectingHour ? !this.isHourFormat24 && this.meridienSelected === this.AM ? 11 : 23 : 59;
},
faceSize: function faceSize() {
return this.pickerSize - outerPadding * 2;
},
faceDisabledValues: function faceDisabledValues() {
return this.isSelectingHour ? this.isHourDisabled : this.isMinuteDisabled;
}
},
methods: {
onClockInput: function onClockInput(value) {
if (this.isSelectingHour) {
this.hoursSelected = value;
this.onHoursChange(value);
} else {
this.minutesSelected = value;
this.onMinutesChange(value);
}
},
onClockChange: function onClockChange(value) {
if (this.autoSwitch && this.isSelectingHour) {
this.isSelectingHour = !this.isSelectingHour;
}
},
onMeridienClick: function onMeridienClick(value) {
if (this.meridienSelected !== value) {
this.meridienSelected = value;
this.onMeridienChange(value);
}
}
}
};
/* script */
const __vue_script__$e = script$e;
/* template */
var __vue_render__$c = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-clockpicker control",class:[_vm.size, _vm.type, {'is-expanded': _vm.expanded}]},[(!_vm.isMobile || _vm.inline)?_c('b-dropdown',{ref:"dropdown",attrs:{"position":_vm.position,"disabled":_vm.disabled,"inline":_vm.inline}},[(!_vm.inline)?_c('b-input',_vm._b({ref:"input",attrs:{"slot":"trigger","autocomplete":"off","value":_vm.formatValue(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"loading":_vm.loading,"disabled":_vm.disabled,"readonly":!_vm.editable,"rounded":_vm.rounded,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.handleOnFocus,"blur":function($event){_vm.onBlur() && _vm.checkHtml5Validity();}},nativeOn:{"click":function($event){$event.stopPropagation();return _vm.toggle(true)},"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.toggle(true)},"change":function($event){return _vm.onChangeNativePicker($event)}},slot:"trigger"},'b-input',_vm.$attrs,false)):_vm._e(),_vm._v(" "),_c('div',{staticClass:"card",attrs:{"disabled":_vm.disabled,"custom":""}},[(_vm.inline)?_c('header',{staticClass:"card-header"},[_c('div',{staticClass:"b-clockpicker-header card-header-title"},[_c('div',{staticClass:"b-clockpicker-time"},[_c('span',{staticClass:"b-clockpicker-btn",class:{ active: _vm.isSelectingHour },on:{"click":function($event){_vm.isSelectingHour = true;}}},[_vm._v(_vm._s(_vm.hoursDisplay))]),_vm._v(" "),_c('span',[_vm._v(":")]),_vm._v(" "),_c('span',{staticClass:"b-clockpicker-btn",class:{ active: !_vm.isSelectingHour },on:{"click":function($event){_vm.isSelectingHour = false;}}},[_vm._v(_vm._s(_vm.minutesDisplay))])]),_vm._v(" "),(!_vm.isHourFormat24)?_c('div',{staticClass:"b-clockpicker-period"},[_c('div',{staticClass:"b-clockpicker-btn",class:{ active: _vm.meridienSelected == _vm.AM },on:{"click":function($event){return _vm.onMeridienClick(_vm.AM)}}},[_vm._v("am")]),_vm._v(" "),_c('div',{staticClass:"b-clockpicker-btn",class:{ active: _vm.meridienSelected == _vm.PM },on:{"click":function($event){return _vm.onMeridienClick(_vm.PM)}}},[_vm._v("pm")])]):_vm._e()])]):_vm._e(),_vm._v(" "),_c('div',{staticClass:"card-content"},[_c('div',{staticClass:"b-clockpicker-body",style:({ width: _vm.faceSize + 'px', height: _vm.faceSize + 'px' })},[(!_vm.inline)?_c('div',{staticClass:"b-clockpicker-time"},[_c('div',{staticClass:"b-clockpicker-btn",class:{ active: _vm.isSelectingHour },on:{"click":function($event){_vm.isSelectingHour = true;}}},[_vm._v(_vm._s(_vm.hoursLabel))]),_vm._v(" "),_c('span',{staticClass:"b-clockpicker-btn",class:{ active: !_vm.isSelectingHour },on:{"click":function($event){_vm.isSelectingHour = false;}}},[_vm._v(_vm._s(_vm.minutesLabel))])]):_vm._e(),_vm._v(" "),(!_vm.isHourFormat24 && !_vm.inline)?_c('div',{staticClass:"b-clockpicker-period"},[_c('div',{staticClass:"b-clockpicker-btn",class:{ active: _vm.meridienSelected == _vm.AM },on:{"click":function($event){return _vm.onMeridienClick(_vm.AM)}}},[_vm._v(_vm._s(_vm.AM))]),_vm._v(" "),_c('div',{staticClass:"b-clockpicker-btn",class:{ active: _vm.meridienSelected == _vm.PM },on:{"click":function($event){return _vm.onMeridienClick(_vm.PM)}}},[_vm._v(_vm._s(_vm.PM))])]):_vm._e(),_vm._v(" "),_c('b-clockpicker-face',{attrs:{"picker-size":_vm.faceSize,"min":_vm.minFaceValue,"max":_vm.maxFaceValue,"face-numbers":_vm.isSelectingHour ? _vm.hours : _vm.minutes,"disabled-values":_vm.faceDisabledValues,"double":_vm.isSelectingHour && _vm.isHourFormat24,"value":_vm.isSelectingHour ? _vm.hoursSelected : _vm.minutesSelected},on:{"input":_vm.onClockInput,"change":_vm.onClockChange}})],1)]),_vm._v(" "),(_vm.$slots.default !== undefined && _vm.$slots.default.length)?_c('footer',{staticClass:"b-clockpicker-footer card-footer"},[_vm._t("default")],2):_vm._e()])],1):_c('b-input',_vm._b({ref:"input",attrs:{"type":"time","autocomplete":"off","value":_vm.formatHHMMSS(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"loading":_vm.loading,"max":_vm.formatHHMMSS(_vm.maxTime),"min":_vm.formatHHMMSS(_vm.minTime),"disabled":_vm.disabled,"readonly":false,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.handleOnFocus,"blur":function($event){_vm.onBlur() && _vm.checkHtml5Validity();}},nativeOn:{"click":function($event){$event.stopPropagation();return _vm.toggle(true)},"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.toggle(true)},"change":function($event){return _vm.onChangeNativePicker($event)}}},'b-input',_vm.$attrs,false))],1)};
var __vue_staticRenderFns__$c = [];
/* style */
const __vue_inject_styles__$e = undefined;
/* scoped */
const __vue_scope_id__$e = undefined;
/* module identifier */
const __vue_module_identifier__$e = undefined;
/* functional template */
const __vue_is_functional_template__$e = false;
/* style inject */
/* style inject SSR */
var Clockpicker = normalizeComponent_1(
{ render: __vue_render__$c, staticRenderFns: __vue_staticRenderFns__$c },
__vue_inject_styles__$e,
__vue_script__$e,
__vue_scope_id__$e,
__vue_is_functional_template__$e,
__vue_module_identifier__$e,
undefined,
undefined
);
var Plugin$5 = {
install: function install(Vue) {
registerComponent(Vue, Clockpicker);
}
};
use(Plugin$5);
var script$f = {
name: 'BSelect',
components: _defineProperty({}, Icon.name, Icon),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: {
type: [String, Number, Boolean, Object, Array, Function],
default: null
},
placeholder: String,
multiple: Boolean,
nativeSize: [String, Number]
},
data: function data() {
return {
selected: this.value,
_elementRef: 'select'
};
},
computed: {
computedValue: {
get: function get() {
return this.selected;
},
set: function set(value) {
this.selected = value;
this.$emit('input', value);
!this.isValid && this.checkHtml5Validity();
}
},
spanClasses: function spanClasses() {
return [this.size, this.statusType, {
'is-fullwidth': this.expanded,
'is-loading': this.loading,
'is-multiple': this.multiple,
'is-rounded': this.rounded,
'is-empty': this.selected === null
}];
}
},
watch: {
/**
* When v-model is changed:
* 1. Set the selected option.
* 2. If it's invalid, validate again.
*/
value: function value(_value) {
this.selected = _value;
!this.isValid && this.checkHtml5Validity();
}
}
};
/* script */
const __vue_script__$f = script$f;
/* template */
var __vue_render__$d = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"control",class:{ 'is-expanded': _vm.expanded, 'has-icons-left': _vm.icon }},[_c('span',{staticClass:"select",class:_vm.spanClasses},[_c('select',_vm._b({directives:[{name:"model",rawName:"v-model",value:(_vm.computedValue),expression:"computedValue"}],ref:"select",attrs:{"multiple":_vm.multiple,"size":_vm.nativeSize},on:{"blur":function($event){_vm.$emit('blur', $event) && _vm.checkHtml5Validity();},"focus":function($event){return _vm.$emit('focus', $event)},"change":function($event){var $$selectedVal = Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return val}); _vm.computedValue=$event.target.multiple ? $$selectedVal : $$selectedVal[0];}}},'select',_vm.$attrs,false),[(_vm.placeholder)?[(_vm.computedValue == null)?_c('option',{attrs:{"disabled":"","hidden":""},domProps:{"value":null}},[_vm._v("\n "+_vm._s(_vm.placeholder)+"\n ")]):_vm._e()]:_vm._e(),_vm._v(" "),_vm._t("default")],2)]),_vm._v(" "),(_vm.icon)?_c('b-icon',{staticClass:"is-left",attrs:{"icon":_vm.icon,"pack":_vm.iconPack,"size":_vm.iconSize}}):_vm._e()],1)};
var __vue_staticRenderFns__$d = [];
/* style */
const __vue_inject_styles__$f = undefined;
/* scoped */
const __vue_scope_id__$f = undefined;
/* module identifier */
const __vue_module_identifier__$f = undefined;
/* functional template */
const __vue_is_functional_template__$f = false;
/* style inject */
/* style inject SSR */
var Select = normalizeComponent_1(
{ render: __vue_render__$d, staticRenderFns: __vue_staticRenderFns__$d },
__vue_inject_styles__$f,
__vue_script__$f,
__vue_scope_id__$f,
__vue_is_functional_template__$f,
__vue_module_identifier__$f,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$g = {
name: 'BDatepickerTableRow',
props: {
selectedDate: {
type: [Date, Array]
},
hoveredDateRange: Array,
week: {
type: Array,
required: true
},
month: {
type: Number,
required: true
},
minDate: Date,
maxDate: Date,
disabled: Boolean,
unselectableDates: Array,
unselectableDaysOfWeek: Array,
selectableDates: Array,
events: Array,
indicators: String,
dateCreator: Function,
nearbyMonthDays: Boolean,
nearbySelectableMonthDays: Boolean,
showWeekNumber: {
type: Boolean,
default: function _default() {
return false;
}
},
range: Boolean,
multiple: Boolean,
rulesForFirstWeek: {
type: Number,
default: function _default() {
return 4;
}
},
firstDayOfWeek: Number
},
methods: {
firstWeekOffset: function firstWeekOffset(year, dow, doy) {
// first-week day -- which january is always in the first week (4 for iso, 1 for other)
var fwd = 7 + dow - doy; // first-week day local weekday -- which local weekday is fwd
var firstJanuary = new Date(year, 0, fwd);
var fwdlw = (7 + firstJanuary.getDay() - dow) % 7;
return -fwdlw + fwd - 1;
},
daysInYear: function daysInYear(year) {
return this.isLeapYear(year) ? 366 : 365;
},
isLeapYear: function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
},
getSetDayOfYear: function getSetDayOfYear(input) {
return Math.round((input - new Date(input.getFullYear(), 0, 1)) / 864e5) + 1;
},
weeksInYear: function weeksInYear(year, dow, doy) {
var weekOffset = this.firstWeekOffset(year, dow, doy);
var weekOffsetNext = this.firstWeekOffset(year + 1, dow, doy);
return (this.daysInYear(year) - weekOffset + weekOffsetNext) / 7;
},
getWeekNumber: function getWeekNumber(mom) {
var dow = this.firstDayOfWeek; // first day of week
// Rules for the first week : 1 for the 1st January, 4 for the 4th January
var doy = this.rulesForFirstWeek;
var weekOffset = this.firstWeekOffset(mom.getFullYear(), dow, doy);
var week = Math.floor((this.getSetDayOfYear(mom) - weekOffset - 1) / 7) + 1;
var resWeek;
var resYear;
if (week < 1) {
resYear = mom.getFullYear() - 1;
resWeek = week + this.weeksInYear(resYear, dow, doy);
} else if (week > this.weeksInYear(mom.getFullYear(), dow, doy)) {
resWeek = week - this.weeksInYear(mom.getFullYear(), dow, doy);
resYear = mom.getFullYear() + 1;
} else {
resYear = mom.getFullYear();
resWeek = week;
}
return resWeek;
},
/*
* Check that selected day is within earliest/latest params and
* is within this month
*/
selectableDate: function selectableDate(day) {
var validity = [];
if (this.minDate) {
validity.push(day >= this.minDate);
}
if (this.maxDate) {
validity.push(day <= this.maxDate);
}
if (this.nearbyMonthDays && !this.nearbySelectableMonthDays) {
validity.push(day.getMonth() === this.month);
}
if (this.selectableDates) {
for (var i = 0; i < this.selectableDates.length; i++) {
var enabledDate = this.selectableDates[i];
if (day.getDate() === enabledDate.getDate() && day.getFullYear() === enabledDate.getFullYear() && day.getMonth() === enabledDate.getMonth()) {
return true;
} else {
validity.push(false);
}
}
}
if (this.unselectableDates) {
for (var _i = 0; _i < this.unselectableDates.length; _i++) {
var disabledDate = this.unselectableDates[_i];
validity.push(day.getDate() !== disabledDate.getDate() || day.getFullYear() !== disabledDate.getFullYear() || day.getMonth() !== disabledDate.getMonth());
}
}
if (this.unselectableDaysOfWeek) {
for (var _i2 = 0; _i2 < this.unselectableDaysOfWeek.length; _i2++) {
var dayOfWeek = this.unselectableDaysOfWeek[_i2];
validity.push(day.getDay() !== dayOfWeek);
}
}
return validity.indexOf(false) < 0;
},
/*
* Emit select event with chosen date as payload
*/
emitChosenDate: function emitChosenDate(day) {
if (this.disabled) return;
if (this.selectableDate(day)) {
this.$emit('select', day);
}
},
eventsDateMatch: function eventsDateMatch(day) {
if (!this.events || !this.events.length) return false;
var dayEvents = [];
for (var i = 0; i < this.events.length; i++) {
if (this.events[i].date.getDay() === day.getDay()) {
dayEvents.push(this.events[i]);
}
}
if (!dayEvents.length) {
return false;
}
return dayEvents;
},
/*
* Build classObject for cell using validations
*/
classObject: function classObject(day) {
function dateMatch(dateOne, dateTwo, multiple) {
// if either date is null or undefined, return false
// if using multiple flag, return false
if (!dateOne || !dateTwo || multiple) {
return false;
}
if (Array.isArray(dateTwo)) {
return dateTwo.some(function (date) {
return dateOne.getDate() === date.getDate() && dateOne.getFullYear() === date.getFullYear() && dateOne.getMonth() === date.getMonth();
});
}
return dateOne.getDate() === dateTwo.getDate() && dateOne.getFullYear() === dateTwo.getFullYear() && dateOne.getMonth() === dateTwo.getMonth();
}
function dateWithin(dateOne, dates, multiple) {
if (!Array.isArray(dates) || multiple) {
return false;
}
return dateOne > dates[0] && dateOne < dates[1];
}
return {
'is-selected': dateMatch(day, this.selectedDate) || dateWithin(day, this.selectedDate, this.multiple),
'is-first-selected': dateMatch(day, Array.isArray(this.selectedDate) && this.selectedDate[0], this.multiple),
'is-within-selected': dateWithin(day, this.selectedDate, this.multiple),
'is-last-selected': dateMatch(day, Array.isArray(this.selectedDate) && this.selectedDate[1], this.multiple),
'is-within-hovered-range': this.hoveredDateRange && this.hoveredDateRange.length === 2 && (dateMatch(day, this.hoveredDateRange) || dateWithin(day, this.hoveredDateRange)),
'is-first-hovered': dateMatch(day, Array.isArray(this.hoveredDateRange) && this.hoveredDateRange[0]),
'is-within-hovered': dateWithin(day, this.hoveredDateRange),
'is-last-hovered': dateMatch(day, Array.isArray(this.hoveredDateRange) && this.hoveredDateRange[1]),
'is-today': dateMatch(day, this.dateCreator()),
'is-selectable': this.selectableDate(day) && !this.disabled,
'is-unselectable': !this.selectableDate(day) || this.disabled,
'is-invisible': !this.nearbyMonthDays && day.getMonth() !== this.month,
'is-nearby': this.nearbySelectableMonthDays && day.getMonth() !== this.month
};
},
setRangeHoverEndDate: function setRangeHoverEndDate(day) {
if (this.range) {
this.$emit('rangeHoverEndDate', day);
}
}
}
};
/* script */
const __vue_script__$g = script$g;
/* template */
var __vue_render__$e = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"datepicker-row"},[(_vm.showWeekNumber)?_c('a',{staticClass:"datepicker-cell is-week-number"},[_vm._v("\n "+_vm._s(_vm.getWeekNumber(_vm.week[6]))+"\n ")]):_vm._e(),_vm._v(" "),_vm._l((_vm.week),function(day,index){return [(_vm.selectableDate(day) && !_vm.disabled)?_c('a',{key:index,staticClass:"datepicker-cell",class:[_vm.classObject(day), {'has-event': _vm.eventsDateMatch(day)}, _vm.indicators],attrs:{"role":"button","href":"#","disabled":_vm.disabled},on:{"click":function($event){$event.preventDefault();return _vm.emitChosenDate(day)},"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.emitChosenDate(day)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"space",32,$event.key,[" ","Spacebar"])){ return null; }$event.preventDefault();return _vm.emitChosenDate(day)}],"mouseenter":function($event){return _vm.setRangeHoverEndDate(day)}}},[_vm._v("\n "+_vm._s(day.getDate())+"\n "),(_vm.eventsDateMatch(day))?_c('div',{staticClass:"events"},_vm._l((_vm.eventsDateMatch(day)),function(event,index){return _c('div',{key:index,staticClass:"event",class:event.type})}),0):_vm._e()]):_c('div',{key:index,staticClass:"datepicker-cell",class:_vm.classObject(day)},[_vm._v("\n "+_vm._s(day.getDate())+"\n ")])]})],2)};
var __vue_staticRenderFns__$e = [];
/* style */
const __vue_inject_styles__$g = undefined;
/* scoped */
const __vue_scope_id__$g = undefined;
/* module identifier */
const __vue_module_identifier__$g = undefined;
/* functional template */
const __vue_is_functional_template__$g = false;
/* style inject */
/* style inject SSR */
var DatepickerTableRow = normalizeComponent_1(
{ render: __vue_render__$e, staticRenderFns: __vue_staticRenderFns__$e },
__vue_inject_styles__$g,
__vue_script__$g,
__vue_scope_id__$g,
__vue_is_functional_template__$g,
__vue_module_identifier__$g,
undefined,
undefined
);
var isDefined = function isDefined(d) {
return d !== undefined;
};
var script$h = {
name: 'BDatepickerTable',
components: _defineProperty({}, DatepickerTableRow.name, DatepickerTableRow),
props: {
value: {
type: [Date, Array]
},
dayNames: Array,
monthNames: Array,
firstDayOfWeek: Number,
events: Array,
indicators: String,
minDate: Date,
maxDate: Date,
focused: Object,
disabled: Boolean,
dateCreator: Function,
unselectableDates: Array,
unselectableDaysOfWeek: Array,
selectableDates: Array,
nearbyMonthDays: Boolean,
nearbySelectableMonthDays: Boolean,
showWeekNumber: {
type: Boolean,
default: function _default() {
return false;
}
},
rulesForFirstWeek: {
type: Number,
default: function _default() {
return 4;
}
},
range: Boolean,
multiple: Boolean
},
data: function data() {
return {
selectedBeginDate: undefined,
selectedEndDate: undefined,
hoveredEndDate: undefined,
multipleSelectedDates: []
};
},
computed: {
visibleDayNames: function visibleDayNames() {
var visibleDayNames = [];
var index = this.firstDayOfWeek;
while (visibleDayNames.length < this.dayNames.length) {
var currentDayName = this.dayNames[index % this.dayNames.length];
visibleDayNames.push(currentDayName);
index++;
}
if (this.showWeekNumber) visibleDayNames.unshift('');
return visibleDayNames;
},
hasEvents: function hasEvents() {
return this.events && this.events.length;
},
/*
* Return array of all events in the specified month
*/
eventsInThisMonth: function eventsInThisMonth() {
if (!this.events) return [];
var monthEvents = [];
for (var i = 0; i < this.events.length; i++) {
var event = this.events[i];
if (!event.hasOwnProperty('date')) {
event = {
date: event
};
}
if (!event.hasOwnProperty('type')) {
event.type = 'is-primary';
}
if (event.date.getMonth() === this.focused.month && event.date.getFullYear() === this.focused.year) {
monthEvents.push(event);
}
}
return monthEvents;
},
/*
* Return array of all weeks in the specified month
*/
weeksInThisMonth: function weeksInThisMonth() {
var month = this.focused.month;
var year = this.focused.year;
var weeksInThisMonth = [];
var startingDay = 1;
while (weeksInThisMonth.length < 6) {
var newWeek = this.weekBuilder(startingDay, month, year);
weeksInThisMonth.push(newWeek);
startingDay += 7;
}
return weeksInThisMonth;
},
hoveredDateRange: function hoveredDateRange() {
if (!this.range) {
return [];
}
if (!isNaN(this.selectedEndDate)) {
return [];
}
if (this.hoveredEndDate < this.selectedBeginDate) {
return [this.hoveredEndDate, this.selectedBeginDate].filter(isDefined);
}
return [this.selectedBeginDate, this.hoveredEndDate].filter(isDefined);
}
},
methods: {
/*
* Emit input event with selected date as payload for v-model in parent
*/
updateSelectedDate: function updateSelectedDate(date) {
if (!this.range && !this.multiple) {
this.$emit('input', date);
} else if (this.range) {
this.handleSelectRangeDate(date);
} else if (this.multiple) {
this.handleSelectMultipleDates(date);
}
},
/*
* If both begin and end dates are set, reset the end date and set the begin date.
* If only begin date is selected, emit an array of the begin date and the new date.
* If not set, only set the begin date.
*/
handleSelectRangeDate: function handleSelectRangeDate(date) {
if (this.selectedBeginDate && this.selectedEndDate) {
this.selectedBeginDate = date;
this.selectedEndDate = undefined;
} else if (this.selectedBeginDate && !this.selectedEndDate) {
if (this.selectedBeginDate > date) {
this.selectedEndDate = this.selectedBeginDate;
this.selectedBeginDate = date;
} else {
this.selectedEndDate = date;
}
this.$emit('input', [this.selectedBeginDate, this.selectedEndDate]);
} else {
this.selectedBeginDate = date;
}
},
/*
* If selected date already exists list of selected dates, remove it from the list
* Otherwise, add date to list of selected dates
*/
handleSelectMultipleDates: function handleSelectMultipleDates(date) {
var multipleSelect = this.multipleSelectedDates.filter(function (selectedDate) {
return selectedDate.getTime() === date.getTime();
});
if (multipleSelect) {
this.multipleSelectedDates = this.multipleSelectedDates.filter(function (selectedDate) {
return selectedDate.getTime() !== date.getTime();
});
} else {
this.multipleSelectedDates.push(date);
}
this.$emit('input', this.multipleSelectedDates);
},
/*
* Return array of all days in the week that the startingDate is within
*/
weekBuilder: function weekBuilder(startingDate, month, year) {
var thisMonth = new Date(year, month);
var thisWeek = [];
var dayOfWeek = new Date(year, month, startingDate).getDay();
var end = dayOfWeek >= this.firstDayOfWeek ? dayOfWeek - this.firstDayOfWeek : 7 - this.firstDayOfWeek + dayOfWeek;
var daysAgo = 1;
for (var i = 0; i < end; i++) {
thisWeek.unshift(new Date(thisMonth.getFullYear(), thisMonth.getMonth(), startingDate - daysAgo));
daysAgo++;
}
thisWeek.push(new Date(year, month, startingDate));
var daysForward = 1;
while (thisWeek.length < 7) {
thisWeek.push(new Date(year, month, startingDate + daysForward));
daysForward++;
}
return thisWeek;
},
eventsInThisWeek: function eventsInThisWeek(week) {
return this.eventsInThisMonth.filter(function (event) {
var stripped = new Date(Date.parse(event.date));
stripped.setHours(0, 0, 0, 0);
var timed = stripped.getTime();
return week.some(function (weekDate) {
return weekDate.getTime() === timed;
});
});
},
setRangeHoverEndDate: function setRangeHoverEndDate(day) {
this.hoveredEndDate = day;
}
}
};
/* script */
const __vue_script__$h = script$h;
/* template */
var __vue_render__$f = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('section',{staticClass:"datepicker-table"},[_c('header',{staticClass:"datepicker-header"},_vm._l((_vm.visibleDayNames),function(day,index){return _c('div',{key:index,staticClass:"datepicker-cell"},[_vm._v("\n "+_vm._s(day)+"\n ")])}),0),_vm._v(" "),_c('div',{staticClass:"datepicker-body",class:{'has-events':_vm.hasEvents}},_vm._l((_vm.weeksInThisMonth),function(week,index){return _c('b-datepicker-table-row',{key:index,attrs:{"selected-date":_vm.value,"week":week,"month":_vm.focused.month,"min-date":_vm.minDate,"max-date":_vm.maxDate,"disabled":_vm.disabled,"unselectable-dates":_vm.unselectableDates,"unselectable-days-of-week":_vm.unselectableDaysOfWeek,"selectable-dates":_vm.selectableDates,"events":_vm.eventsInThisWeek(week),"indicators":_vm.indicators,"date-creator":_vm.dateCreator,"nearby-month-days":_vm.nearbyMonthDays,"nearby-selectable-month-days":_vm.nearbySelectableMonthDays,"show-week-number":_vm.showWeekNumber,"first-day-of-week":_vm.firstDayOfWeek,"rules-for-first-week":_vm.rulesForFirstWeek,"range":_vm.range,"hovered-date-range":_vm.hoveredDateRange,"multiple":_vm.multiple},on:{"select":_vm.updateSelectedDate,"rangeHoverEndDate":_vm.setRangeHoverEndDate}})}),1)])};
var __vue_staticRenderFns__$f = [];
/* style */
const __vue_inject_styles__$h = undefined;
/* scoped */
const __vue_scope_id__$h = undefined;
/* module identifier */
const __vue_module_identifier__$h = undefined;
/* functional template */
const __vue_is_functional_template__$h = false;
/* style inject */
/* style inject SSR */
var DatepickerTable = normalizeComponent_1(
{ render: __vue_render__$f, staticRenderFns: __vue_staticRenderFns__$f },
__vue_inject_styles__$h,
__vue_script__$h,
__vue_scope_id__$h,
__vue_is_functional_template__$h,
__vue_module_identifier__$h,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$i = {
name: 'BDatepickerMonth',
props: {
value: {
type: [Date, Array]
},
monthNames: Array,
events: Array,
indicators: String,
minDate: Date,
maxDate: Date,
focused: Object,
disabled: Boolean,
dateCreator: Function,
unselectableDates: Array,
unselectableDaysOfWeek: Array,
selectableDates: Array,
multiple: Boolean
},
data: function data() {
return {
multipleSelectedDates: []
};
},
computed: {
hasEvents: function hasEvents() {
return this.events && this.events.length;
},
/*
* Return array of all events in the specified month
*/
eventsInThisYear: function eventsInThisYear() {
if (!this.events) return [];
var yearEvents = [];
for (var i = 0; i < this.events.length; i++) {
var event = this.events[i];
if (!event.hasOwnProperty('date')) {
event = {
date: event
};
}
if (!event.hasOwnProperty('type')) {
event.type = 'is-primary';
}
if (event.date.getFullYear() === this.focused.year) {
yearEvents.push(event);
}
}
return yearEvents;
},
monthDates: function monthDates() {
var year = this.focused.year;
var months = [];
for (var i = 0; i < 12; i++) {
var d = new Date(year, i, 1);
d.setHours(0, 0, 0, 0);
months.push(d);
}
return months;
}
},
methods: {
selectMultipleDates: function selectMultipleDates(date) {
var multipleSelct = this.multipleSelectedDates.find(function (selectedDate) {
return selectedDate.getTime() === date.getTime();
});
if (multipleSelct) {
this.multipleSelectedDates = this.multipleSelectedDates.filter(function (selectedDate) {
return selectedDate.getTime() !== date.getTime();
});
} else {
this.multipleSelectedDates.push(date);
}
this.$emit('input', this.multipleSelectedDates);
},
selectableDate: function selectableDate(day) {
var validity = [];
if (this.minDate) {
validity.push(day >= this.minDate);
}
if (this.maxDate) {
validity.push(day <= this.maxDate);
}
validity.push(day.getFullYear() === this.focused.year);
if (this.selectableDates) {
for (var i = 0; i < this.selectableDates.length; i++) {
var enabledDate = this.selectableDates[i];
if (day.getFullYear() === enabledDate.getFullYear() && day.getMonth() === enabledDate.getMonth()) {
return true;
} else {
validity.push(false);
}
}
}
if (this.unselectableDates) {
for (var _i = 0; _i < this.unselectableDates.length; _i++) {
var disabledDate = this.unselectableDates[_i];
validity.push(day.getFullYear() !== disabledDate.getFullYear() || day.getMonth() !== disabledDate.getMonth());
}
}
if (this.unselectableDaysOfWeek) {
for (var _i2 = 0; _i2 < this.unselectableDaysOfWeek.length; _i2++) {
var dayOfWeek = this.unselectableDaysOfWeek[_i2];
validity.push(day.getDay() !== dayOfWeek);
}
}
return validity.indexOf(false) < 0;
},
eventsDateMatch: function eventsDateMatch(day) {
if (!this.eventsInThisYear.length) return false;
var monthEvents = [];
for (var i = 0; i < this.eventsInThisYear.length; i++) {
if (this.eventsInThisYear[i].date.getMonth() === day.getMonth()) {
monthEvents.push(this.events[i]);
}
}
if (!monthEvents.length) {
return false;
}
return monthEvents;
},
/*
* Build classObject for cell using validations
*/
classObject: function classObject(day) {
function dateMatch(dateOne, dateTwo, multiple) {
// if either date is null or undefined, return false
if (!dateOne || !dateTwo || multiple) {
return false;
}
return dateOne.getFullYear() === dateTwo.getFullYear() && dateOne.getMonth() === dateTwo.getMonth();
}
function dateMultipleSelected(dateOne, dates, multiple) {
if (!Array.isArray(dates) || !multiple) {
return false;
}
return dates.some(function (date) {
return dateOne.getDate() === date.getDate() && dateOne.getFullYear() === date.getFullYear() && dateOne.getMonth() === date.getMonth();
});
}
return {
'is-selected': dateMatch(day, this.value, this.multiple) || dateMultipleSelected(day, this.multipleSelectedDates, this.multiple),
'is-today': dateMatch(day, this.dateCreator()),
'is-selectable': this.selectableDate(day) && !this.disabled,
'is-unselectable': !this.selectableDate(day) || this.disabled
};
},
/*
* Emit select event with chosen date as payload
*/
emitChosenDate: function emitChosenDate(day) {
if (this.disabled) return;
if (!this.multiple) {
if (this.selectableDate(day)) {
this.$emit('input', day);
}
} else {
this.selectMultipleDates(day);
}
}
}
};
/* script */
const __vue_script__$i = script$i;
/* template */
var __vue_render__$g = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('section',{staticClass:"datepicker-table"},[_c('div',{staticClass:"datepicker-body",class:{'has-events':_vm.hasEvents}},[_c('div',{staticClass:"datepicker-months"},[_vm._l((_vm.monthDates),function(date,index){return [(_vm.selectableDate(date) && !_vm.disabled)?_c('a',{key:index,staticClass:"datepicker-cell",class:[
_vm.classObject(date),
{'has-event': _vm.eventsDateMatch(date)},
_vm.indicators
],attrs:{"role":"button","href":"#","disabled":_vm.disabled},on:{"click":function($event){$event.preventDefault();return _vm.emitChosenDate(date)},"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.emitChosenDate(date)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"space",32,$event.key,[" ","Spacebar"])){ return null; }$event.preventDefault();return _vm.emitChosenDate(date)}]}},[_vm._v("\n "+_vm._s(_vm.monthNames[date.getMonth()])+"\n "),(_vm.eventsDateMatch(date))?_c('div',{staticClass:"events"},_vm._l((_vm.eventsDateMatch(date)),function(event,index){return _c('div',{key:index,staticClass:"event",class:event.type})}),0):_vm._e()]):_c('div',{key:index,staticClass:"datepicker-cell",class:_vm.classObject(date)},[_vm._v("\n "+_vm._s(_vm.monthNames[date.getMonth()])+"\n ")])]})],2)])])};
var __vue_staticRenderFns__$g = [];
/* style */
const __vue_inject_styles__$i = undefined;
/* scoped */
const __vue_scope_id__$i = undefined;
/* module identifier */
const __vue_module_identifier__$i = undefined;
/* functional template */
const __vue_is_functional_template__$i = false;
/* style inject */
/* style inject SSR */
var DatepickerMonth = normalizeComponent_1(
{ render: __vue_render__$g, staticRenderFns: __vue_staticRenderFns__$g },
__vue_inject_styles__$i,
__vue_script__$i,
__vue_scope_id__$i,
__vue_is_functional_template__$i,
__vue_module_identifier__$i,
undefined,
undefined
);
var _components$1;
var defaultDateFormatter = function defaultDateFormatter(date, vm) {
var targetDates = Array.isArray(date) ? date : [date];
var dates = targetDates.map(function (date) {
var yyyyMMdd = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
var d = new Date(yyyyMMdd);
return !vm.isTypeMonth ? d.toLocaleDateString() : d.toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit'
});
});
return !vm.multiple ? dates.join(' - ') : dates.join(', ');
};
var defaultDateParser = function defaultDateParser(date, vm) {
if (!vm.isTypeMonth) return new Date(Date.parse(date));
if (date) {
var s = date.split('/');
var year = s[0].length === 4 ? s[0] : s[1];
var month = s[0].length === 2 ? s[0] : s[1];
if (year && month) {
return new Date(parseInt(year, 10), parseInt(month - 1, 10), 1, 0, 0, 0, 0);
}
}
return null;
};
var script$j = {
name: 'BDatepicker',
components: (_components$1 = {}, _defineProperty(_components$1, DatepickerTable.name, DatepickerTable), _defineProperty(_components$1, DatepickerMonth.name, DatepickerMonth), _defineProperty(_components$1, Input.name, Input), _defineProperty(_components$1, Field.name, Field), _defineProperty(_components$1, Select.name, Select), _defineProperty(_components$1, Icon.name, Icon), _defineProperty(_components$1, Dropdown.name, Dropdown), _defineProperty(_components$1, DropdownItem.name, DropdownItem), _components$1),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: {
type: [Date, Array]
},
dayNames: {
type: Array,
default: function _default() {
if (Array.isArray(config.defaultDayNames)) {
return config.defaultDayNames;
} else {
return ['Su', 'M', 'Tu', 'W', 'Th', 'F', 'S'];
}
}
},
monthNames: {
type: Array,
default: function _default() {
if (Array.isArray(config.defaultMonthNames)) {
return config.defaultMonthNames;
} else {
return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
}
}
},
firstDayOfWeek: {
type: Number,
default: function _default() {
if (typeof config.defaultFirstDayOfWeek === 'number') {
return config.defaultFirstDayOfWeek;
} else {
return 0;
}
}
},
inline: Boolean,
minDate: Date,
maxDate: Date,
focusedDate: Date,
placeholder: String,
editable: Boolean,
disabled: Boolean,
unselectableDates: Array,
unselectableDaysOfWeek: {
type: Array,
default: function _default() {
return config.defaultUnselectableDaysOfWeek;
}
},
selectableDates: Array,
dateFormatter: {
type: Function,
default: function _default(date, vm) {
if (typeof config.defaultDateFormatter === 'function') {
return config.defaultDateFormatter(date);
} else {
return defaultDateFormatter(date, vm);
}
}
},
dateParser: {
type: Function,
default: function _default(date, vm) {
if (typeof config.defaultDateParser === 'function') {
return config.defaultDateParser(date);
} else {
return defaultDateParser(date, vm);
}
}
},
dateCreator: {
type: Function,
default: function _default() {
if (typeof config.defaultDateCreator === 'function') {
return config.defaultDateCreator();
} else {
return new Date();
}
}
},
mobileNative: {
type: Boolean,
default: function _default() {
return config.defaultDatepickerMobileNative;
}
},
position: String,
events: Array,
indicators: {
type: String,
default: 'dots'
},
openOnFocus: Boolean,
iconPrev: {
type: String,
default: config.defaultIconPrev
},
iconNext: {
type: String,
default: config.defaultIconNext
},
yearsRange: {
type: Array,
default: function _default() {
return config.defaultDatepickerYearsRange;
}
},
type: {
type: String,
validator: function validator(value) {
return ['month'].indexOf(value) >= 0;
}
},
nearbyMonthDays: {
type: Boolean,
default: function _default() {
return config.defaultDatepickerNearbyMonthDays;
}
},
nearbySelectableMonthDays: {
type: Boolean,
default: function _default() {
return config.defaultDatepickerNearbySelectableMonthDays;
}
},
showWeekNumber: {
type: Boolean,
default: function _default() {
return config.defaultDatepickerShowWeekNumber;
}
},
rulesForFirstWeek: {
type: Number,
default: function _default() {
return 4;
}
},
range: {
type: Boolean,
default: false
},
closeOnClick: {
type: Boolean,
default: true
},
multiple: {
type: Boolean,
default: false
},
mobileModal: {
type: Boolean,
default: function _default() {
return config.defaultDatepickerMobileModal;
}
}
},
data: function data() {
var focusedDate = (Array.isArray(this.value) ? this.value[0] : this.value) || this.focusedDate || this.dateCreator();
return {
dateSelected: this.value,
focusedDateData: {
month: focusedDate.getMonth(),
year: focusedDate.getFullYear()
},
_elementRef: 'input',
_isDatepicker: true
};
},
computed: {
computedValue: {
get: function get() {
return this.dateSelected;
},
set: function set(value) {
this.updateInternalState(value);
if (!this.multiple) this.togglePicker(false);
this.$emit('input', value);
}
},
/*
* Returns an array of years for the year dropdown. If earliest/latest
* dates are set by props, range of years will fall within those dates.
*/
listOfYears: function listOfYears() {
var latestYear = this.focusedDateData.year + this.yearsRange[1];
if (this.maxDate && this.maxDate.getFullYear() < latestYear) {
latestYear = Math.max(this.maxDate.getFullYear(), this.focusedDateData.year);
}
var earliestYear = this.focusedDateData.year + this.yearsRange[0];
if (this.minDate && this.minDate.getFullYear() > earliestYear) {
earliestYear = Math.min(this.minDate.getFullYear(), this.focusedDateData.year);
}
var arrayOfYears = [];
for (var i = earliestYear; i <= latestYear; i++) {
arrayOfYears.push(i);
}
return arrayOfYears.reverse();
},
showPrev: function showPrev() {
if (!this.minDate) return false;
if (this.isTypeMonth) {
return this.focusedDateData.year <= this.minDate.getFullYear();
}
var dateToCheck = new Date(this.focusedDateData.year, this.focusedDateData.month);
var date = new Date(this.minDate.getFullYear(), this.minDate.getMonth());
return dateToCheck <= date;
},
showNext: function showNext() {
if (!this.maxDate) return false;
if (this.isTypeMonth) {
return this.focusedDateData.year >= this.maxDate.getFullYear();
}
var dateToCheck = new Date(this.focusedDateData.year, this.focusedDateData.month);
var date = new Date(this.maxDate.getFullYear(), this.maxDate.getMonth());
return dateToCheck >= date;
},
isMobile: function isMobile$1() {
return this.mobileNative && isMobile.any();
},
isTypeMonth: function isTypeMonth() {
return this.type === 'month';
}
},
watch: {
/**
* When v-model is changed:
* 1. Update internal value.
* 2. If it's invalid, validate again.
*/
value: function value(_value) {
this.updateInternalState(_value);
if (!this.multiple) this.togglePicker(false);
!this.isValid && this.$refs.input.checkHtml5Validity();
},
focusedDate: function focusedDate(value) {
if (value) {
this.focusedDateData = {
month: value.getMonth(),
year: value.getFullYear()
};
}
},
/*
* Emit input event on month and/or year change
*/
'focusedDateData.month': function focusedDateDataMonth(value) {
this.$emit('change-month', value);
},
'focusedDateData.year': function focusedDateDataYear(value) {
this.$emit('change-year', value);
}
},
methods: {
/*
* Parse string into date
*/
onChange: function onChange(value) {
var date = this.dateParser(value, this);
if (date && (!isNaN(date) || Array.isArray(date) && date.length === 2 && !isNaN(date[0]) && !isNaN(date[1]))) {
this.computedValue = date;
} else {
// Force refresh input value when not valid date
this.computedValue = null;
this.$refs.input.newValue = this.computedValue;
}
},
/*
* Format date into string
*/
formatValue: function formatValue(value) {
if (Array.isArray(value)) {
var isArrayWithValidDates = Array.isArray(value) && value.every(function (v) {
return !isNaN(v);
});
return isArrayWithValidDates ? this.dateFormatter(value, this) : null;
}
return value && !isNaN(value) ? this.dateFormatter(value, this) : null;
},
/*
* Either decrement month by 1 if not January or decrement year by 1
* and set month to 11 (December) or decrement year when 'month'
*/
prev: function prev() {
if (this.disabled) return;
if (this.isTypeMonth) {
this.focusedDateData.year -= 1;
} else {
if (this.focusedDateData.month > 0) {
this.focusedDateData.month -= 1;
} else {
this.focusedDateData.month = 11;
this.focusedDateData.year -= 1;
}
}
},
/*
* Either increment month by 1 if not December or increment year by 1
* and set month to 0 (January) or increment year when 'month'
*/
next: function next() {
if (this.disabled) return;
if (this.isTypeMonth) {
this.focusedDateData.year += 1;
} else {
if (this.focusedDateData.month < 11) {
this.focusedDateData.month += 1;
} else {
this.focusedDateData.month = 0;
this.focusedDateData.year += 1;
}
}
},
formatNative: function formatNative(value) {
return this.isTypeMonth ? this.formatYYYYMM(value) : this.formatYYYYMMDD(value);
},
/*
* Format date into string 'YYYY-MM-DD'
*/
formatYYYYMMDD: function formatYYYYMMDD(value) {
var date = new Date(value);
if (value && !isNaN(date)) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return year + '-' + ((month < 10 ? '0' : '') + month) + '-' + ((day < 10 ? '0' : '') + day);
}
return '';
},
/*
* Format date into string 'YYYY-MM'
*/
formatYYYYMM: function formatYYYYMM(value) {
var date = new Date(value);
if (value && !isNaN(date)) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
return year + '-' + ((month < 10 ? '0' : '') + month);
}
return '';
},
/*
* Parse date from string
*/
onChangeNativePicker: function onChangeNativePicker(event) {
var date = event.target.value;
this.computedValue = date ? new Date(date + 'T00:00:00') : null;
},
updateInternalState: function updateInternalState(value) {
var currentDate = Array.isArray(value) ? !value.length ? this.dateCreator() : value[0] : !value ? this.dateCreator() : value;
this.focusedDateData = {
month: currentDate.getMonth(),
year: currentDate.getFullYear()
};
this.dateSelected = value;
},
/*
* Toggle datepicker
*/
togglePicker: function togglePicker(active) {
if (this.$refs.dropdown) {
if (this.closeOnClick) {
this.$refs.dropdown.isActive = typeof active === 'boolean' ? active : !this.$refs.dropdown.isActive;
}
}
},
/*
* Call default onFocus method and show datepicker
*/
handleOnFocus: function handleOnFocus(event) {
this.onFocus(event);
if (this.openOnFocus) {
this.togglePicker(true);
}
},
/*
* Toggle dropdown
*/
toggle: function toggle() {
if (this.mobileNative && this.isMobile) {
var input = this.$refs.input.$refs.input;
input.focus();
input.click();
return;
}
this.$refs.dropdown.toggle();
},
/*
* Avoid dropdown toggle when is already visible
*/
onInputClick: function onInputClick(event) {
if (this.$refs.dropdown.isActive) {
event.stopPropagation();
}
},
/**
* Keypress event that is bound to the document.
*/
keyPress: function keyPress(event) {
// Esc key
if (this.$refs.dropdown && this.$refs.dropdown.isActive && event.keyCode === 27) {
this.togglePicker(false);
}
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('keyup', this.keyPress);
}
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('keyup', this.keyPress);
}
}
};
/* script */
const __vue_script__$j = script$j;
/* template */
var __vue_render__$h = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"datepicker control",class:[_vm.size, {'is-expanded': _vm.expanded}]},[(!_vm.isMobile || _vm.inline)?_c('b-dropdown',{ref:"dropdown",attrs:{"position":_vm.position,"disabled":_vm.disabled,"inline":_vm.inline,"mobile-modal":_vm.mobileModal}},[(!_vm.inline)?_c('b-input',_vm._b({ref:"input",attrs:{"slot":"trigger","autocomplete":"off","value":_vm.formatValue(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"rounded":_vm.rounded,"loading":_vm.loading,"disabled":_vm.disabled,"readonly":!_vm.editable,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.handleOnFocus,"blur":_vm.onBlur},nativeOn:{"click":function($event){return _vm.onInputClick($event)},"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.togglePicker(true)},"change":function($event){return _vm.onChange($event.target.value)}},slot:"trigger"},'b-input',_vm.$attrs,false)):_vm._e(),_vm._v(" "),_c('b-dropdown-item',{attrs:{"disabled":_vm.disabled,"custom":""}},[_c('header',{staticClass:"datepicker-header"},[(_vm.$slots.header !== undefined && _vm.$slots.header.length)?[_vm._t("header")]:_c('div',{staticClass:"pagination field is-centered",class:_vm.size},[_c('a',{directives:[{name:"show",rawName:"v-show",value:(!_vm.showPrev && !_vm.disabled),expression:"!showPrev && !disabled"}],staticClass:"pagination-previous",attrs:{"role":"button","href":"#","disabled":_vm.disabled},on:{"click":function($event){$event.preventDefault();return _vm.prev($event)},"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.prev($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"space",32,$event.key,[" ","Spacebar"])){ return null; }$event.preventDefault();return _vm.prev($event)}]}},[_c('b-icon',{attrs:{"icon":_vm.iconPrev,"pack":_vm.iconPack,"both":"","type":"is-primary is-clickable"}})],1),_vm._v(" "),_c('a',{directives:[{name:"show",rawName:"v-show",value:(!_vm.showNext && !_vm.disabled),expression:"!showNext && !disabled"}],staticClass:"pagination-next",attrs:{"role":"button","href":"#","disabled":_vm.disabled},on:{"click":function($event){$event.preventDefault();return _vm.next($event)},"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.next($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"space",32,$event.key,[" ","Spacebar"])){ return null; }$event.preventDefault();return _vm.next($event)}]}},[_c('b-icon',{attrs:{"icon":_vm.iconNext,"pack":_vm.iconPack,"both":"","type":"is-primary is-clickable"}})],1),_vm._v(" "),_c('div',{staticClass:"pagination-list"},[_c('b-field',[(!_vm.isTypeMonth)?_c('b-select',{attrs:{"disabled":_vm.disabled,"size":_vm.size},model:{value:(_vm.focusedDateData.month),callback:function ($$v) {_vm.$set(_vm.focusedDateData, "month", $$v);},expression:"focusedDateData.month"}},_vm._l((_vm.monthNames),function(month,index){return _c('option',{key:month,domProps:{"value":index}},[_vm._v("\n "+_vm._s(month)+"\n ")])}),0):_vm._e(),_vm._v(" "),_c('b-select',{attrs:{"disabled":_vm.disabled,"size":_vm.size},model:{value:(_vm.focusedDateData.year),callback:function ($$v) {_vm.$set(_vm.focusedDateData, "year", $$v);},expression:"focusedDateData.year"}},_vm._l((_vm.listOfYears),function(year){return _c('option',{key:year,domProps:{"value":year}},[_vm._v("\n "+_vm._s(year)+"\n ")])}),0)],1)],1)])],2),_vm._v(" "),(!_vm.isTypeMonth)?_c('div',{staticClass:"datepicker-content"},[_c('b-datepicker-table',{attrs:{"day-names":_vm.dayNames,"month-names":_vm.monthNames,"first-day-of-week":_vm.firstDayOfWeek,"rules-for-first-week":_vm.rulesForFirstWeek,"min-date":_vm.minDate,"max-date":_vm.maxDate,"focused":_vm.focusedDateData,"disabled":_vm.disabled,"unselectable-dates":_vm.unselectableDates,"unselectable-days-of-week":_vm.unselectableDaysOfWeek,"selectable-dates":_vm.selectableDates,"events":_vm.events,"indicators":_vm.indicators,"date-creator":_vm.dateCreator,"type-month":_vm.isTypeMonth,"nearby-month-days":_vm.nearbyMonthDays,"nearby-selectable-month-days":_vm.nearbySelectableMonthDays,"show-week-number":_vm.showWeekNumber,"range":_vm.range,"multiple":_vm.multiple},on:{"close":function($event){return _vm.togglePicker(false)}},model:{value:(_vm.computedValue),callback:function ($$v) {_vm.computedValue=$$v;},expression:"computedValue"}})],1):_c('div',[_c('b-datepicker-month',{attrs:{"month-names":_vm.monthNames,"min-date":_vm.minDate,"max-date":_vm.maxDate,"focused":_vm.focusedDateData,"disabled":_vm.disabled,"unselectable-dates":_vm.unselectableDates,"unselectable-days-of-week":_vm.unselectableDaysOfWeek,"selectable-dates":_vm.selectableDates,"events":_vm.events,"indicators":_vm.indicators,"date-creator":_vm.dateCreator,"multiple":_vm.multiple},on:{"close":function($event){return _vm.togglePicker(false)}},model:{value:(_vm.computedValue),callback:function ($$v) {_vm.computedValue=$$v;},expression:"computedValue"}})],1),_vm._v(" "),(_vm.$slots.default !== undefined && _vm.$slots.default.length)?_c('footer',{staticClass:"datepicker-footer"},[_vm._t("default")],2):_vm._e()])],1):_c('b-input',_vm._b({ref:"input",attrs:{"type":!_vm.isTypeMonth ? 'date' : 'month',"autocomplete":"off","value":_vm.formatNative(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"loading":_vm.loading,"max":_vm.formatNative(_vm.maxDate),"min":_vm.formatNative(_vm.minDate),"disabled":_vm.disabled,"readonly":false,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.onFocus,"blur":_vm.onBlur},nativeOn:{"change":function($event){return _vm.onChangeNativePicker($event)}}},'b-input',_vm.$attrs,false))],1)};
var __vue_staticRenderFns__$h = [];
/* style */
const __vue_inject_styles__$j = undefined;
/* scoped */
const __vue_scope_id__$j = undefined;
/* module identifier */
const __vue_module_identifier__$j = undefined;
/* functional template */
const __vue_is_functional_template__$j = false;
/* style inject */
/* style inject SSR */
var Datepicker = normalizeComponent_1(
{ render: __vue_render__$h, staticRenderFns: __vue_staticRenderFns__$h },
__vue_inject_styles__$j,
__vue_script__$j,
__vue_scope_id__$j,
__vue_is_functional_template__$j,
__vue_module_identifier__$j,
undefined,
undefined
);
var Plugin$6 = {
install: function install(Vue) {
registerComponent(Vue, Datepicker);
}
};
use(Plugin$6);
var _components$2;
var script$k = {
name: 'BTimepicker',
components: (_components$2 = {}, _defineProperty(_components$2, Input.name, Input), _defineProperty(_components$2, Field.name, Field), _defineProperty(_components$2, Select.name, Select), _defineProperty(_components$2, Icon.name, Icon), _defineProperty(_components$2, Dropdown.name, Dropdown), _defineProperty(_components$2, DropdownItem.name, DropdownItem), _components$2),
mixins: [TimepickerMixin],
inheritAttrs: false,
data: function data() {
return {
_isTimepicker: true
};
},
computed: {
nativeStep: function nativeStep() {
if (this.enableSeconds) return '1';
}
}
};
/* script */
const __vue_script__$k = script$k;
/* template */
var __vue_render__$i = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"timepicker control",class:[_vm.size, {'is-expanded': _vm.expanded}]},[(!_vm.isMobile || _vm.inline)?_c('b-dropdown',{ref:"dropdown",attrs:{"position":_vm.position,"disabled":_vm.disabled,"inline":_vm.inline}},[(!_vm.inline)?_c('b-input',_vm._b({ref:"input",attrs:{"slot":"trigger","autocomplete":"off","value":_vm.formatValue(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"loading":_vm.loading,"disabled":_vm.disabled,"readonly":!_vm.editable,"rounded":_vm.rounded,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.handleOnFocus,"blur":function($event){_vm.onBlur() && _vm.checkHtml5Validity();}},nativeOn:{"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.toggle(true)},"change":function($event){return _vm.onChange($event.target.value)}},slot:"trigger"},'b-input',_vm.$attrs,false)):_vm._e(),_vm._v(" "),_c('b-dropdown-item',{attrs:{"disabled":_vm.disabled,"custom":""}},[_c('b-field',{attrs:{"grouped":"","position":"is-centered"}},[_c('b-select',{attrs:{"disabled":_vm.disabled,"placeholder":"00"},nativeOn:{"change":function($event){return _vm.onHoursChange($event.target.value)}},model:{value:(_vm.hoursSelected),callback:function ($$v) {_vm.hoursSelected=$$v;},expression:"hoursSelected"}},_vm._l((_vm.hours),function(hour){return _c('option',{key:hour.value,attrs:{"disabled":_vm.isHourDisabled(hour.value)},domProps:{"value":hour.value}},[_vm._v("\n "+_vm._s(hour.label)+"\n ")])}),0),_vm._v(" "),_c('span',{staticClass:"control is-colon"},[_vm._v(":")]),_vm._v(" "),_c('b-select',{attrs:{"disabled":_vm.disabled,"placeholder":"00"},nativeOn:{"change":function($event){return _vm.onMinutesChange($event.target.value)}},model:{value:(_vm.minutesSelected),callback:function ($$v) {_vm.minutesSelected=$$v;},expression:"minutesSelected"}},_vm._l((_vm.minutes),function(minute){return _c('option',{key:minute.value,attrs:{"disabled":_vm.isMinuteDisabled(minute.value)},domProps:{"value":minute.value}},[_vm._v("\n "+_vm._s(minute.label)+"\n ")])}),0),_vm._v(" "),(_vm.enableSeconds)?[_c('span',{staticClass:"control is-colon"},[_vm._v(":")]),_vm._v(" "),_c('b-select',{attrs:{"disabled":_vm.disabled,"placeholder":"00"},nativeOn:{"change":function($event){return _vm.onSecondsChange($event.target.value)}},model:{value:(_vm.secondsSelected),callback:function ($$v) {_vm.secondsSelected=$$v;},expression:"secondsSelected"}},_vm._l((_vm.seconds),function(second){return _c('option',{key:second.value,attrs:{"disabled":_vm.isSecondDisabled(second.value)},domProps:{"value":second.value}},[_vm._v("\n "+_vm._s(second.label)+"\n ")])}),0)]:_vm._e(),_vm._v(" "),(!_vm.isHourFormat24)?_c('b-select',{attrs:{"disabled":_vm.disabled},nativeOn:{"change":function($event){return _vm.onMeridienChange($event.target.value)}},model:{value:(_vm.meridienSelected),callback:function ($$v) {_vm.meridienSelected=$$v;},expression:"meridienSelected"}},_vm._l((_vm.meridiens),function(meridien){return _c('option',{key:meridien,domProps:{"value":meridien}},[_vm._v("\n "+_vm._s(meridien)+"\n ")])}),0):_vm._e()],2),_vm._v(" "),(_vm.$slots.default !== undefined && _vm.$slots.default.length)?_c('footer',{staticClass:"timepicker-footer"},[_vm._t("default")],2):_vm._e()],1)],1):_c('b-input',_vm._b({ref:"input",attrs:{"type":"time","step":_vm.nativeStep,"autocomplete":"off","value":_vm.formatHHMMSS(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"loading":_vm.loading,"max":_vm.formatHHMMSS(_vm.maxTime),"min":_vm.formatHHMMSS(_vm.minTime),"disabled":_vm.disabled,"readonly":false,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.handleOnFocus,"blur":function($event){_vm.onBlur() && _vm.checkHtml5Validity();}},nativeOn:{"change":function($event){return _vm.onChange($event.target.value)}}},'b-input',_vm.$attrs,false))],1)};
var __vue_staticRenderFns__$i = [];
/* style */
const __vue_inject_styles__$k = undefined;
/* scoped */
const __vue_scope_id__$k = undefined;
/* module identifier */
const __vue_module_identifier__$k = undefined;
/* functional template */
const __vue_is_functional_template__$k = false;
/* style inject */
/* style inject SSR */
var Timepicker = normalizeComponent_1(
{ render: __vue_render__$i, staticRenderFns: __vue_staticRenderFns__$i },
__vue_inject_styles__$k,
__vue_script__$k,
__vue_scope_id__$k,
__vue_is_functional_template__$k,
__vue_module_identifier__$k,
undefined,
undefined
);
var _components$3;
var script$l = {
name: 'BDatetimepicker',
components: (_components$3 = {}, _defineProperty(_components$3, Datepicker.name, Datepicker), _defineProperty(_components$3, Timepicker.name, Timepicker), _components$3),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: {
type: Date
},
editable: {
type: Boolean,
default: false
},
placeholder: String,
disabled: Boolean,
icon: String,
iconPack: String,
inline: Boolean,
openOnFocus: Boolean,
position: String,
mobileNative: {
type: Boolean,
default: true
},
minDatetime: Date,
maxDatetime: Date,
datetimeFormatter: {
type: Function
},
datetimeParser: {
type: Function
},
datetimeCreator: {
type: Function,
default: function _default(date) {
if (typeof config.defaultDatetimeCreator === 'function') {
return config.defaultDatetimeCreator(date);
} else {
return date;
}
}
},
datepicker: Object,
timepicker: Object
},
data: function data() {
return {
newValue: this.value
};
},
computed: {
computedValue: {
get: function get() {
return this.newValue;
},
set: function set(value) {
if (value) {
var val = new Date(value.getTime());
if (this.newValue) {
// restore time part
if ((value.getDate() !== this.newValue.getDate() || value.getMonth() !== this.newValue.getMonth() || value.getFullYear() !== this.newValue.getFullYear()) && value.getHours() === 0 && value.getMinutes() === 0 && value.getSeconds() === 0) {
val.setHours(this.newValue.getHours(), this.newValue.getMinutes(), this.newValue.getSeconds(), 0);
}
} else {
val = this.datetimeCreator(value);
} // check min and max range
if (this.minDatetime && val < this.minDatetime) {
val = this.minDatetime;
} else if (this.maxDatetime && val > this.maxDatetime) {
val = this.maxDatetime;
}
this.newValue = new Date(val.getTime());
} else {
this.newValue = value;
}
this.$emit('input', this.newValue);
}
},
isMobile: function isMobile$1() {
return this.mobileNative && isMobile.any();
},
minDate: function minDate() {
if (!this.minDatetime) return this.datepicker ? this.datepicker.minDate : null;
return new Date(this.minDatetime.getFullYear(), this.minDatetime.getMonth(), this.minDatetime.getDate(), 0, 0, 0, 0);
},
maxDate: function maxDate() {
if (!this.maxDatetime) return this.datepicker ? this.datepicker.maxDate : null;
return new Date(this.maxDatetime.getFullYear(), this.maxDatetime.getMonth(), this.maxDatetime.getDate(), 0, 0, 0, 0);
},
minTime: function minTime() {
if (!this.minDatetime || this.newValue === null || typeof this.newValue === 'undefined') {
return this.timepicker ? this.timepicker.minTime : null;
}
if (this.minDatetime.getFullYear() === this.newValue.getFullYear() && this.minDatetime.getMonth() === this.newValue.getMonth() && this.minDatetime.getDate() === this.newValue.getDate()) {
return this.minDatetime;
}
},
maxTime: function maxTime() {
if (!this.maxDatetime || this.newValue === null || typeof this.newValue === 'undefined') {
return this.timepicker ? this.timepicker.maxTime : null;
}
if (this.maxDatetime.getFullYear() === this.newValue.getFullYear() && this.maxDatetime.getMonth() === this.newValue.getMonth() && this.maxDatetime.getDate() === this.newValue.getDate()) {
return this.maxDatetime;
}
},
datepickerSize: function datepickerSize() {
return this.datepicker && this.datepicker.size ? this.datepicker.size : this.size;
},
timepickerSize: function timepickerSize() {
return this.timepicker && this.timepicker.size ? this.timepicker.size : this.size;
},
timepickerDisabled: function timepickerDisabled() {
return this.timepicker && this.timepicker.disabled ? this.timepicker.disabled : this.disabled;
}
},
watch: {
value: function value(_value) {
this.newValue = _value;
}
},
methods: {
defaultDatetimeParser: function defaultDatetimeParser(date) {
if (typeof this.datetimeParser === 'function') {
return this.datetimeParser(date);
} else if (typeof config.defaultDatetimeParser === 'function') {
return config.defaultDatetimeParser(date);
} else {
return new Date(Date.parse(date));
}
},
defaultDatetimeFormatter: function defaultDatetimeFormatter(date) {
if (typeof this.datetimeFormatter === 'function') {
return this.datetimeFormatter(date);
} else if (typeof config.defaultDatetimeParser === 'function') {
return config.defaultDatetimeParser(date);
} else {
if (this.$refs.timepicker) {
var yyyyMMdd = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
var d = new Date(yyyyMMdd);
return d.toLocaleDateString() + ' ' + this.$refs.timepicker.timeFormatter(date, this.$refs.timepicker);
}
return null;
}
},
/*
* Parse date from string
*/
onChangeNativePicker: function onChangeNativePicker(event) {
var date = event.target.value;
this.computedValue = date ? new Date(date) : null;
},
formatNative: function formatNative(value) {
var date = new Date(value);
if (value && !isNaN(date)) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
return year + '-' + ((month < 10 ? '0' : '') + month) + '-' + ((day < 10 ? '0' : '') + day) + 'T' + ((hours < 10 ? '0' : '') + hours) + ':' + ((minutes < 10 ? '0' : '') + minutes) + ':' + ((seconds < 10 ? '0' : '') + seconds);
}
return '';
},
toggle: function toggle() {
this.$refs.datepicker.toggle();
}
},
mounted: function mounted() {
// $refs attached, it's time to refresh datepicker (input)
if (this.newValue) {
this.$refs.datepicker.$forceUpdate();
}
}
};
/* script */
const __vue_script__$l = script$l;
/* template */
var __vue_render__$j = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return (!_vm.isMobile || _vm.inline)?_c('b-datepicker',_vm._b({ref:"datepicker",attrs:{"open-on-focus":_vm.openOnFocus,"position":_vm.position,"loading":_vm.loading,"inline":_vm.inline,"editable":_vm.editable,"expanded":_vm.expanded,"close-on-click":false,"date-formatter":_vm.defaultDatetimeFormatter,"date-parser":_vm.defaultDatetimeParser,"min-date":_vm.minDate,"max-date":_vm.maxDate,"icon":_vm.icon,"icon-pack":_vm.iconPack,"size":_vm.datepickerSize,"placeholder":_vm.placeholder,"range":false,"disabled":_vm.disabled,"mobile-native":_vm.mobileNative},on:{"change-month":function($event){return _vm.$emit('change-month', $event)},"change-year":function($event){return _vm.$emit('change-year', $event)}},model:{value:(_vm.computedValue),callback:function ($$v) {_vm.computedValue=$$v;},expression:"computedValue"}},'b-datepicker',_vm.datepicker,false),[_c('nav',{staticClass:"level is-mobile"},[(_vm.$slots.left !== undefined)?_c('div',{staticClass:"level-item has-text-centered"},[_vm._t("left")],2):_vm._e(),_vm._v(" "),_c('div',{staticClass:"level-item has-text-centered"},[_c('b-timepicker',_vm._b({ref:"timepicker",attrs:{"inline":"","editable":_vm.editable,"min-time":_vm.minTime,"max-time":_vm.maxTime,"size":_vm.timepickerSize,"disabled":_vm.timepickerDisabled},model:{value:(_vm.computedValue),callback:function ($$v) {_vm.computedValue=$$v;},expression:"computedValue"}},'b-timepicker',_vm.timepicker,false))],1),_vm._v(" "),(_vm.$slots.right !== undefined)?_c('div',{staticClass:"level-item has-text-centered"},[_vm._t("right")],2):_vm._e()])]):_c('b-input',_vm._b({ref:"input",attrs:{"type":"datetime-local","autocomplete":"off","value":_vm.formatNative(_vm.computedValue),"placeholder":_vm.placeholder,"size":_vm.size,"icon":_vm.icon,"icon-pack":_vm.iconPack,"loading":_vm.loading,"max":_vm.formatNative(_vm.maxDate),"min":_vm.formatNative(_vm.minDate),"disabled":_vm.disabled,"readonly":false,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":_vm.onFocus,"blur":_vm.onBlur},nativeOn:{"change":function($event){return _vm.onChangeNativePicker($event)}}},'b-input',_vm.$attrs,false))};
var __vue_staticRenderFns__$j = [];
/* style */
const __vue_inject_styles__$l = undefined;
/* scoped */
const __vue_scope_id__$l = undefined;
/* module identifier */
const __vue_module_identifier__$l = undefined;
/* functional template */
const __vue_is_functional_template__$l = false;
/* style inject */
/* style inject SSR */
var Datetimepicker = normalizeComponent_1(
{ render: __vue_render__$j, staticRenderFns: __vue_staticRenderFns__$j },
__vue_inject_styles__$l,
__vue_script__$l,
__vue_scope_id__$l,
__vue_is_functional_template__$l,
__vue_module_identifier__$l,
undefined,
undefined
);
var Plugin$7 = {
install: function install(Vue) {
registerComponent(Vue, Datetimepicker);
}
};
use(Plugin$7);
//
var script$m = {
name: 'BModal',
directives: {
trapFocus: directive
},
props: {
active: Boolean,
component: [Object, Function],
content: String,
programmatic: Boolean,
props: Object,
events: Object,
width: {
type: [String, Number],
default: 960
},
hasModalCard: Boolean,
animation: {
type: String,
default: 'zoom-out'
},
canCancel: {
type: [Array, Boolean],
default: function _default() {
return config.defaultModalCanCancel;
}
},
onCancel: {
type: Function,
default: function _default() {}
},
scroll: {
type: String,
default: function _default() {
return config.defaultModalScroll ? config.defaultModalScroll : 'clip';
},
validator: function validator(value) {
return ['clip', 'keep'].indexOf(value) >= 0;
}
},
fullScreen: Boolean,
trapFocus: {
type: Boolean,
default: config.defaultTrapFocus
},
customClass: String,
ariaRole: {
type: String,
validator: function validator(value) {
return ['dialog', 'alertdialog'].indexOf(value) >= 0;
}
},
ariaModal: Boolean
},
data: function data() {
return {
isActive: this.active || false,
savedScrollTop: null,
newWidth: typeof this.width === 'number' ? this.width + 'px' : this.width,
animating: true
};
},
computed: {
cancelOptions: function cancelOptions() {
return typeof this.canCancel === 'boolean' ? this.canCancel ? config.defaultModalCanCancel : [] : this.canCancel;
},
showX: function showX() {
return this.cancelOptions.indexOf('x') >= 0;
},
customStyle: function customStyle() {
if (!this.fullScreen) {
return {
maxWidth: this.newWidth
};
}
return null;
}
},
watch: {
active: function active(value) {
var _this = this;
this.isActive = value;
this.$nextTick(function () {
if (value && _this.$el && _this.$el.focus) {
_this.$el.focus();
}
});
},
isActive: function isActive() {
this.handleScroll();
}
},
methods: {
handleScroll: function handleScroll() {
if (typeof window === 'undefined') return;
if (this.scroll === 'clip') {
if (this.isActive) {
document.documentElement.classList.add('is-clipped');
} else {
document.documentElement.classList.remove('is-clipped');
}
return;
}
this.savedScrollTop = !this.savedScrollTop ? document.documentElement.scrollTop : this.savedScrollTop;
if (this.isActive) {
document.body.classList.add('is-noscroll');
} else {
document.body.classList.remove('is-noscroll');
}
if (this.isActive) {
document.body.style.top = "-".concat(this.savedScrollTop, "px");
return;
}
document.documentElement.scrollTop = this.savedScrollTop;
document.body.style.top = null;
this.savedScrollTop = null;
},
/**
* Close the Modal if canCancel and call the onCancel prop (function).
*/
cancel: function cancel(method) {
if (this.cancelOptions.indexOf(method) < 0) return;
this.onCancel.apply(null, arguments);
this.close();
},
/**
* Call the onCancel prop (function).
* Emit events, and destroy modal if it's programmatic.
*/
close: function close() {
var _this2 = this;
this.$emit('close');
this.$emit('update:active', false); // Timeout for the animation complete before destroying
if (this.programmatic) {
this.isActive = false;
setTimeout(function () {
_this2.$destroy();
removeElement(_this2.$el);
}, 150);
}
},
/**
* Keypress event that is bound to the document.
*/
keyPress: function keyPress(event) {
// Esc key
if (this.isActive && event.keyCode === 27) this.cancel('escape');
},
/**
* Transition after-enter hook
*/
afterEnter: function afterEnter() {
this.animating = false;
},
/**
* Transition before-leave hook
*/
beforeLeave: function beforeLeave() {
this.animating = true;
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('keyup', this.keyPress);
}
},
beforeMount: function beforeMount() {
// Insert the Modal component in body tag
// only if it's programmatic
this.programmatic && document.body.appendChild(this.$el);
},
mounted: function mounted() {
if (this.programmatic) this.isActive = true;else if (this.isActive) this.handleScroll();
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('keyup', this.keyPress); // reset scroll
document.documentElement.classList.remove('is-clipped');
var savedScrollTop = !this.savedScrollTop ? document.documentElement.scrollTop : this.savedScrollTop;
document.body.classList.remove('is-noscroll');
document.documentElement.scrollTop = savedScrollTop;
document.body.style.top = null;
}
}
};
/* script */
const __vue_script__$m = script$m;
/* template */
var __vue_render__$k = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":_vm.animation},on:{"after-enter":_vm.afterEnter,"before-leave":_vm.beforeLeave}},[(_vm.isActive)?_c('div',{directives:[{name:"trap-focus",rawName:"v-trap-focus",value:(_vm.trapFocus),expression:"trapFocus"}],staticClass:"modal is-active",class:[{'is-full-screen': _vm.fullScreen}, _vm.customClass],attrs:{"tabindex":"-1","role":_vm.ariaRole,"aria-modal":_vm.ariaModal}},[_c('div',{staticClass:"modal-background",on:{"click":function($event){return _vm.cancel('outside')}}}),_vm._v(" "),_c('div',{staticClass:"animation-content",class:{ 'modal-content': !_vm.hasModalCard },style:(_vm.customStyle)},[(_vm.component)?_c(_vm.component,_vm._g(_vm._b({tag:"component",on:{"close":_vm.close}},'component',_vm.props,false),_vm.events)):(_vm.content)?_c('div',{domProps:{"innerHTML":_vm._s(_vm.content)}}):_vm._t("default"),_vm._v(" "),(_vm.showX)?_c('button',{directives:[{name:"show",rawName:"v-show",value:(!_vm.animating),expression:"!animating"}],staticClass:"modal-close is-large",attrs:{"type":"button"},on:{"click":function($event){return _vm.cancel('x')}}}):_vm._e()],2)]):_vm._e()])};
var __vue_staticRenderFns__$k = [];
/* style */
const __vue_inject_styles__$m = undefined;
/* scoped */
const __vue_scope_id__$m = undefined;
/* module identifier */
const __vue_module_identifier__$m = undefined;
/* functional template */
const __vue_is_functional_template__$m = false;
/* style inject */
/* style inject SSR */
var Modal = normalizeComponent_1(
{ render: __vue_render__$k, staticRenderFns: __vue_staticRenderFns__$k },
__vue_inject_styles__$m,
__vue_script__$m,
__vue_scope_id__$m,
__vue_is_functional_template__$m,
__vue_module_identifier__$m,
undefined,
undefined
);
var script$n = {
name: 'BDialog',
components: _defineProperty({}, Icon.name, Icon),
directives: {
trapFocus: directive
},
extends: Modal,
props: {
title: String,
message: String,
icon: String,
iconPack: String,
hasIcon: Boolean,
type: {
type: String,
default: 'is-primary'
},
size: String,
confirmText: {
type: String,
default: function _default() {
return config.defaultDialogConfirmText ? config.defaultDialogConfirmText : 'OK';
}
},
cancelText: {
type: String,
default: function _default() {
return config.defaultDialogCancelText ? config.defaultDialogCancelText : 'Cancel';
}
},
hasInput: Boolean,
// Used internally to know if it's prompt
inputAttrs: {
type: Object,
default: function _default() {
return {};
}
},
onConfirm: {
type: Function,
default: function _default() {}
},
container: {
type: String,
default: config.defaultContainerElement
},
focusOn: {
type: String,
default: 'confirm'
},
trapFocus: {
type: Boolean,
default: config.defaultTrapFocus
},
ariaRole: {
type: String,
validator: function validator(value) {
return ['dialog', 'alertdialog'].indexOf(value) >= 0;
}
},
ariaModal: Boolean
},
data: function data() {
var prompt = this.hasInput ? this.inputAttrs.value || '' : '';
return {
prompt: prompt,
isActive: false,
validationMessage: ''
};
},
computed: {
dialogClass: function dialogClass() {
return [this.size, {
'has-custom-container': this.container !== null
}];
},
/**
* Icon name (MDI) based on the type.
*/
iconByType: function iconByType() {
switch (this.type) {
case 'is-info':
return 'information';
case 'is-success':
return 'check-circle';
case 'is-warning':
return 'alert';
case 'is-danger':
return 'alert-circle';
default:
return null;
}
},
showCancel: function showCancel() {
return this.cancelOptions.indexOf('button') >= 0;
}
},
methods: {
/**
* If it's a prompt Dialog, validate the input.
* Call the onConfirm prop (function) and close the Dialog.
*/
confirm: function confirm() {
var _this = this;
if (this.$refs.input !== undefined) {
if (!this.$refs.input.checkValidity()) {
this.validationMessage = this.$refs.input.validationMessage;
this.$nextTick(function () {
return _this.$refs.input.select();
});
return;
}
}
this.onConfirm(this.prompt);
this.close();
},
/**
* Close the Dialog.
*/
close: function close() {
var _this2 = this;
this.isActive = false; // Timeout for the animation complete before destroying
setTimeout(function () {
_this2.$destroy();
removeElement(_this2.$el);
}, 150);
}
},
beforeMount: function beforeMount() {
var _this3 = this;
// Insert the Dialog component in the element container
if (typeof window !== 'undefined') {
this.$nextTick(function () {
var container = document.querySelector(_this3.container) || document.body;
container.appendChild(_this3.$el);
});
}
},
mounted: function mounted() {
var _this4 = this;
this.isActive = true;
if (typeof this.inputAttrs.required === 'undefined') {
this.$set(this.inputAttrs, 'required', true);
}
this.$nextTick(function () {
// Handle which element receives focus
if (_this4.hasInput) {
_this4.$refs.input.focus();
} else if (_this4.focusOn === 'cancel' && _this4.showCancel) {
_this4.$refs.cancelButton.focus();
} else {
_this4.$refs.confirmButton.focus();
}
});
}
};
/* script */
const __vue_script__$n = script$n;
/* template */
var __vue_render__$l = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":_vm.animation}},[(_vm.isActive)?_c('div',{directives:[{name:"trap-focus",rawName:"v-trap-focus",value:(_vm.trapFocus),expression:"trapFocus"}],staticClass:"dialog modal is-active",class:_vm.dialogClass,attrs:{"role":_vm.ariaRole,"aria-modal":_vm.ariaModal}},[_c('div',{staticClass:"modal-background",on:{"click":function($event){return _vm.cancel('outside')}}}),_vm._v(" "),_c('div',{staticClass:"modal-card animation-content"},[(_vm.title)?_c('header',{staticClass:"modal-card-head"},[_c('p',{staticClass:"modal-card-title"},[_vm._v(_vm._s(_vm.title))])]):_vm._e(),_vm._v(" "),_c('section',{staticClass:"modal-card-body",class:{ 'is-titleless': !_vm.title, 'is-flex': _vm.hasIcon }},[_c('div',{staticClass:"media"},[(_vm.hasIcon && (_vm.icon || _vm.iconByType))?_c('div',{staticClass:"media-left"},[_c('b-icon',{attrs:{"icon":_vm.icon ? _vm.icon : _vm.iconByType,"pack":_vm.iconPack,"type":_vm.type,"both":!_vm.icon,"size":"is-large"}})],1):_vm._e(),_vm._v(" "),_c('div',{staticClass:"media-content"},[_c('p',{domProps:{"innerHTML":_vm._s(_vm.message)}}),_vm._v(" "),(_vm.hasInput)?_c('div',{staticClass:"field"},[_c('div',{staticClass:"control"},[(((_vm.inputAttrs).type)==='checkbox')?_c('input',_vm._b({directives:[{name:"model",rawName:"v-model",value:(_vm.prompt),expression:"prompt"}],ref:"input",staticClass:"input",class:{ 'is-danger': _vm.validationMessage },attrs:{"type":"checkbox"},domProps:{"checked":Array.isArray(_vm.prompt)?_vm._i(_vm.prompt,null)>-1:(_vm.prompt)},on:{"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.confirm($event)},"change":function($event){var $$a=_vm.prompt,$$el=$event.target,$$c=$$el.checked?(true):(false);if(Array.isArray($$a)){var $$v=null,$$i=_vm._i($$a,$$v);if($$el.checked){$$i<0&&(_vm.prompt=$$a.concat([$$v]));}else{$$i>-1&&(_vm.prompt=$$a.slice(0,$$i).concat($$a.slice($$i+1)));}}else{_vm.prompt=$$c;}}}},'input',_vm.inputAttrs,false)):(((_vm.inputAttrs).type)==='radio')?_c('input',_vm._b({directives:[{name:"model",rawName:"v-model",value:(_vm.prompt),expression:"prompt"}],ref:"input",staticClass:"input",class:{ 'is-danger': _vm.validationMessage },attrs:{"type":"radio"},domProps:{"checked":_vm._q(_vm.prompt,null)},on:{"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.confirm($event)},"change":function($event){_vm.prompt=null;}}},'input',_vm.inputAttrs,false)):_c('input',_vm._b({directives:[{name:"model",rawName:"v-model",value:(_vm.prompt),expression:"prompt"}],ref:"input",staticClass:"input",class:{ 'is-danger': _vm.validationMessage },attrs:{"type":(_vm.inputAttrs).type},domProps:{"value":(_vm.prompt)},on:{"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }return _vm.confirm($event)},"input":function($event){if($event.target.composing){ return; }_vm.prompt=$event.target.value;}}},'input',_vm.inputAttrs,false))]),_vm._v(" "),_c('p',{staticClass:"help is-danger"},[_vm._v(_vm._s(_vm.validationMessage))])]):_vm._e()])])]),_vm._v(" "),_c('footer',{staticClass:"modal-card-foot"},[(_vm.showCancel)?_c('button',{ref:"cancelButton",staticClass:"button",on:{"click":function($event){return _vm.cancel('button')}}},[_vm._v("\n "+_vm._s(_vm.cancelText)+"\n ")]):_vm._e(),_vm._v(" "),_c('button',{ref:"confirmButton",staticClass:"button",class:_vm.type,on:{"click":_vm.confirm}},[_vm._v("\n "+_vm._s(_vm.confirmText)+"\n ")])])])]):_vm._e()])};
var __vue_staticRenderFns__$l = [];
/* style */
const __vue_inject_styles__$n = undefined;
/* scoped */
const __vue_scope_id__$n = undefined;
/* module identifier */
const __vue_module_identifier__$n = undefined;
/* functional template */
const __vue_is_functional_template__$n = false;
/* style inject */
/* style inject SSR */
var Dialog = normalizeComponent_1(
{ render: __vue_render__$l, staticRenderFns: __vue_staticRenderFns__$l },
__vue_inject_styles__$n,
__vue_script__$n,
__vue_scope_id__$n,
__vue_is_functional_template__$n,
__vue_module_identifier__$n,
undefined,
undefined
);
function open(propsData) {
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : Vue;
var DialogComponent = vm.extend(Dialog);
return new DialogComponent({
el: document.createElement('div'),
propsData: propsData
});
}
var DialogProgrammatic = {
alert: function alert(params) {
if (typeof params === 'string') {
params = {
message: params
};
}
var defaultParam = {
canCancel: false
};
var propsData = merge(defaultParam, params);
return open(propsData);
},
confirm: function confirm(params) {
var defaultParam = {};
var propsData = merge(defaultParam, params);
return open(propsData);
},
prompt: function prompt(params) {
var defaultParam = {
hasInput: true,
confirmText: 'Done'
};
var propsData = merge(defaultParam, params);
return open(propsData);
}
};
var Plugin$8 = {
install: function install(Vue) {
registerComponent(Vue, Dialog);
registerComponentProgrammatic(Vue, 'dialog', DialogProgrammatic);
}
};
use(Plugin$8);
var Plugin$9 = {
install: function install(Vue) {
registerComponent(Vue, Dropdown);
registerComponent(Vue, DropdownItem);
}
};
use(Plugin$9);
var Plugin$a = {
install: function install(Vue) {
registerComponent(Vue, Field);
}
};
use(Plugin$a);
var Plugin$b = {
install: function install(Vue) {
registerComponent(Vue, Icon);
}
};
use(Plugin$b);
var Plugin$c = {
install: function install(Vue) {
registerComponent(Vue, Input);
}
};
use(Plugin$c);
// Polyfills for SSR
var isSSR = typeof window === 'undefined';
var HTMLElement = isSSR ? Object : window.HTMLElement;
var File = isSSR ? Object : window.File;
//
var script$o = {
name: 'BLoading',
props: {
active: Boolean,
programmatic: Boolean,
container: [Object, Function, HTMLElement],
isFullPage: {
type: Boolean,
default: true
},
animation: {
type: String,
default: 'fade'
},
canCancel: {
type: Boolean,
default: false
},
onCancel: {
type: Function,
default: function _default() {}
}
},
data: function data() {
return {
isActive: this.active || false
};
},
watch: {
active: function active(value) {
this.isActive = value;
}
},
methods: {
/**
* Close the Modal if canCancel.
*/
cancel: function cancel() {
if (!this.canCancel || !this.isActive) return;
this.close();
},
/**
* Emit events, and destroy modal if it's programmatic.
*/
close: function close() {
var _this = this;
this.onCancel.apply(null, arguments);
this.$emit('close');
this.$emit('update:active', false); // Timeout for the animation complete before destroying
if (this.programmatic) {
this.isActive = false;
setTimeout(function () {
_this.$destroy();
removeElement(_this.$el);
}, 150);
}
},
/**
* Keypress event that is bound to the document.
*/
keyPress: function keyPress(event) {
// Esc key
if (event.keyCode === 27) this.cancel();
}
},
created: function created() {
if (typeof window !== 'undefined') {
document.addEventListener('keyup', this.keyPress);
}
},
beforeMount: function beforeMount() {
// Insert the Loading component in body tag
// only if it's programmatic
if (this.programmatic) {
if (!this.container) {
document.body.appendChild(this.$el);
} else {
this.isFullPage = false;
this.container.appendChild(this.$el);
}
}
},
mounted: function mounted() {
if (this.programmatic) this.isActive = true;
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
document.removeEventListener('keyup', this.keyPress);
}
}
};
/* script */
const __vue_script__$o = script$o;
/* template */
var __vue_render__$m = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":_vm.animation}},[(_vm.isActive)?_c('div',{staticClass:"loading-overlay is-active",class:{ 'is-full-page': _vm.isFullPage }},[_c('div',{staticClass:"loading-background",on:{"click":_vm.cancel}}),_vm._v(" "),_vm._t("default",[_c('div',{staticClass:"loading-icon"})])],2):_vm._e()])};
var __vue_staticRenderFns__$m = [];
/* style */
const __vue_inject_styles__$o = undefined;
/* scoped */
const __vue_scope_id__$o = undefined;
/* module identifier */
const __vue_module_identifier__$o = undefined;
/* functional template */
const __vue_is_functional_template__$o = false;
/* style inject */
/* style inject SSR */
var Loading = normalizeComponent_1(
{ render: __vue_render__$m, staticRenderFns: __vue_staticRenderFns__$m },
__vue_inject_styles__$o,
__vue_script__$o,
__vue_scope_id__$o,
__vue_is_functional_template__$o,
__vue_module_identifier__$o,
undefined,
undefined
);
var LoadingProgrammatic = {
open: function open(params) {
var defaultParam = {
programmatic: true
};
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : Vue;
var LoadingComponent = vm.extend(Loading);
return new LoadingComponent({
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin$d = {
install: function install(Vue) {
registerComponent(Vue, Loading);
registerComponentProgrammatic(Vue, 'loading', LoadingProgrammatic);
}
};
use(Plugin$d);
//
//
//
//
//
//
var script$p = {
name: 'BMenu',
props: {
accordion: {
type: Boolean,
default: true
}
},
data: function data() {
return {
_isMenu: true // Used by MenuItem
};
}
};
/* script */
const __vue_script__$p = script$p;
/* template */
var __vue_render__$n = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"menu"},[_vm._t("default")],2)};
var __vue_staticRenderFns__$n = [];
/* style */
const __vue_inject_styles__$p = undefined;
/* scoped */
const __vue_scope_id__$p = undefined;
/* module identifier */
const __vue_module_identifier__$p = undefined;
/* functional template */
const __vue_is_functional_template__$p = false;
/* style inject */
/* style inject SSR */
var Menu = normalizeComponent_1(
{ render: __vue_render__$n, staticRenderFns: __vue_staticRenderFns__$n },
__vue_inject_styles__$p,
__vue_script__$p,
__vue_scope_id__$p,
__vue_is_functional_template__$p,
__vue_module_identifier__$p,
undefined,
undefined
);
var script$q = {
name: 'BMenuList',
functional: true,
props: {
label: String,
icon: String,
iconPack: String,
ariaRole: {
type: String,
default: ''
}
},
render: function render(createElement, context) {
var vlabel = null;
var slots = context.slots();
if (context.props.label || slots.label) {
vlabel = createElement('p', {
attrs: {
'class': 'menu-label'
}
}, context.props.label ? context.props.icon ? [createElement('b-icon', {
props: {
'icon': context.props.icon,
'pack': context.props.iconPack,
'size': 'is-small'
}
}), createElement('span', {}, context.props.label)] : context.props.label : slots.label);
}
var vnode = createElement('ul', {
attrs: {
'class': 'menu-list',
'role': context.props.ariaRole === 'menu' ? context.props.ariaRole : null
}
}, slots.default);
return vlabel ? [vlabel, vnode] : vnode;
}
};
/* script */
const __vue_script__$q = script$q;
/* template */
/* style */
const __vue_inject_styles__$q = undefined;
/* scoped */
const __vue_scope_id__$q = undefined;
/* module identifier */
const __vue_module_identifier__$q = undefined;
/* functional template */
const __vue_is_functional_template__$q = undefined;
/* style inject */
/* style inject SSR */
var MenuList = normalizeComponent_1(
{},
__vue_inject_styles__$q,
__vue_script__$q,
__vue_scope_id__$q,
__vue_is_functional_template__$q,
__vue_module_identifier__$q,
undefined,
undefined
);
var script$r = {
name: 'BMenuItem',
components: _defineProperty({}, Icon.name, Icon),
inheritAttrs: false,
props: {
label: String,
active: Boolean,
expanded: Boolean,
disabled: Boolean,
iconPack: String,
icon: String,
animation: {
type: String,
default: 'fade'
},
tag: {
type: String,
default: 'a',
validator: function validator(value) {
return ['a', 'router-link', 'nuxt-link', 'n-link', 'NuxtLink', 'NLink'].indexOf(value) >= 0;
}
},
ariaRole: {
type: String,
default: ''
}
},
data: function data() {
return {
newActive: this.active,
newExpanded: this.expanded
};
},
computed: {
ariaRoleMenu: function ariaRoleMenu() {
return this.ariaRole === 'menuitem' ? this.ariaRole : null;
}
},
watch: {
active: function active(value) {
this.newActive = value;
},
expanded: function expanded(value) {
this.newExpanded = value;
}
},
methods: {
onClick: function onClick(event) {
if (this.disabled) return;
this.reset(this.$parent);
this.newExpanded = true;
this.$emit('update:expanded', this.newActive);
this.newActive = true;
this.$emit('update:active', this.newActive);
this.$emit('click', event);
},
reset: function reset(parent) {
var _this = this;
var items = parent.$children.filter(function (c) {
return c.name === _this.name;
});
items.forEach(function (item) {
if (item !== _this) {
_this.reset(item);
if (!parent.$data._isMenu || parent.$data._isMenu && parent.accordion) {
item.newExpanded = false;
item.$emit('update:expanded', item.newActive);
}
item.newActive = false;
item.$emit('update:active', item.newActive);
}
});
}
}
};
/* script */
const __vue_script__$r = script$r;
/* template */
var __vue_render__$o = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('li',{attrs:{"role":_vm.ariaRoleMenu}},[_c(_vm.tag,_vm._b({tag:"component",class:{
'is-active': _vm.newActive,
'is-disabled': _vm.disabled
},on:{"click":function($event){return _vm.onClick($event)}},nativeOn:{"click":function($event){return _vm.onClick($event)}}},'component',_vm.$attrs,false),[(_vm.icon)?_c('b-icon',{attrs:{"icon":_vm.icon,"pack":_vm.iconPack,"size":"is-small"}}):_vm._e(),_vm._v(" "),(_vm.label)?_c('span',[_vm._v(_vm._s(_vm.label))]):_vm._t("label",null,{"expanded":_vm.newExpanded,"active":_vm.newActive})],2),_vm._v(" "),(_vm.$slots.default)?[_c('transition',{attrs:{"name":_vm.animation}},[_c('ul',{directives:[{name:"show",rawName:"v-show",value:(_vm.newExpanded),expression:"newExpanded"}]},[_vm._t("default")],2)])]:_vm._e()],2)};
var __vue_staticRenderFns__$o = [];
/* style */
const __vue_inject_styles__$r = undefined;
/* scoped */
const __vue_scope_id__$r = undefined;
/* module identifier */
const __vue_module_identifier__$r = undefined;
/* functional template */
const __vue_is_functional_template__$r = false;
/* style inject */
/* style inject SSR */
var MenuItem = normalizeComponent_1(
{ render: __vue_render__$o, staticRenderFns: __vue_staticRenderFns__$o },
__vue_inject_styles__$r,
__vue_script__$r,
__vue_scope_id__$r,
__vue_is_functional_template__$r,
__vue_module_identifier__$r,
undefined,
undefined
);
var Plugin$e = {
install: function install(Vue) {
registerComponent(Vue, Menu);
registerComponent(Vue, MenuList);
registerComponent(Vue, MenuItem);
}
};
use(Plugin$e);
var MessageMixin = {
components: _defineProperty({}, Icon.name, Icon),
props: {
active: {
type: Boolean,
default: true
},
title: String,
closable: {
type: Boolean,
default: true
},
message: String,
type: String,
hasIcon: Boolean,
size: String,
iconPack: String,
iconSize: String,
autoClose: {
type: Boolean,
default: false
},
duration: {
type: Number,
default: 2000
}
},
data: function data() {
return {
isActive: this.active
};
},
watch: {
active: function active(value) {
this.isActive = value;
},
isActive: function isActive(value) {
if (value) {
this.setAutoClose();
} else {
if (this.timer) {
clearTimeout(this.timer);
}
}
}
},
computed: {
/**
* Icon name (MDI) based on type.
*/
icon: function icon() {
switch (this.type) {
case 'is-info':
return 'information';
case 'is-success':
return 'check-circle';
case 'is-warning':
return 'alert';
case 'is-danger':
return 'alert-circle';
default:
return null;
}
}
},
methods: {
/**
* Close the Message and emit events.
*/
close: function close() {
this.isActive = false;
this.$emit('close');
this.$emit('update:active', false);
},
/**
* Set timer to auto close message
*/
setAutoClose: function setAutoClose() {
var _this = this;
if (this.autoClose) {
this.timer = setTimeout(function () {
if (_this.isActive) {
_this.close();
}
}, this.duration);
}
}
},
mounted: function mounted() {
this.setAutoClose();
}
};
//
var script$s = {
name: 'BMessage',
mixins: [MessageMixin],
props: {
ariaCloseLabel: String
},
data: function data() {
return {
newIconSize: this.iconSize || this.size || 'is-large'
};
}
};
/* script */
const __vue_script__$s = script$s;
/* template */
var __vue_render__$p = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"fade"}},[(_vm.isActive)?_c('article',{staticClass:"message",class:[_vm.type, _vm.size]},[(_vm.title)?_c('header',{staticClass:"message-header"},[_c('p',[_vm._v(_vm._s(_vm.title))]),_vm._v(" "),(_vm.closable)?_c('button',{staticClass:"delete",attrs:{"type":"button","aria-label":_vm.ariaCloseLabel},on:{"click":_vm.close}}):_vm._e()]):_vm._e(),_vm._v(" "),_c('section',{staticClass:"message-body"},[_c('div',{staticClass:"media"},[(_vm.icon && _vm.hasIcon)?_c('div',{staticClass:"media-left"},[_c('b-icon',{class:_vm.type,attrs:{"icon":_vm.icon,"pack":_vm.iconPack,"both":"","size":_vm.newIconSize}})],1):_vm._e(),_vm._v(" "),_c('div',{staticClass:"media-content"},[_vm._t("default")],2)])])]):_vm._e()])};
var __vue_staticRenderFns__$p = [];
/* style */
const __vue_inject_styles__$s = undefined;
/* scoped */
const __vue_scope_id__$s = undefined;
/* module identifier */
const __vue_module_identifier__$s = undefined;
/* functional template */
const __vue_is_functional_template__$s = false;
/* style inject */
/* style inject SSR */
var Message = normalizeComponent_1(
{ render: __vue_render__$p, staticRenderFns: __vue_staticRenderFns__$p },
__vue_inject_styles__$s,
__vue_script__$s,
__vue_scope_id__$s,
__vue_is_functional_template__$s,
__vue_module_identifier__$s,
undefined,
undefined
);
var Plugin$f = {
install: function install(Vue) {
registerComponent(Vue, Message);
}
};
use(Plugin$f);
var ModalProgrammatic = {
open: function open(params) {
var parent;
if (typeof params === 'string') {
params = {
content: params
};
}
var defaultParam = {
programmatic: true
};
if (params.parent) {
parent = params.parent;
delete params.parent;
}
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : Vue;
var ModalComponent = vm.extend(Modal);
return new ModalComponent({
parent: parent,
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin$g = {
install: function install(Vue) {
registerComponent(Vue, Modal);
registerComponentProgrammatic(Vue, 'modal', ModalProgrammatic);
}
};
use(Plugin$g);
//
var script$t = {
name: 'BNotification',
mixins: [MessageMixin],
props: {
position: String,
ariaCloseLabel: String
}
};
/* script */
const __vue_script__$t = script$t;
/* template */
var __vue_render__$q = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"fade"}},[_c('article',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"notification",class:[_vm.type, _vm.position]},[(_vm.closable)?_c('button',{staticClass:"delete",attrs:{"type":"button","aria-label":_vm.ariaCloseLabel},on:{"click":_vm.close}}):_vm._e(),_vm._v(" "),_c('div',{staticClass:"media"},[(_vm.icon && _vm.hasIcon)?_c('div',{staticClass:"media-left"},[_c('b-icon',{attrs:{"icon":_vm.icon,"pack":_vm.iconPack,"both":"","size":"is-large","aria-hidden":""}})],1):_vm._e(),_vm._v(" "),_c('div',{staticClass:"media-content"},[(_vm.message)?_c('p',{staticClass:"text",domProps:{"innerHTML":_vm._s(_vm.message)}}):_vm._t("default")],2)])])])};
var __vue_staticRenderFns__$q = [];
/* style */
const __vue_inject_styles__$t = undefined;
/* scoped */
const __vue_scope_id__$t = undefined;
/* module identifier */
const __vue_module_identifier__$t = undefined;
/* functional template */
const __vue_is_functional_template__$t = false;
/* style inject */
/* style inject SSR */
var Notification = normalizeComponent_1(
{ render: __vue_render__$q, staticRenderFns: __vue_staticRenderFns__$q },
__vue_inject_styles__$t,
__vue_script__$t,
__vue_scope_id__$t,
__vue_is_functional_template__$t,
__vue_module_identifier__$t,
undefined,
undefined
);
var NoticeMixin = {
props: {
type: {
type: String,
default: 'is-dark'
},
message: String,
duration: Number,
queue: {
type: Boolean,
default: undefined
},
position: {
type: String,
default: 'is-top',
validator: function validator(value) {
return ['is-top-right', 'is-top', 'is-top-left', 'is-bottom-right', 'is-bottom', 'is-bottom-left'].indexOf(value) > -1;
}
},
container: String
},
data: function data() {
return {
isActive: false,
parentTop: null,
parentBottom: null,
newContainer: this.container || config.defaultContainerElement
};
},
computed: {
correctParent: function correctParent() {
switch (this.position) {
case 'is-top-right':
case 'is-top':
case 'is-top-left':
return this.parentTop;
case 'is-bottom-right':
case 'is-bottom':
case 'is-bottom-left':
return this.parentBottom;
}
},
transition: function transition() {
switch (this.position) {
case 'is-top-right':
case 'is-top':
case 'is-top-left':
return {
enter: 'fadeInDown',
leave: 'fadeOut'
};
case 'is-bottom-right':
case 'is-bottom':
case 'is-bottom-left':
return {
enter: 'fadeInUp',
leave: 'fadeOut'
};
}
}
},
methods: {
shouldQueue: function shouldQueue() {
var queue = this.queue !== undefined ? this.queue : config.defaultNoticeQueue;
if (!queue) return false;
return this.parentTop.childElementCount > 0 || this.parentBottom.childElementCount > 0;
},
close: function close() {
var _this = this;
clearTimeout(this.timer);
this.isActive = false; // Timeout for the animation complete before destroying
setTimeout(function () {
_this.$destroy();
removeElement(_this.$el);
}, 150);
},
showNotice: function showNotice() {
var _this2 = this;
if (this.shouldQueue()) {
// Call recursively if should queue
setTimeout(function () {
return _this2.showNotice();
}, 250);
return;
}
this.correctParent.insertAdjacentElement('afterbegin', this.$el);
this.isActive = true;
if (!this.indefinite) {
this.timer = setTimeout(function () {
return _this2.close();
}, this.newDuration);
}
},
setupContainer: function setupContainer() {
this.parentTop = document.querySelector((this.newContainer ? this.newContainer : 'body') + '>.notices.is-top');
this.parentBottom = document.querySelector((this.newContainer ? this.newContainer : 'body') + '>.notices.is-bottom');
if (this.parentTop && this.parentBottom) return;
if (!this.parentTop) {
this.parentTop = document.createElement('div');
this.parentTop.className = 'notices is-top';
}
if (!this.parentBottom) {
this.parentBottom = document.createElement('div');
this.parentBottom.className = 'notices is-bottom';
}
var container = document.querySelector(this.newContainer) || document.body;
container.appendChild(this.parentTop);
container.appendChild(this.parentBottom);
if (this.newContainer) {
this.parentTop.classList.add('has-custom-container');
this.parentBottom.classList.add('has-custom-container');
}
}
},
beforeMount: function beforeMount() {
this.setupContainer();
},
mounted: function mounted() {
this.showNotice();
}
};
//
var script$u = {
name: 'BNotificationNotice',
mixins: [NoticeMixin],
props: {
indefinite: {
type: Boolean,
default: false
}
},
data: function data() {
return {
newDuration: this.duration || config.defaultNotificationDuration
};
}
};
/* script */
const __vue_script__$u = script$u;
/* template */
var __vue_render__$r = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('b-notification',_vm._b({on:{"close":_vm.close}},'b-notification',_vm.$options.propsData,false))};
var __vue_staticRenderFns__$r = [];
/* style */
const __vue_inject_styles__$u = undefined;
/* scoped */
const __vue_scope_id__$u = undefined;
/* module identifier */
const __vue_module_identifier__$u = undefined;
/* functional template */
const __vue_is_functional_template__$u = false;
/* style inject */
/* style inject SSR */
var NotificationNotice = normalizeComponent_1(
{ render: __vue_render__$r, staticRenderFns: __vue_staticRenderFns__$r },
__vue_inject_styles__$u,
__vue_script__$u,
__vue_scope_id__$u,
__vue_is_functional_template__$u,
__vue_module_identifier__$u,
undefined,
undefined
);
var NotificationProgrammatic = {
open: function open(params) {
var parent;
if (typeof params === 'string') {
params = {
message: params
};
}
var defaultParam = {
position: config.defaultNotificationPosition || 'is-top-right'
};
if (params.parent) {
parent = params.parent;
delete params.parent;
}
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : Vue;
var NotificationNoticeComponent = vm.extend(NotificationNotice);
return new NotificationNoticeComponent({
parent: parent,
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin$h = {
install: function install(Vue) {
registerComponent(Vue, Notification);
registerComponentProgrammatic(Vue, 'notification', NotificationProgrammatic);
}
};
use(Plugin$h);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$v = {
name: 'NavbarBurger',
props: {
isOpened: {
type: Boolean,
default: false
}
}
};
/* script */
const __vue_script__$v = script$v;
/* template */
var __vue_render__$s = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('a',_vm._g({staticClass:"navbar-burger burger",class:{ 'is-active': _vm.isOpened },attrs:{"role":"button","aria-label":"menu","aria-expanded":_vm.isOpened}},_vm.$listeners),[_c('span',{attrs:{"aria-hidden":"true"}}),_vm._v(" "),_c('span',{attrs:{"aria-hidden":"true"}}),_vm._v(" "),_c('span',{attrs:{"aria-hidden":"true"}})])};
var __vue_staticRenderFns__$s = [];
/* style */
const __vue_inject_styles__$v = undefined;
/* scoped */
const __vue_scope_id__$v = undefined;
/* module identifier */
const __vue_module_identifier__$v = undefined;
/* functional template */
const __vue_is_functional_template__$v = false;
/* style inject */
/* style inject SSR */
var NavbarBurger = normalizeComponent_1(
{ render: __vue_render__$s, staticRenderFns: __vue_staticRenderFns__$s },
__vue_inject_styles__$v,
__vue_script__$v,
__vue_scope_id__$v,
__vue_is_functional_template__$v,
__vue_module_identifier__$v,
undefined,
undefined
);
var isTouch = typeof window !== 'undefined' && ('ontouchstart' in window || navigator.msMaxTouchPoints > 0);
var events = isTouch ? ['touchstart', 'click'] : ['click'];
var instances = [];
function processArgs(bindingValue) {
var isFunction = typeof bindingValue === 'function';
if (!isFunction && _typeof(bindingValue) !== 'object') {
throw new Error("v-click-outside: Binding value should be a function or an object, typeof ".concat(bindingValue, " given"));
}
return {
handler: isFunction ? bindingValue : bindingValue.handler,
middleware: bindingValue.middleware || function (isClickOutside) {
return isClickOutside;
},
events: bindingValue.events || events
};
}
function onEvent(_ref) {
var el = _ref.el,
event = _ref.event,
handler = _ref.handler,
middleware = _ref.middleware;
var isClickOutside = event.target !== el && !el.contains(event.target);
if (!isClickOutside) {
return;
}
if (middleware(event, el)) {
handler(event, el);
}
}
function bind$1(el, _ref2) {
var value = _ref2.value;
var _processArgs = processArgs(value),
_handler = _processArgs.handler,
middleware = _processArgs.middleware,
events = _processArgs.events;
var instance = {
el: el,
eventHandlers: events.map(function (eventName) {
return {
event: eventName,
handler: function handler(event) {
return onEvent({
event: event,
el: el,
handler: _handler,
middleware: middleware
});
}
};
})
};
instance.eventHandlers.forEach(function (_ref3) {
var event = _ref3.event,
handler = _ref3.handler;
return document.addEventListener(event, handler);
});
instances.push(instance);
}
function update(el, _ref4) {
var value = _ref4.value;
var _processArgs2 = processArgs(value),
_handler2 = _processArgs2.handler,
middleware = _processArgs2.middleware,
events = _processArgs2.events;
var instance = instances.find(function (instance) {
return instance.el === el;
});
instance.eventHandlers.forEach(function (_ref5) {
var event = _ref5.event,
handler = _ref5.handler;
return document.removeEventListener(event, handler);
});
instance.eventHandlers = events.map(function (eventName) {
return {
event: eventName,
handler: function handler(event) {
return onEvent({
event: event,
el: el,
handler: _handler2,
middleware: middleware
});
}
};
});
instance.eventHandlers.forEach(function (_ref6) {
var event = _ref6.event,
handler = _ref6.handler;
return document.addEventListener(event, handler);
});
}
function unbind$1(el) {
var instance = instances.find(function (instance) {
return instance.el === el;
});
instance.eventHandlers.forEach(function (_ref7) {
var event = _ref7.event,
handler = _ref7.handler;
return document.removeEventListener(event, handler);
});
}
var directive$1 = {
bind: bind$1,
update: update,
unbind: unbind$1,
instances: instances
};
var FIXED_TOP_CLASS = 'is-fixed-top';
var BODY_FIXED_TOP_CLASS = 'has-navbar-fixed-top';
var BODY_SPACED_FIXED_TOP_CLASS = 'has-spaced-navbar-fixed-top';
var FIXED_BOTTOM_CLASS = 'is-fixed-bottom';
var BODY_FIXED_BOTTOM_CLASS = 'has-navbar-fixed-bottom';
var BODY_SPACED_FIXED_BOTTOM_CLASS = 'has-spaced-navbar-fixed-bottom';
var isFilled = function isFilled(str) {
return !!str;
};
var script$w = {
name: 'BNavbar',
components: {
NavbarBurger: NavbarBurger
},
directives: {
clickOutside: directive$1
},
props: {
type: [String, Object],
transparent: {
type: Boolean,
default: false
},
fixedTop: {
type: Boolean,
default: false
},
fixedBottom: {
type: Boolean,
default: false
},
isActive: {
type: Boolean,
default: false
},
wrapperClass: {
type: String
},
closeOnClick: {
type: Boolean,
default: true
},
mobileBurger: {
type: Boolean,
default: true
},
spaced: Boolean,
shadow: Boolean
},
data: function data() {
return {
internalIsActive: this.isActive
};
},
computed: {
isOpened: function isOpened() {
return this.internalIsActive;
},
computedClasses: function computedClasses() {
var _ref;
return [this.type, (_ref = {}, _defineProperty(_ref, FIXED_TOP_CLASS, this.fixedTop), _defineProperty(_ref, FIXED_BOTTOM_CLASS, this.fixedBottom), _defineProperty(_ref, 'is-spaced', this.spaced), _defineProperty(_ref, 'has-shadow', this.shadow), _defineProperty(_ref, 'is-transparent', this.transparent), _ref)];
}
},
watch: {
isActive: {
handler: function handler(isActive) {
this.internalIsActive = isActive;
},
immediate: true
},
fixedTop: {
handler: function handler(isSet) {
this.checkIfFixedPropertiesAreColliding();
var className = this.spaced ? BODY_SPACED_FIXED_TOP_CLASS : BODY_FIXED_TOP_CLASS;
if (isSet) {
return this.setBodyClass(className);
}
this.removeBodyClass(className);
},
immediate: true
},
fixedBottom: {
handler: function handler(isSet) {
this.checkIfFixedPropertiesAreColliding();
var className = this.spaced ? BODY_SPACED_FIXED_BOTTOM_CLASS : BODY_FIXED_BOTTOM_CLASS;
if (isSet) {
return this.setBodyClass(className);
}
this.removeBodyClass(className);
},
immediate: true
}
},
methods: {
toggleActive: function toggleActive() {
this.internalIsActive = !this.internalIsActive;
this.emitUpdateParentEvent();
},
closeMenu: function closeMenu() {
if (this.closeOnClick) {
this.internalIsActive = false;
this.emitUpdateParentEvent();
}
},
emitUpdateParentEvent: function emitUpdateParentEvent() {
this.$emit('update:isActive', this.internalIsActive);
},
setBodyClass: function setBodyClass(className) {
if (typeof window !== 'undefined') {
document.body.classList.add(className);
}
},
removeBodyClass: function removeBodyClass(className) {
if (typeof window !== 'undefined') {
document.body.classList.remove(className);
}
},
checkIfFixedPropertiesAreColliding: function checkIfFixedPropertiesAreColliding() {
var areColliding = this.fixedTop && this.fixedBottom;
if (areColliding) {
throw new Error('You should choose if the BNavbar is fixed bottom or fixed top, but not both');
}
},
genNavbar: function genNavbar(createElement) {
var navBarSlots = [this.genNavbarBrandNode(createElement), this.genNavbarSlotsNode(createElement)];
if (!isFilled(this.wrapperClass)) {
return this.genNavbarSlots(createElement, navBarSlots);
} // It wraps the slots into a div with the provided wrapperClass prop
var navWrapper = createElement('div', {
class: this.wrapperClass
}, navBarSlots);
return this.genNavbarSlots(createElement, [navWrapper]);
},
genNavbarSlots: function genNavbarSlots(createElement, slots) {
return createElement('nav', {
staticClass: 'navbar',
class: this.computedClasses,
attrs: {
role: 'navigation',
'aria-label': 'main navigation'
},
directives: [{
name: 'click-outside',
value: this.closeMenu
}]
}, slots);
},
genNavbarBrandNode: function genNavbarBrandNode(createElement) {
return createElement('div', {
class: 'navbar-brand'
}, [this.$slots.brand, this.genBurgerNode(createElement)]);
},
genBurgerNode: function genBurgerNode(createElement) {
if (this.mobileBurger) {
var defaultBurgerNode = createElement('navbar-burger', {
props: {
isOpened: this.isOpened
},
on: {
click: this.toggleActive
}
});
var hasBurgerSlot = !!this.$scopedSlots.burger;
return hasBurgerSlot ? this.$scopedSlots.burger({
isOpened: this.isOpened,
toggleActive: this.toggleActive
}) : defaultBurgerNode;
}
},
genNavbarSlotsNode: function genNavbarSlotsNode(createElement) {
return createElement('div', {
staticClass: 'navbar-menu',
class: {
'is-active': this.isOpened
}
}, [this.genMenuPosition(createElement, 'start'), this.genMenuPosition(createElement, 'end')]);
},
genMenuPosition: function genMenuPosition(createElement, positionName) {
return createElement('div', {
staticClass: "navbar-".concat(positionName)
}, this.$slots[positionName]);
}
},
beforeDestroy: function beforeDestroy() {
this.removeBodyClass(FIXED_BOTTOM_CLASS);
this.removeBodyClass(FIXED_TOP_CLASS);
},
render: function render(createElement, fn) {
return this.genNavbar(createElement);
}
};
/* script */
const __vue_script__$w = script$w;
/* template */
/* style */
const __vue_inject_styles__$w = undefined;
/* scoped */
const __vue_scope_id__$w = undefined;
/* module identifier */
const __vue_module_identifier__$w = undefined;
/* functional template */
const __vue_is_functional_template__$w = undefined;
/* style inject */
/* style inject SSR */
var Navbar = normalizeComponent_1(
{},
__vue_inject_styles__$w,
__vue_script__$w,
__vue_scope_id__$w,
__vue_is_functional_template__$w,
__vue_module_identifier__$w,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
//
//
var clickableWhiteList = ['div', 'span'];
var script$x = {
name: 'BNavbarItem',
inheritAttrs: false,
props: {
tag: {
type: String,
default: 'a'
},
active: Boolean
},
methods: {
/**
* Keypress event that is bound to the document
*/
keyPress: function keyPress(event) {
// Esc key
// TODO: use code instead (because keyCode is actually deprecated)
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
if (event.keyCode === 27) {
this.$parent.closeMenu();
}
},
/**
* Close parent if clicked outside.
*/
handleClickEvent: function handleClickEvent(event) {
var isOnWhiteList = clickableWhiteList.some(function (item) {
return item === event.target.localName;
});
if (!isOnWhiteList) {
if (this.$parent.$data._isNavDropdown) {
this.$parent.closeMenu();
this.$parent.$parent.closeMenu();
} else {
this.$parent.closeMenu();
}
}
}
},
mounted: function mounted() {
if (typeof window !== 'undefined') {
this.$el.addEventListener('click', this.handleClickEvent);
document.addEventListener('keyup', this.keyPress);
}
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
this.$el.removeEventListener('click', this.handleClickEvent);
document.removeEventListener('keyup', this.keyPress);
}
}
};
/* script */
const __vue_script__$x = script$x;
/* template */
var __vue_render__$t = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,_vm._g(_vm._b({tag:"component",staticClass:"navbar-item",class:{
'is-active': _vm.active
}},'component',_vm.$attrs,false),_vm.$listeners),[_vm._t("default")],2)};
var __vue_staticRenderFns__$t = [];
/* style */
const __vue_inject_styles__$x = undefined;
/* scoped */
const __vue_scope_id__$x = undefined;
/* module identifier */
const __vue_module_identifier__$x = undefined;
/* functional template */
const __vue_is_functional_template__$x = false;
/* style inject */
/* style inject SSR */
var NavbarItem = normalizeComponent_1(
{ render: __vue_render__$t, staticRenderFns: __vue_staticRenderFns__$t },
__vue_inject_styles__$x,
__vue_script__$x,
__vue_scope_id__$x,
__vue_is_functional_template__$x,
__vue_module_identifier__$x,
undefined,
undefined
);
//
var script$y = {
name: 'BNavbarDropdown',
directives: {
clickOutside: directive$1
},
props: {
label: String,
hoverable: Boolean,
active: Boolean,
right: Boolean,
arrowless: Boolean,
boxed: Boolean
},
data: function data() {
return {
newActive: this.active,
_isNavDropdown: true // Used internally by NavbarItem
};
},
watch: {
active: function active(value) {
this.newActive = value;
}
},
methods: {
showMenu: function showMenu() {
this.newActive = true;
},
/**
* See naming convetion of navbaritem
*/
closeMenu: function closeMenu() {
this.newActive = false;
}
}
};
/* script */
const __vue_script__$y = script$y;
/* template */
var __vue_render__$u = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeMenu),expression:"closeMenu"}],staticClass:"navbar-item has-dropdown",class:{
'is-hoverable': _vm.hoverable,
'is-active': _vm.newActive
}},[_c('a',{staticClass:"navbar-link",class:{
'is-arrowless': _vm.arrowless
},on:{"click":function($event){_vm.newActive = !_vm.newActive;}}},[(_vm.label)?[_vm._v(_vm._s(_vm.label))]:_vm._t("label")],2),_vm._v(" "),_c('div',{staticClass:"navbar-dropdown",class:{
'is-right': _vm.right,
'is-boxed': _vm.boxed
}},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$u = [];
/* style */
const __vue_inject_styles__$y = undefined;
/* scoped */
const __vue_scope_id__$y = undefined;
/* module identifier */
const __vue_module_identifier__$y = undefined;
/* functional template */
const __vue_is_functional_template__$y = false;
/* style inject */
/* style inject SSR */
var NavbarDropdown = normalizeComponent_1(
{ render: __vue_render__$u, staticRenderFns: __vue_staticRenderFns__$u },
__vue_inject_styles__$y,
__vue_script__$y,
__vue_scope_id__$y,
__vue_is_functional_template__$y,
__vue_module_identifier__$y,
undefined,
undefined
);
var Plugin$i = {
install: function install(Vue) {
registerComponent(Vue, Navbar);
registerComponent(Vue, NavbarItem);
registerComponent(Vue, NavbarDropdown);
}
};
use(Plugin$i);
var _components$4;
var script$z = {
name: 'BNumberinput',
components: (_components$4 = {}, _defineProperty(_components$4, Icon.name, Icon), _defineProperty(_components$4, Input.name, Input), _components$4),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: Number,
min: [Number, String],
max: [Number, String],
step: [Number, String],
disabled: Boolean,
type: {
type: String,
default: 'is-primary'
},
editable: {
type: Boolean,
default: true
},
controls: {
type: Boolean,
default: true
},
controlsRounded: {
type: Boolean,
default: false
},
controlsPosition: String
},
data: function data() {
return {
newValue: !isNaN(this.value) ? this.value : parseFloat(this.min) || 0,
newStep: this.step || 1,
_elementRef: 'input'
};
},
computed: {
computedValue: {
get: function get() {
return this.newValue;
},
set: function set(value) {
var newValue = value;
if (value === '') {
newValue = parseFloat(this.min) || null;
}
this.newValue = newValue;
this.$emit('input', newValue);
!this.isValid && this.$refs.input.checkHtml5Validity();
}
},
fieldClasses: function fieldClasses() {
return [{
'has-addons': this.controlsPosition === 'compact'
}, {
'is-grouped': this.controlsPosition !== 'compact'
}, {
'is-expanded': this.expanded
}];
},
buttonClasses: function buttonClasses() {
return [this.type, this.size, {
'is-rounded': this.controlsRounded
}];
},
minNumber: function minNumber() {
return typeof this.min === 'string' ? parseFloat(this.min) : this.min;
},
maxNumber: function maxNumber() {
return typeof this.max === 'string' ? parseFloat(this.max) : this.max;
},
stepNumber: function stepNumber() {
return typeof this.newStep === 'string' ? parseFloat(this.newStep) : this.newStep;
},
disabledMin: function disabledMin() {
return this.computedValue - this.stepNumber < this.minNumber;
},
disabledMax: function disabledMax() {
return this.computedValue + this.stepNumber > this.maxNumber;
},
stepDecimals: function stepDecimals() {
var step = this.stepNumber.toString();
var index = step.indexOf('.');
if (index >= 0) {
return step.substring(index + 1).length;
}
return 0;
}
},
watch: {
/**
* When v-model is changed:
* 1. Set internal value.
*/
value: function value(_value) {
this.newValue = _value;
}
},
methods: {
decrement: function decrement() {
if (typeof this.minNumber === 'undefined' || this.computedValue - this.stepNumber >= this.minNumber) {
var value = this.computedValue - this.stepNumber;
this.computedValue = parseFloat(value.toFixed(this.stepDecimals));
}
},
increment: function increment() {
if (typeof this.maxNumber === 'undefined' || this.computedValue + this.stepNumber <= this.maxNumber) {
var value = this.computedValue + this.stepNumber;
this.computedValue = parseFloat(value.toFixed(this.stepDecimals));
}
},
onControlClick: function onControlClick(event, inc) {
// IE 11 -> filter click event
if (event.detail !== 0 || event.type === 'click') return;
if (inc) this.increment();else this.decrement();
},
onStartLongPress: function onStartLongPress(event, inc) {
var _this = this;
if (event.button !== 0 && event.type !== 'touchstart') return;
this._$intervalTime = new Date();
clearInterval(this._$intervalRef);
this._$intervalRef = setInterval(function () {
if (inc) _this.increment();else _this.decrement();
}, 250);
},
onStopLongPress: function onStopLongPress(inc) {
if (!this._$intervalRef) return;
var d = new Date();
if (d - this._$intervalTime < 250) {
if (inc) this.increment();else this.decrement();
}
clearInterval(this._$intervalRef);
this._$intervalRef = null;
}
}
};
/* script */
const __vue_script__$z = script$z;
/* template */
var __vue_render__$v = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-numberinput field",class:_vm.fieldClasses},[(_vm.controls)?_c('p',{staticClass:"control",on:{"mouseup":function($event){return _vm.onStopLongPress(false)},"mouseleave":function($event){return _vm.onStopLongPress(false)},"touchend":function($event){return _vm.onStopLongPress(false)},"touchcancel":function($event){return _vm.onStopLongPress(false)}}},[_c('button',{staticClass:"button",class:_vm.buttonClasses,attrs:{"type":"button","disabled":_vm.disabled || _vm.disabledMin},on:{"mousedown":function($event){return _vm.onStartLongPress($event, false)},"touchstart":function($event){$event.preventDefault();return _vm.onStartLongPress($event, false)},"click":function($event){return _vm.onControlClick($event, false)}}},[_c('b-icon',{attrs:{"icon":"minus","pack":_vm.iconPack,"size":_vm.iconSize}})],1)]):_vm._e(),_vm._v(" "),_c('b-input',_vm._b({ref:"input",attrs:{"type":"number","step":_vm.newStep,"max":_vm.max,"min":_vm.min,"size":_vm.size,"disabled":_vm.disabled,"readonly":!_vm.editable,"loading":_vm.loading,"rounded":_vm.rounded,"icon":_vm.icon,"icon-pack":_vm.iconPack,"autocomplete":_vm.autocomplete,"expanded":_vm.expanded,"use-html5-validation":_vm.useHtml5Validation},on:{"focus":function($event){return _vm.$emit('focus', $event)},"blur":function($event){return _vm.$emit('blur', $event)}},model:{value:(_vm.computedValue),callback:function ($$v) {_vm.computedValue=_vm._n($$v);},expression:"computedValue"}},'b-input',_vm.$attrs,false)),_vm._v(" "),(_vm.controls)?_c('p',{staticClass:"control",on:{"mouseup":function($event){return _vm.onStopLongPress(true)},"mouseleave":function($event){return _vm.onStopLongPress(true)},"touchend":function($event){return _vm.onStopLongPress(true)},"touchcancel":function($event){return _vm.onStopLongPress(true)}}},[_c('button',{staticClass:"button",class:_vm.buttonClasses,attrs:{"type":"button","disabled":_vm.disabled || _vm.disabledMax},on:{"mousedown":function($event){return _vm.onStartLongPress($event, true)},"touchstart":function($event){$event.preventDefault();return _vm.onStartLongPress($event, true)},"click":function($event){return _vm.onControlClick($event, true)}}},[_c('b-icon',{attrs:{"icon":"plus","pack":_vm.iconPack,"size":_vm.iconSize}})],1)]):_vm._e()],1)};
var __vue_staticRenderFns__$v = [];
/* style */
const __vue_inject_styles__$z = undefined;
/* scoped */
const __vue_scope_id__$z = undefined;
/* module identifier */
const __vue_module_identifier__$z = undefined;
/* functional template */
const __vue_is_functional_template__$z = false;
/* style inject */
/* style inject SSR */
var Numberinput = normalizeComponent_1(
{ render: __vue_render__$v, staticRenderFns: __vue_staticRenderFns__$v },
__vue_inject_styles__$z,
__vue_script__$z,
__vue_scope_id__$z,
__vue_is_functional_template__$z,
__vue_module_identifier__$z,
undefined,
undefined
);
var Plugin$j = {
install: function install(Vue) {
registerComponent(Vue, Numberinput);
}
};
use(Plugin$j);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$A = {
name: 'BPaginationButton',
props: {
page: {
type: Object,
required: true
},
tag: {
type: String,
default: 'a',
validator: function validator(value) {
return ['a', 'button', 'input', 'router-link', 'nuxt-link', 'n-link', 'NuxtLink', 'NLink'].indexOf(value) >= 0;
}
},
disabled: {
type: Boolean,
default: false
}
},
computed: {
href: function href() {
if (this.tag === 'a') {
return '#';
}
},
isDisabled: function isDisabled() {
return this.disabled || this.page.disabled;
}
}
};
/* script */
const __vue_script__$A = script$A;
/* template */
var __vue_render__$w = function () {
var _obj;
var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,_vm._b({tag:"component",staticClass:"pagination-link",class:( _obj = { 'is-current': _vm.page.isCurrent }, _obj[_vm.page.class] = true, _obj ),attrs:{"role":"button","href":_vm.href,"disabled":_vm.isDisabled,"aria-label":_vm.page['aria-label'],"aria-current":_vm.page.isCurrent},on:{"click":function($event){$event.preventDefault();return _vm.page.click($event)}}},'component',_vm.$attrs,false),[_vm._t("default",[_vm._v(_vm._s(_vm.page.number))])],2)};
var __vue_staticRenderFns__$w = [];
/* style */
const __vue_inject_styles__$A = undefined;
/* scoped */
const __vue_scope_id__$A = undefined;
/* module identifier */
const __vue_module_identifier__$A = undefined;
/* functional template */
const __vue_is_functional_template__$A = false;
/* style inject */
/* style inject SSR */
var PaginationButton = normalizeComponent_1(
{ render: __vue_render__$w, staticRenderFns: __vue_staticRenderFns__$w },
__vue_inject_styles__$A,
__vue_script__$A,
__vue_scope_id__$A,
__vue_is_functional_template__$A,
__vue_module_identifier__$A,
undefined,
undefined
);
var _components$5;
var script$B = {
name: 'BPagination',
components: (_components$5 = {}, _defineProperty(_components$5, Icon.name, Icon), _defineProperty(_components$5, PaginationButton.name, PaginationButton), _components$5),
props: {
total: [Number, String],
perPage: {
type: [Number, String],
default: 20
},
current: {
type: [Number, String],
default: 1
},
rangeBefore: {
type: [Number, String],
default: 1
},
rangeAfter: {
type: [Number, String],
default: 1
},
size: String,
simple: Boolean,
rounded: Boolean,
order: String,
iconPack: String,
iconPrev: {
type: String,
default: config.defaultIconPrev
},
iconNext: {
type: String,
default: config.defaultIconNext
},
ariaNextLabel: String,
ariaPreviousLabel: String,
ariaPageLabel: String,
ariaCurrentLabel: String
},
computed: {
rootClasses: function rootClasses() {
return [this.order, this.size, {
'is-simple': this.simple,
'is-rounded': this.rounded
}];
},
beforeCurrent: function beforeCurrent() {
return parseInt(this.rangeBefore);
},
afterCurrent: function afterCurrent() {
return parseInt(this.rangeAfter);
},
/**
* Total page size (count).
*/
pageCount: function pageCount() {
return Math.ceil(this.total / this.perPage);
},
/**
* First item of the page (count).
*/
firstItem: function firstItem() {
var firstItem = this.current * this.perPage - this.perPage + 1;
return firstItem >= 0 ? firstItem : 0;
},
/**
* Check if previous button is available.
*/
hasPrev: function hasPrev() {
return this.current > 1;
},
/**
* Check if first page button should be visible.
*/
hasFirst: function hasFirst() {
return this.current >= 2 + this.beforeCurrent;
},
/**
* Check if first ellipsis should be visible.
*/
hasFirstEllipsis: function hasFirstEllipsis() {
return this.current >= this.beforeCurrent + 4;
},
/**
* Check if last page button should be visible.
*/
hasLast: function hasLast() {
return this.current <= this.pageCount - (1 + this.afterCurrent);
},
/**
* Check if last ellipsis should be visible.
*/
hasLastEllipsis: function hasLastEllipsis() {
return this.current < this.pageCount - (2 + this.afterCurrent);
},
/**
* Check if next button is available.
*/
hasNext: function hasNext() {
return this.current < this.pageCount;
},
/**
* Get near pages, 1 before and 1 after the current.
* Also add the click event to the array.
*/
pagesInRange: function pagesInRange() {
if (this.simple) return;
var left = Math.max(1, this.current - this.beforeCurrent);
if (left - 1 === 2) {
left--; // Do not show the ellipsis if there is only one to hide
}
var right = Math.min(this.current + this.afterCurrent, this.pageCount);
if (this.pageCount - right === 2) {
right++; // Do not show the ellipsis if there is only one to hide
}
var pages = [];
for (var i = left; i <= right; i++) {
pages.push(this.getPage(i));
}
return pages;
}
},
watch: {
/**
* If current page is trying to be greater than page count, set to last.
*/
pageCount: function pageCount(value) {
if (this.current > value) this.last();
}
},
methods: {
/**
* Previous button click listener.
*/
prev: function prev(event) {
this.changePage(this.current - 1, event);
},
/**
* Next button click listener.
*/
next: function next(event) {
this.changePage(this.current + 1, event);
},
/**
* First button click listener.
*/
first: function first(event) {
this.changePage(1, event);
},
/**
* Last button click listener.
*/
last: function last(event) {
this.changePage(this.pageCount, event);
},
changePage: function changePage(num, event) {
if (this.current === num || num < 1 || num > this.pageCount) return;
this.$emit('change', num);
this.$emit('update:current', num); // Set focus on element to keep tab order
if (event && event.target) {
this.$nextTick(function () {
return event.target.focus();
});
}
},
getPage: function getPage(num) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return {
number: num,
isCurrent: this.current === num,
click: function click(event) {
return _this.changePage(num, event);
},
disabled: options.disabled || false,
class: options.class || '',
'aria-label': options['aria-label'] || this.getAriaPageLabel(num, this.current === num)
};
},
/**
* Get text for aria-label according to page number.
*/
getAriaPageLabel: function getAriaPageLabel(pageNumber, isCurrent) {
if (this.ariaPageLabel && (!isCurrent || !this.ariaCurrentLabel)) {
return this.ariaPageLabel + ' ' + pageNumber + '.';
} else if (this.ariaPageLabel && isCurrent && this.ariaCurrentLabel) {
return this.ariaCurrentLabel + ', ' + this.ariaPageLabel + ' ' + pageNumber + '.';
}
return null;
}
}
};
/* script */
const __vue_script__$B = script$B;
/* template */
var __vue_render__$x = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('nav',{staticClass:"pagination",class:_vm.rootClasses},[(_vm.$scopedSlots.previous)?_vm._t("previous",[_c('b-icon',{attrs:{"icon":_vm.iconPrev,"pack":_vm.iconPack,"both":"","aria-hidden":"true"}})],{"page":_vm.getPage(_vm.current - 1, {
disabled: !_vm.hasPrev,
class: 'pagination-previous',
'aria-label': _vm.ariaPreviousLabel
})}):_c('BPaginationButton',{staticClass:"pagination-previous",attrs:{"disabled":!_vm.hasPrev,"page":_vm.getPage(_vm.current - 1)}},[_c('b-icon',{attrs:{"icon":_vm.iconPrev,"pack":_vm.iconPack,"both":"","aria-hidden":"true"}})],1),_vm._v(" "),(_vm.$scopedSlots.next)?_vm._t("next",[_c('b-icon',{attrs:{"icon":_vm.iconNext,"pack":_vm.iconPack,"both":"","aria-hidden":"true"}})],{"page":_vm.getPage(_vm.current + 1, {
disabled: !_vm.hasNext,
class: 'pagination-next',
'aria-label': _vm.ariaNextLabel
})}):_c('BPaginationButton',{staticClass:"pagination-next",attrs:{"disabled":!_vm.hasNext,"page":_vm.getPage(_vm.current + 1)}},[_c('b-icon',{attrs:{"icon":_vm.iconNext,"pack":_vm.iconPack,"both":"","aria-hidden":"true"}})],1),_vm._v(" "),(_vm.simple)?_c('small',{staticClass:"info"},[(_vm.perPage == 1)?[_vm._v("\n "+_vm._s(_vm.firstItem)+" / "+_vm._s(_vm.total)+"\n ")]:[_vm._v("\n "+_vm._s(_vm.firstItem)+"-"+_vm._s(Math.min(_vm.current * _vm.perPage, _vm.total))+" / "+_vm._s(_vm.total)+"\n ")]],2):_c('ul',{staticClass:"pagination-list"},[(_vm.hasFirst)?_c('li',[(_vm.$scopedSlots.default)?_vm._t("default",null,{"page":_vm.getPage(1)}):_c('BPaginationButton',{attrs:{"page":_vm.getPage(1)}})],2):_vm._e(),_vm._v(" "),(_vm.hasFirstEllipsis)?_c('li',[_c('span',{staticClass:"pagination-ellipsis"},[_vm._v("…")])]):_vm._e(),_vm._v(" "),_vm._l((_vm.pagesInRange),function(page){return _c('li',{key:page.number},[(_vm.$scopedSlots.default)?_vm._t("default",null,{"page":page}):_c('BPaginationButton',{attrs:{"page":page}})],2)}),_vm._v(" "),(_vm.hasLastEllipsis)?_c('li',[_c('span',{staticClass:"pagination-ellipsis"},[_vm._v("…")])]):_vm._e(),_vm._v(" "),(_vm.hasLast)?_c('li',[(_vm.$scopedSlots.default)?_vm._t("default",null,{"page":_vm.getPage(_vm.pageCount)}):_c('BPaginationButton',{attrs:{"page":_vm.getPage(_vm.pageCount)}})],2):_vm._e()],2)],2)};
var __vue_staticRenderFns__$x = [];
/* style */
const __vue_inject_styles__$B = undefined;
/* scoped */
const __vue_scope_id__$B = undefined;
/* module identifier */
const __vue_module_identifier__$B = undefined;
/* functional template */
const __vue_is_functional_template__$B = false;
/* style inject */
/* style inject SSR */
var Pagination = normalizeComponent_1(
{ render: __vue_render__$x, staticRenderFns: __vue_staticRenderFns__$x },
__vue_inject_styles__$B,
__vue_script__$B,
__vue_scope_id__$B,
__vue_is_functional_template__$B,
__vue_module_identifier__$B,
undefined,
undefined
);
var Plugin$k = {
install: function install(Vue) {
registerComponent(Vue, Pagination);
registerComponent(Vue, PaginationButton);
}
};
use(Plugin$k);
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$C = {
name: 'BProgress',
props: {
type: {
type: [String, Object],
default: 'is-darkgrey'
},
size: String,
value: {
type: Number,
default: undefined
},
max: {
type: Number,
default: 100
},
showValue: {
type: Boolean,
default: false
},
format: {
type: String,
default: 'raw',
validator: function validator(value) {
return ['raw', 'percent'].indexOf(value) >= 0;
}
},
precision: {
type: Number,
default: 2
},
keepTrailingZeroes: {
type: Boolean,
default: false
}
},
computed: {
isIndeterminate: function isIndeterminate() {
return this.value === undefined || this.value === null;
},
newType: function newType() {
return [this.size, this.type];
},
newValue: function newValue() {
if (this.value === undefined || this.value === null || isNaN(this.value)) {
return undefined;
}
if (this.format === 'percent') {
var _val = this.toFixed(this.value * this.max / 100);
return "".concat(_val, "%");
}
var val = this.toFixed(this.value);
return val;
}
},
watch: {
value: function value(_value) {
this.setValue(_value);
}
},
methods: {
/**
* When value is changed back to undefined, value of native progress get reset to 0.
* Need to add and remove the value attribute to have the indeterminate or not.
*/
setValue: function setValue(value) {
if (this.isIndeterminate) {
this.$refs.progress.removeAttribute('value');
} else {
this.$refs.progress.setAttribute('value', value);
}
},
// Custom function that imitate the javascript toFixed method with improved rounding
toFixed: function toFixed(num) {
var fixed = (+"".concat(Math.round(+"".concat(num, "e").concat(this.precision)), "e").concat(-this.precision)).toFixed(this.precision);
if (!this.keepTrailingZeroes) {
fixed = fixed.replace(/\.?0+$/, '');
}
return fixed;
}
},
mounted: function mounted() {
this.setValue(this.value);
}
};
/* script */
const __vue_script__$C = script$C;
/* template */
var __vue_render__$y = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"progress-wrapper"},[_c('progress',{ref:"progress",staticClass:"progress",class:_vm.newType,attrs:{"max":_vm.max}},[_vm._v(_vm._s(_vm.newValue))]),_vm._v(" "),(_vm.showValue)?_c('p',{staticClass:"progress-value"},[_vm._t("default",[_vm._v(_vm._s(_vm.newValue))])],2):_vm._e()])};
var __vue_staticRenderFns__$y = [];
/* style */
const __vue_inject_styles__$C = undefined;
/* scoped */
const __vue_scope_id__$C = undefined;
/* module identifier */
const __vue_module_identifier__$C = undefined;
/* functional template */
const __vue_is_functional_template__$C = false;
/* style inject */
/* style inject SSR */
var Progress = normalizeComponent_1(
{ render: __vue_render__$y, staticRenderFns: __vue_staticRenderFns__$y },
__vue_inject_styles__$C,
__vue_script__$C,
__vue_scope_id__$C,
__vue_is_functional_template__$C,
__vue_module_identifier__$C,
undefined,
undefined
);
var Plugin$l = {
install: function install(Vue) {
registerComponent(Vue, Progress);
}
};
use(Plugin$l);
//
var script$D = {
name: 'BRadio',
mixins: [CheckRadioMixin]
};
/* script */
const __vue_script__$D = script$D;
/* template */
var __vue_render__$z = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('label',{ref:"label",staticClass:"b-radio radio",class:[_vm.size, { 'is-disabled': _vm.disabled }],attrs:{"disabled":_vm.disabled},on:{"click":_vm.focus,"keydown":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.$refs.label.click()}}},[_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.computedValue),expression:"computedValue"}],ref:"input",attrs:{"type":"radio","disabled":_vm.disabled,"required":_vm.required,"name":_vm.name},domProps:{"value":_vm.nativeValue,"checked":_vm._q(_vm.computedValue,_vm.nativeValue)},on:{"click":function($event){$event.stopPropagation();},"change":function($event){_vm.computedValue=_vm.nativeValue;}}}),_vm._v(" "),_c('span',{staticClass:"check",class:_vm.type}),_vm._v(" "),_c('span',{staticClass:"control-label"},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$z = [];
/* style */
const __vue_inject_styles__$D = undefined;
/* scoped */
const __vue_scope_id__$D = undefined;
/* module identifier */
const __vue_module_identifier__$D = undefined;
/* functional template */
const __vue_is_functional_template__$D = false;
/* style inject */
/* style inject SSR */
var Radio = normalizeComponent_1(
{ render: __vue_render__$z, staticRenderFns: __vue_staticRenderFns__$z },
__vue_inject_styles__$D,
__vue_script__$D,
__vue_scope_id__$D,
__vue_is_functional_template__$D,
__vue_module_identifier__$D,
undefined,
undefined
);
//
var script$E = {
name: 'BRadioButton',
mixins: [CheckRadioMixin],
props: {
type: {
type: String,
default: 'is-primary'
},
expanded: Boolean
},
data: function data() {
return {
isFocused: false
};
}
};
/* script */
const __vue_script__$E = script$E;
/* template */
var __vue_render__$A = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"control",class:{ 'is-expanded': _vm.expanded }},[_c('label',{ref:"label",staticClass:"b-radio radio button",class:[_vm.newValue === _vm.nativeValue ? _vm.type : null, _vm.size, {
'is-disabled': _vm.disabled,
'is-focused': _vm.isFocused
}],attrs:{"disabled":_vm.disabled},on:{"click":_vm.focus,"keydown":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.$refs.label.click()}}},[_vm._t("default"),_vm._v(" "),_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.computedValue),expression:"computedValue"}],ref:"input",attrs:{"type":"radio","disabled":_vm.disabled,"required":_vm.required,"name":_vm.name},domProps:{"value":_vm.nativeValue,"checked":_vm._q(_vm.computedValue,_vm.nativeValue)},on:{"click":function($event){$event.stopPropagation();},"focus":function($event){_vm.isFocused = true;},"blur":function($event){_vm.isFocused = false;},"change":function($event){_vm.computedValue=_vm.nativeValue;}}})],2)])};
var __vue_staticRenderFns__$A = [];
/* style */
const __vue_inject_styles__$E = undefined;
/* scoped */
const __vue_scope_id__$E = undefined;
/* module identifier */
const __vue_module_identifier__$E = undefined;
/* functional template */
const __vue_is_functional_template__$E = false;
/* style inject */
/* style inject SSR */
var RadioButton = normalizeComponent_1(
{ render: __vue_render__$A, staticRenderFns: __vue_staticRenderFns__$A },
__vue_inject_styles__$E,
__vue_script__$E,
__vue_scope_id__$E,
__vue_is_functional_template__$E,
__vue_module_identifier__$E,
undefined,
undefined
);
var Plugin$m = {
install: function install(Vue) {
registerComponent(Vue, Radio);
registerComponent(Vue, RadioButton);
}
};
use(Plugin$m);
var script$F = {
name: 'BRate',
components: _defineProperty({}, Icon.name, Icon),
props: {
value: {
type: Number,
default: 0
},
max: {
type: Number,
default: 5
},
icon: {
type: String,
default: 'star'
},
iconPack: String,
size: String,
spaced: Boolean,
rtl: Boolean,
disabled: Boolean,
showScore: Boolean,
showText: Boolean,
customText: String,
texts: Array
},
data: function data() {
return {
newValue: this.value,
hoverValue: 0
};
},
computed: {
halfStyle: function halfStyle() {
return "width:".concat(this.valueDecimal, "%");
},
showMe: function showMe() {
var result = '';
if (this.showScore) {
result = this.disabled ? this.value : this.newValue;
if (result === 0) result = '';
} else if (this.showText) {
result = this.texts[Math.ceil(this.newValue) - 1];
}
return result;
},
valueDecimal: function valueDecimal() {
return this.value * 100 - Math.floor(this.value) * 100;
}
},
watch: {
// When v-model is changed set the new value.
value: function value(_value) {
this.newValue = _value;
}
},
methods: {
resetNewValue: function resetNewValue() {
if (this.disabled) return;
this.hoverValue = 0;
},
previewRate: function previewRate(index, event) {
if (this.disabled) return;
this.hoverValue = index;
event.stopPropagation();
},
confirmValue: function confirmValue(index) {
if (this.disabled) return;
this.newValue = index;
this.$emit('change', this.newValue);
this.$emit('input', this.newValue);
},
checkHalf: function checkHalf(index) {
var showWhenDisabled = this.disabled && this.valueDecimal > 0 && index - 1 < this.value && index > this.value;
return showWhenDisabled;
},
rateClass: function rateClass(index) {
var output = '';
var currentValue = this.hoverValue !== 0 ? this.hoverValue : this.newValue;
if (index <= currentValue) {
output = 'set-on';
} else if (this.disabled && Math.ceil(this.value) === index) {
output = 'set-half';
}
return output;
}
}
};
/* script */
const __vue_script__$F = script$F;
/* template */
var __vue_render__$B = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"rate",class:{ 'is-disabled': _vm.disabled, 'is-spaced': _vm.spaced, 'is-rtl': _vm.rtl }},[_vm._l((_vm.max),function(item,index){return _c('div',{key:index,staticClass:"rate-item",class:_vm.rateClass(item),on:{"mousemove":function($event){return _vm.previewRate(item, $event)},"mouseleave":_vm.resetNewValue,"click":function($event){$event.preventDefault();return _vm.confirmValue(item)}}},[_c('b-icon',{attrs:{"pack":_vm.iconPack,"icon":_vm.icon,"size":_vm.size}}),_vm._v(" "),(_vm.checkHalf(item))?_c('b-icon',{staticClass:"is-half",style:(_vm.halfStyle),attrs:{"pack":_vm.iconPack,"icon":_vm.icon,"size":_vm.size}}):_vm._e()],1)}),_vm._v(" "),(_vm.showText || _vm.showScore || _vm.customText)?_c('div',{staticClass:"rate-text",class:_vm.size},[_c('span',[_vm._v(_vm._s(_vm.showMe))]),_vm._v(" "),(_vm.customText && !_vm.showText)?_c('span',[_vm._v(_vm._s(_vm.customText))]):_vm._e()]):_vm._e()],2)};
var __vue_staticRenderFns__$B = [];
/* style */
const __vue_inject_styles__$F = undefined;
/* scoped */
const __vue_scope_id__$F = undefined;
/* module identifier */
const __vue_module_identifier__$F = undefined;
/* functional template */
const __vue_is_functional_template__$F = false;
/* style inject */
/* style inject SSR */
var Rate = normalizeComponent_1(
{ render: __vue_render__$B, staticRenderFns: __vue_staticRenderFns__$B },
__vue_inject_styles__$F,
__vue_script__$F,
__vue_scope_id__$F,
__vue_is_functional_template__$F,
__vue_module_identifier__$F,
undefined,
undefined
);
var Plugin$n = {
install: function install(Vue) {
registerComponent(Vue, Rate);
}
};
use(Plugin$n);
var Plugin$o = {
install: function install(Vue) {
registerComponent(Vue, Select);
}
};
use(Plugin$o);
//
var script$G = {
name: 'BTooltip',
props: {
active: {
type: Boolean,
default: true
},
type: String,
label: String,
position: {
type: String,
default: 'is-top',
validator: function validator(value) {
return ['is-top', 'is-bottom', 'is-left', 'is-right'].indexOf(value) > -1;
}
},
always: Boolean,
animated: Boolean,
square: Boolean,
dashed: Boolean,
multilined: Boolean,
size: {
type: String,
default: 'is-medium'
},
delay: Number
},
computed: {
newType: function newType() {
return this.type || config.defaultTooltipType;
},
newAnimated: function newAnimated() {
return this.animated || config.defaultTooltipAnimated;
},
newDelay: function newDelay() {
return this.delay || config.defaultTooltipDelay;
}
}
};
/* script */
const __vue_script__$G = script$G;
/* template */
var __vue_render__$C = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('span',{class:[_vm.newType, _vm.position, _vm.size, {
'b-tooltip': _vm.active,
'is-square': _vm.square,
'is-animated': _vm.newAnimated,
'is-always': _vm.always,
'is-multiline': _vm.multilined,
'is-dashed': _vm.dashed
}],style:({'transition-delay': (_vm.newDelay + "ms")}),attrs:{"data-label":_vm.label}},[_vm._t("default")],2)};
var __vue_staticRenderFns__$C = [];
/* style */
const __vue_inject_styles__$G = undefined;
/* scoped */
const __vue_scope_id__$G = undefined;
/* module identifier */
const __vue_module_identifier__$G = undefined;
/* functional template */
const __vue_is_functional_template__$G = false;
/* style inject */
/* style inject SSR */
var Tooltip = normalizeComponent_1(
{ render: __vue_render__$C, staticRenderFns: __vue_staticRenderFns__$C },
__vue_inject_styles__$G,
__vue_script__$G,
__vue_scope_id__$G,
__vue_is_functional_template__$G,
__vue_module_identifier__$G,
undefined,
undefined
);
var script$H = {
name: 'BSliderThumb',
components: _defineProperty({}, Tooltip.name, Tooltip),
inheritAttrs: false,
props: {
value: {
type: Number,
default: 0
},
type: {
type: String,
default: ''
},
tooltip: {
type: Boolean,
default: true
},
customFormatter: Function
},
data: function data() {
return {
isFocused: false,
dragging: false,
startX: 0,
startPosition: 0,
newPosition: null,
oldValue: this.value
};
},
computed: {
disabled: function disabled() {
return this.$parent.disabled;
},
max: function max() {
return this.$parent.max;
},
min: function min() {
return this.$parent.min;
},
step: function step() {
return this.$parent.step;
},
precision: function precision() {
return this.$parent.precision;
},
currentPosition: function currentPosition() {
return "".concat((this.value - this.min) / (this.max - this.min) * 100, "%");
},
wrapperStyle: function wrapperStyle() {
return {
left: this.currentPosition
};
},
tooltipLabel: function tooltipLabel() {
return typeof this.customFormatter !== 'undefined' ? this.customFormatter(this.value) : this.value.toString();
}
},
methods: {
onFocus: function onFocus() {
this.isFocused = true;
},
onBlur: function onBlur() {
this.isFocused = false;
},
onButtonDown: function onButtonDown(event) {
if (this.disabled) return;
event.preventDefault();
this.onDragStart(event);
if (typeof window !== 'undefined') {
document.addEventListener('mousemove', this.onDragging);
document.addEventListener('touchmove', this.onDragging);
document.addEventListener('mouseup', this.onDragEnd);
document.addEventListener('touchend', this.onDragEnd);
document.addEventListener('contextmenu', this.onDragEnd);
}
},
onLeftKeyDown: function onLeftKeyDown() {
if (this.disabled || this.value === this.min) return;
this.newPosition = parseFloat(this.currentPosition) - this.step / (this.max - this.min) * 100;
this.setPosition(this.newPosition);
this.$parent.emitValue('change');
},
onRightKeyDown: function onRightKeyDown() {
if (this.disabled || this.value === this.max) return;
this.newPosition = parseFloat(this.currentPosition) + this.step / (this.max - this.min) * 100;
this.setPosition(this.newPosition);
this.$parent.emitValue('change');
},
onHomeKeyDown: function onHomeKeyDown() {
if (this.disabled || this.value === this.min) return;
this.newPosition = 0;
this.setPosition(this.newPosition);
this.$parent.emitValue('change');
},
onEndKeyDown: function onEndKeyDown() {
if (this.disabled || this.value === this.max) return;
this.newPosition = 100;
this.setPosition(this.newPosition);
this.$parent.emitValue('change');
},
onDragStart: function onDragStart(event) {
this.dragging = true;
this.$emit('dragstart');
if (event.type === 'touchstart') {
event.clientX = event.touches[0].clientX;
}
this.startX = event.clientX;
this.startPosition = parseFloat(this.currentPosition);
this.newPosition = this.startPosition;
},
onDragging: function onDragging(event) {
if (this.dragging) {
if (event.type === 'touchmove') {
event.clientX = event.touches[0].clientX;
}
var diff = (event.clientX - this.startX) / this.$parent.sliderSize * 100;
this.newPosition = this.startPosition + diff;
this.setPosition(this.newPosition);
}
},
onDragEnd: function onDragEnd() {
this.dragging = false;
this.$emit('dragend');
if (this.value !== this.oldValue) {
this.$parent.emitValue('change');
}
this.setPosition(this.newPosition);
if (typeof window !== 'undefined') {
document.removeEventListener('mousemove', this.onDragging);
document.removeEventListener('touchmove', this.onDragging);
document.removeEventListener('mouseup', this.onDragEnd);
document.removeEventListener('touchend', this.onDragEnd);
document.removeEventListener('contextmenu', this.onDragEnd);
}
},
setPosition: function setPosition(percent) {
if (percent === null || isNaN(percent)) return;
if (percent < 0) {
percent = 0;
} else if (percent > 100) {
percent = 100;
}
var stepLength = 100 / ((this.max - this.min) / this.step);
var steps = Math.round(percent / stepLength);
var value = steps * stepLength / 100 * (this.max - this.min) + this.min;
value = parseFloat(value.toFixed(this.precision));
this.$emit('input', value);
if (!this.dragging && value !== this.oldValue) {
this.oldValue = value;
}
}
}
};
/* script */
const __vue_script__$H = script$H;
/* template */
var __vue_render__$D = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-slider-thumb-wrapper",class:{ 'is-dragging': _vm.dragging },style:(_vm.wrapperStyle)},[_c('b-tooltip',{attrs:{"label":_vm.tooltipLabel,"type":_vm.type,"always":_vm.dragging || _vm.isFocused,"active":!_vm.disabled && _vm.tooltip}},[_c('div',_vm._b({staticClass:"b-slider-thumb",attrs:{"tabindex":_vm.disabled ? false : 0},on:{"mousedown":_vm.onButtonDown,"touchstart":_vm.onButtonDown,"focus":_vm.onFocus,"blur":_vm.onBlur,"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"left",37,$event.key,["Left","ArrowLeft"])){ return null; }if('button' in $event && $event.button !== 0){ return null; }$event.preventDefault();return _vm.onLeftKeyDown($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"right",39,$event.key,["Right","ArrowRight"])){ return null; }if('button' in $event && $event.button !== 2){ return null; }$event.preventDefault();return _vm.onRightKeyDown($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"down",40,$event.key,["Down","ArrowDown"])){ return null; }$event.preventDefault();return _vm.onLeftKeyDown($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"up",38,$event.key,["Up","ArrowUp"])){ return null; }$event.preventDefault();return _vm.onRightKeyDown($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"home",undefined,$event.key,undefined)){ return null; }$event.preventDefault();return _vm.onHomeKeyDown($event)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"end",undefined,$event.key,undefined)){ return null; }$event.preventDefault();return _vm.onEndKeyDown($event)}]}},'div',_vm.$attrs,false))])],1)};
var __vue_staticRenderFns__$D = [];
/* style */
const __vue_inject_styles__$H = undefined;
/* scoped */
const __vue_scope_id__$H = undefined;
/* module identifier */
const __vue_module_identifier__$H = undefined;
/* functional template */
const __vue_is_functional_template__$H = false;
/* style inject */
/* style inject SSR */
var SliderThumb = normalizeComponent_1(
{ render: __vue_render__$D, staticRenderFns: __vue_staticRenderFns__$D },
__vue_inject_styles__$H,
__vue_script__$H,
__vue_scope_id__$H,
__vue_is_functional_template__$H,
__vue_module_identifier__$H,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
var script$I = {
name: 'BSliderTick',
props: {
value: {
type: Number,
default: 0
}
},
computed: {
position: function position() {
var pos = (this.value - this.$parent.min) / (this.$parent.max - this.$parent.min) * 100;
return pos >= 0 && pos <= 100 ? pos : 0;
},
hidden: function hidden() {
return this.value === this.$parent.min || this.value === this.$parent.max;
}
},
methods: {
getTickStyle: function getTickStyle(position) {
return {
'left': position + '%'
};
}
},
created: function created() {
if (!this.$parent.$data._isSlider) {
this.$destroy();
throw new Error('You should wrap bSliderTick on a bSlider');
}
}
};
/* script */
const __vue_script__$I = script$I;
/* template */
var __vue_render__$E = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-slider-tick",class:{ 'is-tick-hidden': _vm.hidden },style:(_vm.getTickStyle(_vm.position))},[(_vm.$slots.default)?_c('span',{staticClass:"b-slider-tick-label"},[_vm._t("default")],2):_vm._e()])};
var __vue_staticRenderFns__$E = [];
/* style */
const __vue_inject_styles__$I = undefined;
/* scoped */
const __vue_scope_id__$I = undefined;
/* module identifier */
const __vue_module_identifier__$I = undefined;
/* functional template */
const __vue_is_functional_template__$I = false;
/* style inject */
/* style inject SSR */
var SliderTick = normalizeComponent_1(
{ render: __vue_render__$E, staticRenderFns: __vue_staticRenderFns__$E },
__vue_inject_styles__$I,
__vue_script__$I,
__vue_scope_id__$I,
__vue_is_functional_template__$I,
__vue_module_identifier__$I,
undefined,
undefined
);
var _components$6;
var script$J = {
name: 'BSlider',
components: (_components$6 = {}, _defineProperty(_components$6, SliderThumb.name, SliderThumb), _defineProperty(_components$6, SliderTick.name, SliderTick), _components$6),
props: {
value: {
type: [Number, Array],
default: 0
},
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
step: {
type: Number,
default: 1
},
type: {
type: String,
default: 'is-primary'
},
size: String,
ticks: {
type: Boolean,
default: false
},
tooltip: {
type: Boolean,
default: true
},
tooltipType: String,
rounded: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
lazy: {
type: Boolean,
default: false
},
customFormatter: Function,
ariaLabel: [String, Array]
},
data: function data() {
return {
value1: null,
value2: null,
dragging: false,
isRange: false,
_isSlider: true // Used by Thumb and Tick
};
},
computed: {
newTooltipType: function newTooltipType() {
return this.tooltipType ? this.tooltipType : this.type;
},
tickValues: function tickValues() {
if (!this.ticks || this.min > this.max || this.step === 0) return [];
var result = [];
for (var i = this.min + this.step; i < this.max; i = i + this.step) {
result.push(i);
}
return result;
},
minValue: function minValue() {
return Math.min(this.value1, this.value2);
},
maxValue: function maxValue() {
return Math.max(this.value1, this.value2);
},
barSize: function barSize() {
return this.isRange ? "".concat(100 * (this.maxValue - this.minValue) / (this.max - this.min), "%") : "".concat(100 * (this.value1 - this.min) / (this.max - this.min), "%");
},
barStart: function barStart() {
return this.isRange ? "".concat(100 * (this.minValue - this.min) / (this.max - this.min), "%") : '0%';
},
precision: function precision() {
var precisions = [this.min, this.max, this.step].map(function (item) {
var decimal = ('' + item).split('.')[1];
return decimal ? decimal.length : 0;
});
return Math.max.apply(Math, _toConsumableArray(precisions));
},
barStyle: function barStyle() {
return {
width: this.barSize,
left: this.barStart
};
},
sliderSize: function sliderSize() {
return this.$refs.slider['clientWidth'];
},
rootClasses: function rootClasses() {
return {
'is-rounded': this.rounded,
'is-dragging': this.dragging,
'is-disabled': this.disabled
};
}
},
watch: {
/**
* When v-model is changed set the new active step.
*/
value: function value(_value) {
this.setValues(_value);
},
value1: function value1() {
this.onInternalValueUpdate();
},
value2: function value2() {
this.onInternalValueUpdate();
},
min: function min() {
this.setValues(this.value);
},
max: function max() {
this.setValues(this.value);
}
},
methods: {
setValues: function setValues(newValue) {
if (this.min > this.max) {
return;
}
if (Array.isArray(newValue)) {
this.isRange = true;
var smallValue = typeof newValue[0] !== 'number' || isNaN(newValue[0]) ? this.min : Math.min(Math.max(this.min, newValue[0]), this.max);
var largeValue = typeof newValue[1] !== 'number' || isNaN(newValue[1]) ? this.max : Math.max(Math.min(this.max, newValue[1]), this.min);
this.value1 = this.isThumbReversed ? largeValue : smallValue;
this.value2 = this.isThumbReversed ? smallValue : largeValue;
} else {
this.isRange = false;
this.value1 = isNaN(newValue) ? this.min : Math.min(this.max, Math.max(this.min, newValue));
this.value2 = null;
}
},
onInternalValueUpdate: function onInternalValueUpdate() {
if (this.isRange) {
this.isThumbReversed = this.value1 > this.value2;
}
if (!this.lazy || !this.dragging) {
this.emitValue('input');
}
if (this.dragging) {
this.emitValue('dragging');
}
},
onSliderClick: function onSliderClick(event) {
if (this.disabled || this.isTrackClickDisabled) return;
var sliderOffsetLeft = this.$refs.slider.getBoundingClientRect().left;
var percent = (event.clientX - sliderOffsetLeft) / this.sliderSize * 100;
var targetValue = this.min + percent * (this.max - this.min) / 100;
var diffFirst = Math.abs(targetValue - this.value1);
if (!this.isRange) {
if (diffFirst < this.step / 2) return;
this.$refs.button1.setPosition(percent);
} else {
var diffSecond = Math.abs(targetValue - this.value2);
if (diffFirst <= diffSecond) {
if (diffFirst < this.step / 2) return;
this.$refs['button1'].setPosition(percent);
} else {
if (diffSecond < this.step / 2) return;
this.$refs['button2'].setPosition(percent);
}
}
this.emitValue('change');
},
onDragStart: function onDragStart() {
this.dragging = true;
this.$emit('dragstart');
},
onDragEnd: function onDragEnd() {
var _this = this;
this.isTrackClickDisabled = true;
setTimeout(function () {
// avoid triggering onSliderClick after dragend
_this.isTrackClickDisabled = false;
}, 0);
this.dragging = false;
this.$emit('dragend');
if (this.lazy) {
this.emitValue('input');
}
},
emitValue: function emitValue(type) {
this.$emit(type, this.isRange ? [this.minValue, this.maxValue] : this.value1);
}
},
created: function created() {
this.isThumbReversed = false;
this.isTrackClickDisabled = false;
this.setValues(this.value);
}
};
/* script */
const __vue_script__$J = script$J;
/* template */
var __vue_render__$F = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-slider",class:[_vm.size, _vm.type, _vm.rootClasses]},[_c('div',{ref:"slider",staticClass:"b-slider-track",on:{"click":_vm.onSliderClick}},[_c('div',{staticClass:"b-slider-fill",style:(_vm.barStyle)}),_vm._v(" "),(_vm.ticks)?_vm._l((_vm.tickValues),function(val,key){return _c('b-slider-tick',{key:key,attrs:{"value":val}})}):_vm._e(),_vm._v(" "),_vm._t("default"),_vm._v(" "),_c('b-slider-thumb',{ref:"button1",attrs:{"type":_vm.newTooltipType,"tooltip":_vm.tooltip,"custom-formatter":_vm.customFormatter,"role":"slider","aria-valuenow":_vm.value1,"aria-valuemin":_vm.min,"aria-valuemax":_vm.max,"aria-orientation":"horizontal","aria-label":Array.isArray(_vm.ariaLabel) ? _vm.ariaLabel[0] : _vm.ariaLabel,"aria-disabled":_vm.disabled},on:{"dragstart":_vm.onDragStart,"dragend":_vm.onDragEnd},model:{value:(_vm.value1),callback:function ($$v) {_vm.value1=$$v;},expression:"value1"}}),_vm._v(" "),(_vm.isRange)?_c('b-slider-thumb',{ref:"button2",attrs:{"type":_vm.newTooltipType,"tooltip":_vm.tooltip,"custom-formatter":_vm.customFormatter,"role":"slider","aria-valuenow":_vm.value2,"aria-valuemin":_vm.min,"aria-valuemax":_vm.max,"aria-orientation":"horizontal","aria-label":Array.isArray(_vm.ariaLabel) ? _vm.ariaLabel[1] : '',"aria-disabled":_vm.disabled},on:{"dragstart":_vm.onDragStart,"dragend":_vm.onDragEnd},model:{value:(_vm.value2),callback:function ($$v) {_vm.value2=$$v;},expression:"value2"}}):_vm._e()],2)])};
var __vue_staticRenderFns__$F = [];
/* style */
const __vue_inject_styles__$J = undefined;
/* scoped */
const __vue_scope_id__$J = undefined;
/* module identifier */
const __vue_module_identifier__$J = undefined;
/* functional template */
const __vue_is_functional_template__$J = false;
/* style inject */
/* style inject SSR */
var Slider = normalizeComponent_1(
{ render: __vue_render__$F, staticRenderFns: __vue_staticRenderFns__$F },
__vue_inject_styles__$J,
__vue_script__$J,
__vue_scope_id__$J,
__vue_is_functional_template__$J,
__vue_module_identifier__$J,
undefined,
undefined
);
var Plugin$p = {
install: function install(Vue) {
registerComponent(Vue, Slider);
registerComponent(Vue, SliderTick);
}
};
use(Plugin$p);
//
var script$K = {
name: 'BSnackbar',
mixins: [NoticeMixin],
props: {
actionText: {
type: String,
default: 'OK'
},
onAction: {
type: Function,
default: function _default() {}
},
indefinite: {
type: Boolean,
default: false
}
},
data: function data() {
return {
newDuration: this.duration || config.defaultSnackbarDuration
};
},
methods: {
/**
* Click listener.
* Call action prop before closing (from Mixin).
*/
action: function action() {
this.onAction();
this.close();
}
}
};
/* script */
const __vue_script__$K = script$K;
/* template */
var __vue_render__$G = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"enter-active-class":_vm.transition.enter,"leave-active-class":_vm.transition.leave}},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"snackbar",class:[_vm.type,_vm.position]},[_c('div',{staticClass:"text",domProps:{"innerHTML":_vm._s(_vm.message)}}),_vm._v(" "),(_vm.actionText)?_c('div',{staticClass:"action",class:_vm.type,on:{"click":_vm.action}},[_c('button',{staticClass:"button"},[_vm._v(_vm._s(_vm.actionText))])]):_vm._e()])])};
var __vue_staticRenderFns__$G = [];
/* style */
const __vue_inject_styles__$K = undefined;
/* scoped */
const __vue_scope_id__$K = undefined;
/* module identifier */
const __vue_module_identifier__$K = undefined;
/* functional template */
const __vue_is_functional_template__$K = false;
/* style inject */
/* style inject SSR */
var Snackbar = normalizeComponent_1(
{ render: __vue_render__$G, staticRenderFns: __vue_staticRenderFns__$G },
__vue_inject_styles__$K,
__vue_script__$K,
__vue_scope_id__$K,
__vue_is_functional_template__$K,
__vue_module_identifier__$K,
undefined,
undefined
);
var SnackbarProgrammatic = {
open: function open(params) {
var parent;
if (typeof params === 'string') {
params = {
message: params
};
}
var defaultParam = {
type: 'is-success',
position: config.defaultSnackbarPosition || 'is-bottom-right'
};
if (params.parent) {
parent = params.parent;
delete params.parent;
}
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : Vue;
var SnackbarComponent = vm.extend(Snackbar);
return new SnackbarComponent({
parent: parent,
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin$q = {
install: function install(Vue) {
registerComponentProgrammatic(Vue, 'snackbar', SnackbarProgrammatic);
}
};
use(Plugin$q);
var SlotComponent = {
name: 'BSlotComponent',
props: {
component: {
type: Object,
required: true
},
name: {
type: String,
default: 'default'
},
scoped: {
type: Boolean
},
props: {
type: Object
},
tag: {
type: String,
default: 'div'
},
event: {
type: String,
default: 'hook:updated'
}
},
methods: {
refresh: function refresh() {
this.$forceUpdate();
},
isVueComponent: function isVueComponent() {
return this.component && this.component._isVue;
}
},
created: function created() {
if (this.isVueComponent()) {
this.component.$on(this.event, this.refresh);
}
},
beforeDestroy: function beforeDestroy() {
if (this.isVueComponent()) {
this.component.$off(this.event, this.refresh);
}
},
render: function render(createElement) {
if (this.isVueComponent()) {
return createElement(this.tag, {}, this.scoped ? this.component.$scopedSlots[this.name](this.props) : this.component.$slots[this.name]);
}
}
};
var _components$7;
var script$L = {
name: 'BSteps',
components: (_components$7 = {}, _defineProperty(_components$7, Icon.name, Icon), _defineProperty(_components$7, SlotComponent.name, SlotComponent), _components$7),
props: {
value: Number,
type: [String, Object],
size: String,
animated: {
type: Boolean,
default: true
},
destroyOnHide: {
type: Boolean,
default: false
},
iconPack: String,
iconPrev: {
type: String,
default: config.defaultIconPrev
},
iconNext: {
type: String,
default: config.defaultIconNext
},
hasNavigation: {
type: Boolean,
default: true
},
ariaNextLabel: String,
ariaPreviousLabel: String
},
data: function data() {
return {
activeStep: this.value || 0,
stepItems: [],
contentHeight: 0,
isTransitioning: false,
_isSteps: true // Used internally by StepItem
};
},
computed: {
mainClasses: function mainClasses() {
return [this.type, this.size];
},
reversedStepItems: function reversedStepItems() {
return this.stepItems.slice().reverse();
},
/**
* Check the first visible step index.
*/
firstVisibleStepIndex: function firstVisibleStepIndex() {
return this.stepItems.map(function (step, idx) {
return step.visible;
}).indexOf(true);
},
/**
* Check if previous button is available.
*/
hasPrev: function hasPrev() {
return this.firstVisibleStepIndex >= 0 && this.activeStep > this.firstVisibleStepIndex;
},
/**
* Check the last visible step index.
*/
lastVisibleStepIndex: function lastVisibleStepIndex() {
var idx = this.reversedStepItems.map(function (step, idx) {
return step.visible;
}).indexOf(true);
if (idx >= 0) {
return this.stepItems.length - 1 - idx;
}
return idx;
},
/**
* Check if next button is available.
*/
hasNext: function hasNext() {
return this.lastVisibleStepIndex >= 0 && this.activeStep < this.lastVisibleStepIndex;
},
navigationProps: function navigationProps() {
return {
previous: {
disabled: !this.hasPrev,
action: this.prev
},
next: {
disabled: !this.hasNext,
action: this.next
}
};
}
},
watch: {
/**
* When v-model is changed set the new active step.
*/
value: function value(_value) {
this.changeStep(_value);
},
/**
* When step-items are updated, set active one.
*/
stepItems: function stepItems() {
if (this.activeStep < this.stepItems.length) {
this.stepItems[this.activeStep].isActive = true;
}
}
},
methods: {
/**
* Change the active step and emit change event.
*/
changeStep: function changeStep(newIndex) {
if (this.activeStep === newIndex) return;
if (this.activeStep < this.stepItems.length) {
this.stepItems[this.activeStep].deactivate(this.activeStep, newIndex);
}
this.stepItems[newIndex].activate(this.activeStep, newIndex);
this.activeStep = newIndex;
this.$emit('change', newIndex);
},
/**
* Return if the step should be clickable or not.
*/
isItemClickable: function isItemClickable(stepItem, index) {
if (stepItem.clickable === undefined) {
return this.activeStep > index;
}
return stepItem.clickable;
},
/**
* Step click listener, emit input event and change active step.
*/
stepClick: function stepClick(value) {
this.$emit('input', value);
this.changeStep(value);
},
/**
* Previous button click listener.
*/
prev: function prev() {
var _this = this;
if (!this.hasPrev) return;
var prevItemIdx = this.reversedStepItems.map(function (step, idx) {
return _this.stepItems.length - 1 - idx < _this.activeStep && step.visible;
}).indexOf(true);
if (prevItemIdx >= 0) {
prevItemIdx = this.stepItems.length - 1 - prevItemIdx;
}
this.$emit('input', prevItemIdx);
this.changeStep(prevItemIdx);
},
/**
* Previous button click listener.
*/
next: function next() {
var _this2 = this;
if (!this.hasNext) return;
var nextItemIdx = this.stepItems.map(function (step, idx) {
return idx > _this2.activeStep && step.visible;
}).indexOf(true);
this.$emit('input', nextItemIdx);
this.changeStep(nextItemIdx);
}
},
mounted: function mounted() {
if (this.activeStep < this.stepItems.length) {
this.stepItems[this.activeStep].isActive = true;
}
}
};
/* script */
const __vue_script__$L = script$L;
/* template */
var __vue_render__$H = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-steps"},[_c('nav',{staticClass:"steps",class:_vm.mainClasses},[_c('ul',{staticClass:"step-items"},_vm._l((_vm.stepItems),function(stepItem,index){return _c('li',{directives:[{name:"show",rawName:"v-show",value:(stepItem.visible),expression:"stepItem.visible"}],key:index,staticClass:"step-item",class:[stepItem.type || _vm.type, {
'is-active': _vm.activeStep === index,
'is-previous': _vm.activeStep > index
}]},[_c('a',{staticClass:"step-link",class:{'is-clickable': _vm.isItemClickable(stepItem, index)},on:{"click":function($event){_vm.isItemClickable(stepItem, index) && _vm.stepClick(index);}}},[_c('div',{staticClass:"step-marker"},[(stepItem.icon)?_c('b-icon',{attrs:{"icon":stepItem.icon,"pack":stepItem.iconPack,"size":_vm.size}}):_vm._e()],1),_vm._v(" "),_c('div',{staticClass:"step-details"},[_c('span',{staticClass:"step-title"},[_vm._v(_vm._s(stepItem.label))])])])])}),0)]),_vm._v(" "),_c('section',{staticClass:"step-content",class:{'is-transitioning': _vm.isTransitioning}},[_vm._t("default")],2),_vm._v(" "),_vm._t("navigation",[(_vm.hasNavigation)?_c('nav',{staticClass:"step-navigation"},[_c('a',{staticClass:"pagination-previous",attrs:{"role":"button","disabled":_vm.navigationProps.previous.disabled,"aria-label":_vm.ariaPreviousLabel},on:{"click":function($event){$event.preventDefault();return _vm.navigationProps.previous.action($event)}}},[_c('b-icon',{attrs:{"icon":_vm.iconPrev,"pack":_vm.iconPack,"both":"","aria-hidden":"true"}})],1),_vm._v(" "),_c('a',{staticClass:"pagination-next",attrs:{"role":"button","disabled":_vm.navigationProps.next.disabled,"aria-label":_vm.ariaNextLabel},on:{"click":function($event){$event.preventDefault();return _vm.navigationProps.next.action($event)}}},[_c('b-icon',{attrs:{"icon":_vm.iconNext,"pack":_vm.iconPack,"both":"","aria-hidden":"true"}})],1)]):_vm._e()],{"previous":_vm.navigationProps.previous,"next":_vm.navigationProps.next})],2)};
var __vue_staticRenderFns__$H = [];
/* style */
const __vue_inject_styles__$L = undefined;
/* scoped */
const __vue_scope_id__$L = undefined;
/* module identifier */
const __vue_module_identifier__$L = undefined;
/* functional template */
const __vue_is_functional_template__$L = false;
/* style inject */
/* style inject SSR */
var Steps = normalizeComponent_1(
{ render: __vue_render__$H, staticRenderFns: __vue_staticRenderFns__$H },
__vue_inject_styles__$L,
__vue_script__$L,
__vue_scope_id__$L,
__vue_is_functional_template__$L,
__vue_module_identifier__$L,
undefined,
undefined
);
var script$M = {
name: 'BStepItem',
props: {
label: String,
type: String | Object,
icon: String,
iconPack: String,
clickable: {
type: Boolean,
default: undefined
},
visible: {
type: Boolean,
default: true
}
},
data: function data() {
return {
isActive: false,
transitionName: null
};
},
methods: {
/**
* Activate step, alter animation name based on the index.
*/
activate: function activate(oldIndex, index) {
this.transitionName = index < oldIndex ? 'slide-next' : 'slide-prev';
this.isActive = true;
},
/**
* Deactivate step, alter animation name based on the index.
*/
deactivate: function deactivate(oldIndex, index) {
this.transitionName = index < oldIndex ? 'slide-next' : 'slide-prev';
this.isActive = false;
}
},
created: function created() {
if (!this.$parent.$data._isSteps) {
this.$destroy();
throw new Error('You should wrap bStepItem on a bSteps');
}
this.$parent.stepItems.push(this);
},
beforeDestroy: function beforeDestroy() {
var index = this.$parent.stepItems.indexOf(this);
if (index >= 0) {
this.$parent.stepItems.splice(index, 1);
}
},
render: function render(createElement) {
var _this = this;
// if destroy apply v-if
if (this.$parent.destroyOnHide) {
if (!this.isActive || !this.visible) {
return;
}
}
var vnode = createElement('div', {
directives: [{
name: 'show',
value: this.isActive && this.visible
}],
attrs: {
'class': 'step-item'
}
}, this.$slots.default); // check animated prop
if (this.$parent.animated) {
return createElement('transition', {
props: {
'name': this.transitionName
},
on: {
'before-enter': function beforeEnter() {
_this.$parent.isTransitioning = true;
},
'after-enter': function afterEnter() {
_this.$parent.isTransitioning = false;
}
}
}, [vnode]);
}
return vnode;
}
};
/* script */
const __vue_script__$M = script$M;
/* template */
/* style */
const __vue_inject_styles__$M = undefined;
/* scoped */
const __vue_scope_id__$M = undefined;
/* module identifier */
const __vue_module_identifier__$M = undefined;
/* functional template */
const __vue_is_functional_template__$M = undefined;
/* style inject */
/* style inject SSR */
var StepItem = normalizeComponent_1(
{},
__vue_inject_styles__$M,
__vue_script__$M,
__vue_scope_id__$M,
__vue_is_functional_template__$M,
__vue_module_identifier__$M,
undefined,
undefined
);
var Plugin$r = {
install: function install(Vue) {
registerComponent(Vue, Steps);
registerComponent(Vue, StepItem);
}
};
use(Plugin$r);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$N = {
name: 'BSwitch',
props: {
value: [String, Number, Boolean, Function, Object, Array],
nativeValue: [String, Number, Boolean, Function, Object, Array],
disabled: Boolean,
type: String,
name: String,
required: Boolean,
size: String,
trueValue: {
type: [String, Number, Boolean, Function, Object, Array],
default: true
},
falseValue: {
type: [String, Number, Boolean, Function, Object, Array],
default: false
},
rounded: {
type: Boolean,
default: true
},
outlined: {
type: Boolean,
default: false
}
},
data: function data() {
return {
newValue: this.value,
isMouseDown: false
};
},
computed: {
computedValue: {
get: function get() {
return this.newValue;
},
set: function set(value) {
this.newValue = value;
this.$emit('input', value);
}
},
newClass: function newClass() {
return [this.size, {
'is-disabled': this.disabled
}, {
'is-rounded': this.rounded
}, {
'is-outlined': this.outlined
}];
}
},
watch: {
/**
* When v-model change, set internal value.
*/
value: function value(_value) {
this.newValue = _value;
}
},
methods: {
focus: function focus() {
// MacOS FireFox and Safari do not focus when clicked
this.$refs.input.focus();
}
}
};
/* script */
const __vue_script__$N = script$N;
/* template */
var __vue_render__$I = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('label',{ref:"label",staticClass:"switch",class:_vm.newClass,attrs:{"disabled":_vm.disabled},on:{"click":_vm.focus,"keydown":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"enter",13,$event.key,"Enter")){ return null; }$event.preventDefault();return _vm.$refs.label.click()},"mousedown":function($event){_vm.isMouseDown = true;},"mouseup":function($event){_vm.isMouseDown = false;},"mouseout":function($event){_vm.isMouseDown = false;},"blur":function($event){_vm.isMouseDown = false;}}},[_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.computedValue),expression:"computedValue"}],ref:"input",attrs:{"type":"checkbox","disabled":_vm.disabled,"name":_vm.name,"required":_vm.required,"true-value":_vm.trueValue,"false-value":_vm.falseValue},domProps:{"value":_vm.nativeValue,"checked":Array.isArray(_vm.computedValue)?_vm._i(_vm.computedValue,_vm.nativeValue)>-1:_vm._q(_vm.computedValue,_vm.trueValue)},on:{"click":function($event){$event.stopPropagation();},"change":function($event){var $$a=_vm.computedValue,$$el=$event.target,$$c=$$el.checked?(_vm.trueValue):(_vm.falseValue);if(Array.isArray($$a)){var $$v=_vm.nativeValue,$$i=_vm._i($$a,$$v);if($$el.checked){$$i<0&&(_vm.computedValue=$$a.concat([$$v]));}else{$$i>-1&&(_vm.computedValue=$$a.slice(0,$$i).concat($$a.slice($$i+1)));}}else{_vm.computedValue=$$c;}}}}),_vm._v(" "),_c('span',{staticClass:"check",class:[{ 'is-elastic': _vm.isMouseDown && !_vm.disabled }, _vm.type]}),_vm._v(" "),_c('span',{staticClass:"control-label"},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$I = [];
/* style */
const __vue_inject_styles__$N = undefined;
/* scoped */
const __vue_scope_id__$N = undefined;
/* module identifier */
const __vue_module_identifier__$N = undefined;
/* functional template */
const __vue_is_functional_template__$N = false;
/* style inject */
/* style inject SSR */
var Switch = normalizeComponent_1(
{ render: __vue_render__$I, staticRenderFns: __vue_staticRenderFns__$I },
__vue_inject_styles__$N,
__vue_script__$N,
__vue_scope_id__$N,
__vue_is_functional_template__$N,
__vue_module_identifier__$N,
undefined,
undefined
);
var Plugin$s = {
install: function install(Vue) {
registerComponent(Vue, Switch);
}
};
use(Plugin$s);
var _components$8;
var script$O = {
name: 'BTableMobileSort',
components: (_components$8 = {}, _defineProperty(_components$8, Select.name, Select), _defineProperty(_components$8, Icon.name, Icon), _components$8),
props: {
currentSortColumn: Object,
isAsc: Boolean,
columns: Array,
placeholder: String,
iconPack: String,
sortIcon: {
type: String,
default: 'arrow-up'
},
sortIconSize: {
type: String,
default: 'is-small'
}
},
data: function data() {
return {
mobileSort: this.currentSortColumn
};
},
computed: {
showPlaceholder: function showPlaceholder() {
var _this = this;
return !this.columns || !this.columns.some(function (column) {
return column === _this.mobileSort;
});
}
},
watch: {
mobileSort: function mobileSort(column) {
if (this.currentSortColumn === column) return;
this.$emit('sort', column);
},
currentSortColumn: function currentSortColumn(column) {
this.mobileSort = column;
}
},
methods: {
sort: function sort() {
this.$emit('sort', this.mobileSort);
}
}
};
/* script */
const __vue_script__$O = script$O;
/* template */
var __vue_render__$J = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"field table-mobile-sort"},[_c('div',{staticClass:"field has-addons"},[_c('b-select',{attrs:{"expanded":""},model:{value:(_vm.mobileSort),callback:function ($$v) {_vm.mobileSort=$$v;},expression:"mobileSort"}},[(_vm.placeholder)?[_c('option',{directives:[{name:"show",rawName:"v-show",value:(_vm.showPlaceholder),expression:"showPlaceholder"}],attrs:{"selected":"","disabled":"","hidden":""},domProps:{"value":{}}},[_vm._v("\n "+_vm._s(_vm.placeholder)+"\n ")])]:_vm._e(),_vm._v(" "),_vm._l((_vm.columns),function(column,index){return (column.sortable)?_c('option',{key:index,domProps:{"value":column}},[_vm._v("\n "+_vm._s(column.label)+"\n ")]):_vm._e()})],2),_vm._v(" "),_c('div',{staticClass:"control"},[_c('button',{staticClass:"button is-primary",on:{"click":_vm.sort}},[_c('b-icon',{directives:[{name:"show",rawName:"v-show",value:(_vm.currentSortColumn === _vm.mobileSort),expression:"currentSortColumn === mobileSort"}],class:{ 'is-desc': !_vm.isAsc },attrs:{"icon":_vm.sortIcon,"pack":_vm.iconPack,"size":_vm.sortIconSize,"both":""}})],1)])],1)])};
var __vue_staticRenderFns__$J = [];
/* style */
const __vue_inject_styles__$O = undefined;
/* scoped */
const __vue_scope_id__$O = undefined;
/* module identifier */
const __vue_module_identifier__$O = undefined;
/* functional template */
const __vue_is_functional_template__$O = false;
/* style inject */
/* style inject SSR */
var TableMobileSort = normalizeComponent_1(
{ render: __vue_render__$J, staticRenderFns: __vue_staticRenderFns__$J },
__vue_inject_styles__$O,
__vue_script__$O,
__vue_scope_id__$O,
__vue_is_functional_template__$O,
__vue_module_identifier__$O,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
var script$P = {
name: 'BTableColumn',
props: {
label: String,
customKey: [String, Number],
field: String,
meta: [String, Number, Boolean, Function, Object, Array],
width: [Number, String],
numeric: Boolean,
centered: Boolean,
searchable: Boolean,
sortable: Boolean,
visible: {
type: Boolean,
default: true
},
subheading: [String, Number],
customSort: Function,
internal: Boolean // Used internally by Table
},
data: function data() {
return {
newKey: this.customKey || this.label
};
},
computed: {
rootClasses: function rootClasses() {
return {
'has-text-right': this.numeric && !this.centered,
'has-text-centered': this.centered
};
}
},
methods: {
addRefToTable: function addRefToTable() {
var _this = this;
if (!this.$parent.$data._isTable) {
this.$destroy();
throw new Error('You should wrap bTableColumn on a bTable');
}
if (this.internal) return; // Since we're using scoped prop the columns gonna be multiplied,
// this finds when to stop based on the newKey property.
var repeated = this.$parent.newColumns.some(function (column) {
return column.newKey === _this.newKey;
});
!repeated && this.$parent.newColumns.push(this);
}
},
beforeMount: function beforeMount() {
this.addRefToTable();
},
beforeUpdate: function beforeUpdate() {
this.addRefToTable();
},
beforeDestroy: function beforeDestroy() {
var _this2 = this;
if (this.sortable) {
if (!this.$parent.visibleData.length) return;
if (this.$parent.$children.filter(function (vm) {
return vm.$options._componentTag === 'b-table-column' && vm.$data.newKey === _this2.newKey;
}).length !== 1) return;
}
var index = this.$parent.newColumns.map(function (column) {
return column.newKey;
}).indexOf(this.newKey);
if (index >= 0) {
this.$parent.newColumns.splice(index, 1);
}
}
};
/* script */
const __vue_script__$P = script$P;
/* template */
var __vue_render__$K = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return (_vm.visible)?_c('td',{class:_vm.rootClasses,attrs:{"data-label":_vm.label}},[_vm._t("default")],2):_vm._e()};
var __vue_staticRenderFns__$K = [];
/* style */
const __vue_inject_styles__$P = undefined;
/* scoped */
const __vue_scope_id__$P = undefined;
/* module identifier */
const __vue_module_identifier__$P = undefined;
/* functional template */
const __vue_is_functional_template__$P = false;
/* style inject */
/* style inject SSR */
var TableColumn = normalizeComponent_1(
{ render: __vue_render__$K, staticRenderFns: __vue_staticRenderFns__$K },
__vue_inject_styles__$P,
__vue_script__$P,
__vue_scope_id__$P,
__vue_is_functional_template__$P,
__vue_module_identifier__$P,
undefined,
undefined
);
var _components$9;
var script$Q = {
name: 'BTable',
components: (_components$9 = {}, _defineProperty(_components$9, Checkbox.name, Checkbox), _defineProperty(_components$9, Icon.name, Icon), _defineProperty(_components$9, Input.name, Input), _defineProperty(_components$9, Pagination.name, Pagination), _defineProperty(_components$9, SlotComponent.name, SlotComponent), _defineProperty(_components$9, TableMobileSort.name, TableMobileSort), _defineProperty(_components$9, TableColumn.name, TableColumn), _components$9),
props: {
data: {
type: Array,
default: function _default() {
return [];
}
},
columns: {
type: Array,
default: function _default() {
return [];
}
},
bordered: Boolean,
striped: Boolean,
narrowed: Boolean,
hoverable: Boolean,
loading: Boolean,
detailed: Boolean,
checkable: Boolean,
headerCheckable: {
type: Boolean,
default: true
},
checkboxPosition: {
type: String,
default: 'left',
validator: function validator(value) {
return ['left', 'right'].indexOf(value) >= 0;
}
},
selected: Object,
focusable: Boolean,
customIsChecked: Function,
isRowCheckable: {
type: Function,
default: function _default() {
return true;
}
},
checkedRows: {
type: Array,
default: function _default() {
return [];
}
},
mobileCards: {
type: Boolean,
default: true
},
defaultSort: [String, Array],
defaultSortDirection: {
type: String,
default: 'asc'
},
sortIcon: {
type: String,
default: 'arrow-up'
},
sortIconSize: {
type: String,
default: 'is-small'
},
paginated: Boolean,
currentPage: {
type: Number,
default: 1
},
perPage: {
type: [Number, String],
default: 20
},
showDetailIcon: {
type: Boolean,
default: true
},
paginationSimple: Boolean,
paginationSize: String,
paginationPosition: {
type: String,
default: 'bottom',
validator: function validator(value) {
return ['bottom', 'top', 'both'].indexOf(value) >= 0;
}
},
backendSorting: Boolean,
rowClass: {
type: Function,
default: function _default() {
return '';
}
},
openedDetailed: {
type: Array,
default: function _default() {
return [];
}
},
hasDetailedVisible: {
type: Function,
default: function _default() {
return true;
}
},
detailKey: {
type: String,
default: ''
},
customDetailRow: {
type: Boolean,
default: false
},
backendPagination: Boolean,
total: {
type: [Number, String],
default: 0
},
iconPack: String,
mobileSortPlaceholder: String,
customRowKey: String,
draggable: {
type: Boolean,
defualt: false
},
ariaNextLabel: String,
ariaPreviousLabel: String,
ariaPageLabel: String,
ariaCurrentLabel: String
},
data: function data() {
return {
getValueByPath: getValueByPath,
newColumns: _toConsumableArray(this.columns),
visibleDetailRows: this.openedDetailed,
newData: this.data,
newDataTotal: this.backendPagination ? this.total : this.data.length,
newCheckedRows: _toConsumableArray(this.checkedRows),
lastCheckedRowIndex: null,
newCurrentPage: this.currentPage,
currentSortColumn: {},
isAsc: true,
filters: {},
firstTimeSort: true,
// Used by first time initSort
_isTable: true // Used by TableColumn
};
},
computed: {
/**
* return if detailed row tabled
* will be with chevron column & icon or not
*/
showDetailRowIcon: function showDetailRowIcon() {
return this.detailed && this.showDetailIcon;
},
tableClasses: function tableClasses() {
return {
'is-bordered': this.bordered,
'is-striped': this.striped,
'is-narrow': this.narrowed,
'has-mobile-cards': this.mobileCards,
'is-hoverable': (this.hoverable || this.focusable) && this.visibleData.length
};
},
/**
* Splitted data based on the pagination.
*/
visibleData: function visibleData() {
if (!this.paginated) return this.newData;
var currentPage = this.newCurrentPage;
var perPage = this.perPage;
if (this.newData.length <= perPage) {
return this.newData;
} else {
var start = (currentPage - 1) * perPage;
var end = parseInt(start, 10) + parseInt(perPage, 10);
return this.newData.slice(start, end);
}
},
visibleColumns: function visibleColumns() {
if (!this.newColumns) return this.newColumns;
return this.newColumns.filter(function (column) {
return column.visible || column.visible === undefined;
});
},
/**
* Check if all rows in the page are checked.
*/
isAllChecked: function isAllChecked() {
var _this = this;
var validVisibleData = this.visibleData.filter(function (row) {
return _this.isRowCheckable(row);
});
if (validVisibleData.length === 0) return false;
var isAllChecked = validVisibleData.some(function (currentVisibleRow) {
return indexOf(_this.newCheckedRows, currentVisibleRow, _this.customIsChecked) < 0;
});
return !isAllChecked;
},
/**
* Check if all rows in the page are checkable.
*/
isAllUncheckable: function isAllUncheckable() {
var _this2 = this;
var validVisibleData = this.visibleData.filter(function (row) {
return _this2.isRowCheckable(row);
});
return validVisibleData.length === 0;
},
/**
* Check if has any sortable column.
*/
hasSortablenewColumns: function hasSortablenewColumns() {
return this.newColumns.some(function (column) {
return column.sortable;
});
},
/**
* Check if has any searchable column.
*/
hasSearchablenewColumns: function hasSearchablenewColumns() {
return this.newColumns.some(function (column) {
return column.searchable;
});
},
/**
* Check if has any column using subheading.
*/
hasCustomSubheadings: function hasCustomSubheadings() {
if (this.$scopedSlots && this.$scopedSlots.subheading) return true;
return this.newColumns.some(function (column) {
return column.subheading || column.$scopedSlots && column.$scopedSlots.subheading;
});
},
/**
* Return total column count based if it's checkable or expanded
*/
columnCount: function columnCount() {
var count = this.newColumns.length;
count += this.checkable ? 1 : 0;
count += this.detailed ? 1 : 0;
return count;
}
},
watch: {
/**
* When data prop change:
* 1. Update internal value.
* 2. Reset newColumns (thead), in case it's on a v-for loop.
* 3. Sort again if it's not backend-sort.
* 4. Set new total if it's not backend-paginated.
*/
data: function data(value) {
var _this3 = this;
// Save newColumns before resetting
var newColumns = this.newColumns;
this.newColumns = [];
this.newData = value; // Prevent table from being headless, data could change and created hook
// on column might not trigger
this.$nextTick(function () {
if (!_this3.newColumns.length) _this3.newColumns = newColumns;
});
if (!this.backendSorting) {
this.sort(this.currentSortColumn, true);
}
if (!this.backendPagination) {
this.newDataTotal = value.length;
}
},
/**
* When Pagination total change, update internal total
* only if it's backend-paginated.
*/
total: function total(newTotal) {
if (!this.backendPagination) return;
this.newDataTotal = newTotal;
},
/**
* When checkedRows prop change, update internal value without
* mutating original data.
*/
checkedRows: function checkedRows(rows) {
this.newCheckedRows = _toConsumableArray(rows);
},
columns: function columns(value) {
this.newColumns = _toConsumableArray(value);
},
newColumns: function newColumns(value) {
this.checkSort();
},
filters: {
handler: function handler(value) {
var _this4 = this;
this.newData = this.data.filter(function (row) {
return _this4.isRowFiltered(row);
});
if (!this.backendPagination) {
this.newDataTotal = this.newData.length;
}
},
deep: true
},
/**
* When the user wants to control the detailed rows via props.
* Or wants to open the details of certain row with the router for example.
*/
openedDetailed: function openedDetailed(expandedRows) {
this.visibleDetailRows = expandedRows;
},
currentPage: function currentPage(newVal) {
this.newCurrentPage = newVal;
}
},
methods: {
/**
* Sort an array by key without mutating original data.
* Call the user sort function if it was passed.
*/
sortBy: function sortBy(array, key, fn, isAsc) {
var sorted = []; // Sorting without mutating original data
if (fn && typeof fn === 'function') {
sorted = _toConsumableArray(array).sort(function (a, b) {
return fn(a, b, isAsc);
});
} else {
sorted = _toConsumableArray(array).sort(function (a, b) {
// Get nested values from objects
var newA = getValueByPath(a, key);
var newB = getValueByPath(b, key); // sort boolean type
if (typeof newA === 'boolean' && typeof newB === 'boolean') {
return isAsc ? newA - newB : newB - newA;
}
if (!newA && newA !== 0) return 1;
if (!newB && newB !== 0) return -1;
if (newA === newB) return 0;
newA = typeof newA === 'string' ? newA.toUpperCase() : newA;
newB = typeof newB === 'string' ? newB.toUpperCase() : newB;
return isAsc ? newA > newB ? 1 : -1 : newA > newB ? -1 : 1;
});
}
return sorted;
},
/**
* Sort the column.
* Toggle current direction on column if it's sortable
* and not just updating the prop.
*/
sort: function sort(column) {
var updatingData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!column || !column.sortable) return;
if (!updatingData) {
this.isAsc = column === this.currentSortColumn ? !this.isAsc : this.defaultSortDirection.toLowerCase() !== 'desc';
}
if (!this.firstTimeSort) {
this.$emit('sort', column.field, this.isAsc ? 'asc' : 'desc');
}
if (!this.backendSorting) {
this.newData = this.sortBy(this.newData, column.field, column.customSort, this.isAsc);
}
this.currentSortColumn = column;
},
/**
* Check if the row is checked (is added to the array).
*/
isRowChecked: function isRowChecked(row) {
return indexOf(this.newCheckedRows, row, this.customIsChecked) >= 0;
},
/**
* Remove a checked row from the array.
*/
removeCheckedRow: function removeCheckedRow(row) {
var index = indexOf(this.newCheckedRows, row, this.customIsChecked);
if (index >= 0) {
this.newCheckedRows.splice(index, 1);
}
},
/**
* Header checkbox click listener.
* Add or remove all rows in current page.
*/
checkAll: function checkAll() {
var _this5 = this;
var isAllChecked = this.isAllChecked;
this.visibleData.forEach(function (currentRow) {
_this5.removeCheckedRow(currentRow);
if (!isAllChecked) {
if (_this5.isRowCheckable(currentRow)) {
_this5.newCheckedRows.push(currentRow);
}
}
});
this.$emit('check', this.newCheckedRows);
this.$emit('check-all', this.newCheckedRows); // Emit checked rows to update user variable
this.$emit('update:checkedRows', this.newCheckedRows);
},
/**
* Row checkbox click listener.
*/
checkRow: function checkRow(row, index, event) {
if (!this.isRowCheckable(row)) return;
var lastIndex = this.lastCheckedRowIndex;
this.lastCheckedRowIndex = index;
if (event.shiftKey && lastIndex !== null && index !== lastIndex) {
this.shiftCheckRow(row, index, lastIndex);
} else if (!this.isRowChecked(row)) {
this.newCheckedRows.push(row);
} else {
this.removeCheckedRow(row);
}
this.$emit('check', this.newCheckedRows, row); // Emit checked rows to update user variable
this.$emit('update:checkedRows', this.newCheckedRows);
},
/**
* Check row when shift is pressed.
*/
shiftCheckRow: function shiftCheckRow(row, index, lastCheckedRowIndex) {
var _this6 = this;
// Get the subset of the list between the two indicies
var subset = this.visibleData.slice(Math.min(index, lastCheckedRowIndex), Math.max(index, lastCheckedRowIndex) + 1); // Determine the operation based on the state of the clicked checkbox
var shouldCheck = !this.isRowChecked(row);
subset.forEach(function (item) {
_this6.removeCheckedRow(item);
if (shouldCheck && _this6.isRowCheckable(item)) {
_this6.newCheckedRows.push(item);
}
});
},
/**
* Row click listener.
* Emit all necessary events.
*/
selectRow: function selectRow(row, index) {
this.$emit('click', row);
if (this.selected === row) return; // Emit new and old row
this.$emit('select', row, this.selected); // Emit new row to update user variable
this.$emit('update:selected', row);
},
/**
* Paginator change listener.
*/
pageChanged: function pageChanged(page) {
this.newCurrentPage = page > 0 ? page : 1;
this.$emit('page-change', this.newCurrentPage);
this.$emit('update:currentPage', this.newCurrentPage);
},
/**
* Toggle to show/hide details slot
*/
toggleDetails: function toggleDetails(obj) {
var found = this.isVisibleDetailRow(obj);
if (found) {
this.closeDetailRow(obj);
this.$emit('details-close', obj);
} else {
this.openDetailRow(obj);
this.$emit('details-open', obj);
} // Syncs the detailed rows with the parent component
this.$emit('update:openedDetailed', this.visibleDetailRows);
},
openDetailRow: function openDetailRow(obj) {
var index = this.handleDetailKey(obj);
this.visibleDetailRows.push(index);
},
closeDetailRow: function closeDetailRow(obj) {
var index = this.handleDetailKey(obj);
var i = this.visibleDetailRows.indexOf(index);
this.visibleDetailRows.splice(i, 1);
},
isVisibleDetailRow: function isVisibleDetailRow(obj) {
var index = this.handleDetailKey(obj);
var result = this.visibleDetailRows.indexOf(index) >= 0;
return result;
},
isActiveDetailRow: function isActiveDetailRow(row) {
return this.detailed && !this.customDetailRow && this.isVisibleDetailRow(row);
},
isActiveCustomDetailRow: function isActiveCustomDetailRow(row) {
return this.detailed && this.customDetailRow && this.isVisibleDetailRow(row);
},
isRowFiltered: function isRowFiltered(row) {
for (var key in this.filters) {
// remove key if empty
if (!this.filters[key]) {
delete this.filters[key];
return true;
}
var value = this.getValueByPath(row, key);
if (value == null) return false;
if (Number.isInteger(value)) {
if (value !== Number(this.filters[key])) return false;
} else {
var re = new RegExp(this.filters[key], 'i');
if (typeof value === 'boolean') value = "".concat(value);
if (!value.match(re)) return false;
}
}
return true;
},
/**
* When the detailKey is defined we use the object[detailKey] as index.
* If not, use the object reference by default.
*/
handleDetailKey: function handleDetailKey(index) {
var key = this.detailKey;
return !key.length ? index : index[key];
},
checkPredefinedDetailedRows: function checkPredefinedDetailedRows() {
var defaultExpandedRowsDefined = this.openedDetailed.length > 0;
if (defaultExpandedRowsDefined && !this.detailKey.length) {
throw new Error('If you set a predefined opened-detailed, you must provide a unique key using the prop "detail-key"');
}
},
/**
* Call initSort only first time (For example async data).
*/
checkSort: function checkSort() {
if (this.newColumns.length && this.firstTimeSort) {
this.initSort();
this.firstTimeSort = false;
} else if (this.newColumns.length) {
if (this.currentSortColumn.field) {
for (var i = 0; i < this.newColumns.length; i++) {
if (this.newColumns[i].field === this.currentSortColumn.field) {
this.currentSortColumn = this.newColumns[i];
break;
}
}
}
}
},
/**
* Check if footer slot has custom content.
*/
hasCustomFooterSlot: function hasCustomFooterSlot() {
if (this.$slots.footer.length > 1) return true;
var tag = this.$slots.footer[0].tag;
if (tag !== 'th' && tag !== 'td') return false;
return true;
},
/**
* Check if bottom-left slot exists.
*/
hasBottomLeftSlot: function hasBottomLeftSlot() {
return typeof this.$slots['bottom-left'] !== 'undefined';
},
/**
* Table arrow keys listener, change selection.
*/
pressedArrow: function pressedArrow(pos) {
if (!this.visibleData.length) return;
var index = this.visibleData.indexOf(this.selected) + pos; // Prevent from going up from first and down from last
index = index < 0 ? 0 : index > this.visibleData.length - 1 ? this.visibleData.length - 1 : index;
this.selectRow(this.visibleData[index]);
},
/**
* Focus table element if has selected prop.
*/
focus: function focus() {
if (!this.focusable) return;
this.$el.querySelector('table').focus();
},
/**
* Initial sorted column based on the default-sort prop.
*/
initSort: function initSort() {
var _this7 = this;
if (!this.defaultSort) return;
var sortField = '';
var sortDirection = this.defaultSortDirection;
if (Array.isArray(this.defaultSort)) {
sortField = this.defaultSort[0];
if (this.defaultSort[1]) {
sortDirection = this.defaultSort[1];
}
} else {
sortField = this.defaultSort;
}
this.newColumns.forEach(function (column) {
if (column.field === sortField) {
_this7.isAsc = sortDirection.toLowerCase() !== 'desc';
_this7.sort(column, true);
}
});
},
/**
* Emits drag start event
*/
handleDragStart: function handleDragStart(event, row, index) {
this.$emit('dragstart', {
event: event,
row: row,
index: index
});
},
/**
* Emits drag leave event
*/
handleDragEnd: function handleDragEnd(event, row, index) {
this.$emit('dragend', {
event: event,
row: row,
index: index
});
},
/**
* Emits drop event
*/
handleDrop: function handleDrop(event, row, index) {
this.$emit('drop', {
event: event,
row: row,
index: index
});
},
/**
* Emits drag over event
*/
handleDragOver: function handleDragOver(event, row, index) {
this.$emit('dragover', {
event: event,
row: row,
index: index
});
},
/**
* Emits drag leave event
*/
handleDragLeave: function handleDragLeave(event, row, index) {
this.$emit('dragleave', {
event: event,
row: row,
index: index
});
}
},
mounted: function mounted() {
this.checkPredefinedDetailedRows();
this.checkSort();
}
};
/* script */
const __vue_script__$Q = script$Q;
/* template */
var __vue_render__$L = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-table",class:{ 'is-loading': _vm.loading }},[(_vm.mobileCards && _vm.hasSortablenewColumns)?_c('b-table-mobile-sort',{attrs:{"current-sort-column":_vm.currentSortColumn,"is-asc":_vm.isAsc,"columns":_vm.newColumns,"placeholder":_vm.mobileSortPlaceholder,"icon-pack":_vm.iconPack,"sort-icon":_vm.sortIcon,"sort-icon-size":_vm.sortIconSize},on:{"sort":function (column) { return _vm.sort(column); }}}):_vm._e(),_vm._v(" "),(_vm.paginated && (_vm.paginationPosition === 'top' || _vm.paginationPosition === 'both'))?_c('div',{staticClass:"top level"},[_c('div',{staticClass:"level-left"},[_vm._t("top-left")],2),_vm._v(" "),_c('div',{staticClass:"level-right"},[(_vm.paginated)?_c('div',{staticClass:"level-item"},[_c('b-pagination',{attrs:{"icon-pack":_vm.iconPack,"total":_vm.newDataTotal,"per-page":_vm.perPage,"simple":_vm.paginationSimple,"size":_vm.paginationSize,"current":_vm.newCurrentPage,"aria-next-label":_vm.ariaNextLabel,"aria-previous-label":_vm.ariaPreviousLabel,"aria-page-label":_vm.ariaPageLabel,"aria-current-label":_vm.ariaCurrentLabel},on:{"change":_vm.pageChanged}})],1):_vm._e()])]):_vm._e(),_vm._v(" "),_c('div',{staticClass:"table-wrapper"},[_c('table',{staticClass:"table",class:_vm.tableClasses,attrs:{"tabindex":!_vm.focusable ? false : 0},on:{"keydown":[function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"up",38,$event.key,["Up","ArrowUp"])){ return null; }if($event.target !== $event.currentTarget){ return null; }$event.preventDefault();return _vm.pressedArrow(-1)},function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"down",40,$event.key,["Down","ArrowDown"])){ return null; }if($event.target !== $event.currentTarget){ return null; }$event.preventDefault();return _vm.pressedArrow(1)}]}},[(_vm.newColumns.length)?_c('thead',[_c('tr',[(_vm.showDetailRowIcon)?_c('th',{attrs:{"width":"40px"}}):_vm._e(),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'left')?_c('th',{staticClass:"checkbox-cell"},[(_vm.headerCheckable)?[_c('b-checkbox',{attrs:{"value":_vm.isAllChecked,"disabled":_vm.isAllUncheckable},nativeOn:{"change":function($event){return _vm.checkAll($event)}}})]:_vm._e()],2):_vm._e(),_vm._v(" "),_vm._l((_vm.visibleColumns),function(column,index){return _c('th',{key:index,class:{
'is-current-sort': _vm.currentSortColumn === column,
'is-sortable': column.sortable
},style:({
width: column.width === undefined ? null :
(isNaN(column.width) ? column.width : column.width + 'px')
}),on:{"click":function($event){$event.stopPropagation();return _vm.sort(column)}}},[_c('div',{staticClass:"th-wrap",class:{
'is-numeric': column.numeric,
'is-centered': column.centered
}},[(column.$scopedSlots && column.$scopedSlots.header)?[_c('b-slot-component',{attrs:{"component":column,"scoped":true,"name":"header","tag":"span","props":{ column: column, index: index }}})]:(_vm.$scopedSlots.header)?[_vm._t("header",null,{"column":column,"index":index})]:[_vm._v(_vm._s(column.label))],_vm._v(" "),_c('b-icon',{directives:[{name:"show",rawName:"v-show",value:(_vm.currentSortColumn === column),expression:"currentSortColumn === column"}],class:{ 'is-desc': !_vm.isAsc },attrs:{"icon":_vm.sortIcon,"pack":_vm.iconPack,"both":"","size":_vm.sortIconSize}})],2)])}),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'right')?_c('th',{staticClass:"checkbox-cell"},[(_vm.headerCheckable)?[_c('b-checkbox',{attrs:{"value":_vm.isAllChecked,"disabled":_vm.isAllUncheckable},nativeOn:{"change":function($event){return _vm.checkAll($event)}}})]:_vm._e()],2):_vm._e()],2),_vm._v(" "),(_vm.hasCustomSubheadings)?_c('tr',{staticClass:"is-subheading"},[(_vm.showDetailRowIcon)?_c('th',{attrs:{"width":"40px"}}):_vm._e(),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'left')?_c('th'):_vm._e(),_vm._v(" "),_vm._l((_vm.visibleColumns),function(column,index){return _c('th',{key:index,style:({
width: column.width === undefined ? null
: (isNaN(column.width) ? column.width : column.width + 'px') })},[_c('div',{staticClass:"th-wrap",class:{
'is-numeric': column.numeric,
'is-centered': column.centered
}},[(column.$scopedSlots && column.$scopedSlots.subheading)?[_c('b-slot-component',{attrs:{"component":column,"scoped":true,"name":"subheading","tag":"span","props":{ column: column, index: index }}})]:(_vm.$scopedSlots.subheading)?[_vm._t("subheading",null,{"column":column,"index":index})]:[_vm._v(_vm._s(column.subheading))]],2)])}),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'right')?_c('th'):_vm._e()],2):_vm._e(),_vm._v(" "),(_vm.hasSearchablenewColumns)?_c('tr',[(_vm.showDetailRowIcon)?_c('th',{attrs:{"width":"40px"}}):_vm._e(),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'left')?_c('th'):_vm._e(),_vm._v(" "),_vm._l((_vm.visibleColumns),function(column,index){return _c('th',{key:index,style:({
width: column.width === undefined ? null
: (isNaN(column.width) ? column.width : column.width + 'px') })},[_c('div',{staticClass:"th-wrap"},[(column.searchable)?[_c('b-input',{attrs:{"type":column.numeric ? 'number' : 'text'},model:{value:(_vm.filters[column.field]),callback:function ($$v) {_vm.$set(_vm.filters, column.field, $$v);},expression:"filters[column.field]"}})]:_vm._e()],2)])}),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'right')?_c('th'):_vm._e()],2):_vm._e()]):_vm._e(),_vm._v(" "),(_vm.visibleData.length)?_c('tbody',[_vm._l((_vm.visibleData),function(row,index){return [_c('tr',{key:_vm.customRowKey ? row[_vm.customRowKey] : index,class:[_vm.rowClass(row, index), {
'is-selected': row === _vm.selected,
'is-checked': _vm.isRowChecked(row),
}],attrs:{"draggable":_vm.draggable},on:{"click":function($event){return _vm.selectRow(row)},"dblclick":function($event){return _vm.$emit('dblclick', row)},"mouseenter":function($event){return _vm.$emit('mouseenter', row)},"mouseleave":function($event){return _vm.$emit('mouseleave', row)},"contextmenu":function($event){return _vm.$emit('contextmenu', row, $event)},"dragstart":function($event){return _vm.handleDragStart($event, row, index)},"dragend":function($event){return _vm.handleDragEnd($event, row, index)},"drop":function($event){return _vm.handleDrop($event, row, index)},"dragover":function($event){return _vm.handleDragOver($event, row, index)},"dragleave":function($event){return _vm.handleDragLeave($event, row, index)}}},[(_vm.showDetailRowIcon)?_c('td',{staticClass:"chevron-cell"},[(_vm.hasDetailedVisible(row))?_c('a',{attrs:{"role":"button"},on:{"click":function($event){$event.stopPropagation();return _vm.toggleDetails(row)}}},[_c('b-icon',{class:{'is-expanded': _vm.isVisibleDetailRow(row)},attrs:{"icon":"chevron-right","pack":_vm.iconPack,"both":""}})],1):_vm._e()]):_vm._e(),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'left')?_c('td',{staticClass:"checkbox-cell"},[_c('b-checkbox',{attrs:{"disabled":!_vm.isRowCheckable(row),"value":_vm.isRowChecked(row)},nativeOn:{"click":function($event){$event.preventDefault();$event.stopPropagation();return _vm.checkRow(row, index, $event)}}})],1):_vm._e(),_vm._v(" "),(_vm.$scopedSlots.default)?_vm._t("default",null,{"row":row,"index":index}):_vm._l((_vm.newColumns),function(column){return _c('BTableColumn',_vm._b({key:column.field,attrs:{"internal":""}},'BTableColumn',column,false),[(column.renderHtml)?_c('span',{domProps:{"innerHTML":_vm._s(_vm.getValueByPath(row, column.field))}}):[_vm._v("\n "+_vm._s(_vm.getValueByPath(row, column.field))+"\n ")]],2)}),_vm._v(" "),(_vm.checkable && _vm.checkboxPosition === 'right')?_c('td',{staticClass:"checkbox-cell"},[_c('b-checkbox',{attrs:{"disabled":!_vm.isRowCheckable(row),"value":_vm.isRowChecked(row)},nativeOn:{"click":function($event){$event.preventDefault();$event.stopPropagation();return _vm.checkRow(row, index, $event)}}})],1):_vm._e()],2),_vm._v(" "),(_vm.isActiveDetailRow(row))?_c('tr',{staticClass:"detail"},[_c('td',{attrs:{"colspan":_vm.columnCount}},[_c('div',{staticClass:"detail-container"},[_vm._t("detail",null,{"row":row,"index":index})],2)])]):_vm._e(),_vm._v(" "),(_vm.isActiveCustomDetailRow(row))?_vm._t("detail",null,{"row":row,"index":index}):_vm._e()]})],2):_c('tbody',[_c('tr',{staticClass:"is-empty"},[_c('td',{attrs:{"colspan":_vm.columnCount}},[_vm._t("empty")],2)])]),_vm._v(" "),(_vm.$slots.footer !== undefined)?_c('tfoot',[_c('tr',{staticClass:"table-footer"},[(_vm.hasCustomFooterSlot())?_vm._t("footer"):_c('th',{attrs:{"colspan":_vm.columnCount}},[_vm._t("footer")],2)],2)]):_vm._e()])]),_vm._v(" "),((_vm.checkable && _vm.hasBottomLeftSlot()) ||
(_vm.paginated && (_vm.paginationPosition === 'bottom' || _vm.paginationPosition === 'both')))?_c('div',{staticClass:"level"},[_c('div',{staticClass:"level-left"},[_vm._t("bottom-left")],2),_vm._v(" "),_c('div',{staticClass:"level-right"},[(_vm.paginated)?_c('div',{staticClass:"level-item"},[_c('b-pagination',{attrs:{"icon-pack":_vm.iconPack,"total":_vm.newDataTotal,"per-page":_vm.perPage,"simple":_vm.paginationSimple,"size":_vm.paginationSize,"current":_vm.newCurrentPage,"aria-next-label":_vm.ariaNextLabel,"aria-previous-label":_vm.ariaPreviousLabel,"aria-page-label":_vm.ariaPageLabel,"aria-current-label":_vm.ariaCurrentLabel},on:{"change":_vm.pageChanged}})],1):_vm._e()])]):_vm._e()],1)};
var __vue_staticRenderFns__$L = [];
/* style */
const __vue_inject_styles__$Q = undefined;
/* scoped */
const __vue_scope_id__$Q = undefined;
/* module identifier */
const __vue_module_identifier__$Q = undefined;
/* functional template */
const __vue_is_functional_template__$Q = false;
/* style inject */
/* style inject SSR */
var Table = normalizeComponent_1(
{ render: __vue_render__$L, staticRenderFns: __vue_staticRenderFns__$L },
__vue_inject_styles__$Q,
__vue_script__$Q,
__vue_scope_id__$Q,
__vue_is_functional_template__$Q,
__vue_module_identifier__$Q,
undefined,
undefined
);
var Plugin$t = {
install: function install(Vue) {
registerComponent(Vue, Table);
registerComponent(Vue, TableColumn);
}
};
use(Plugin$t);
var _components$a;
var script$R = {
name: 'BTabs',
components: (_components$a = {}, _defineProperty(_components$a, Icon.name, Icon), _defineProperty(_components$a, SlotComponent.name, SlotComponent), _components$a),
props: {
value: Number,
expanded: Boolean,
type: String,
size: String,
position: String,
animated: {
type: Boolean,
default: true
},
destroyOnHide: {
type: Boolean,
default: false
},
vertical: Boolean
},
data: function data() {
return {
activeTab: this.value || 0,
tabItems: [],
contentHeight: 0,
isTransitioning: false,
_isTabs: true // Used internally by TabItem
};
},
computed: {
mainClasses: function mainClasses() {
return _defineProperty({
'is-fullwidth': this.expanded,
'is-vertical': this.vertical
}, this.position, this.position && this.vertical);
},
navClasses: function navClasses() {
var _ref2;
return [this.type, this.size, (_ref2 = {}, _defineProperty(_ref2, this.position, this.position && !this.vertical), _defineProperty(_ref2, 'is-fullwidth', this.expanded), _defineProperty(_ref2, 'is-toggle-rounded is-toggle', this.type === 'is-toggle-rounded'), _ref2)];
}
},
watch: {
/**
* When v-model is changed set the new active tab.
*/
value: function value(_value) {
this.changeTab(_value);
},
/**
* When tab-items are updated, set active one.
*/
tabItems: function tabItems() {
if (this.activeTab < this.tabItems.length) {
this.tabItems[this.activeTab].isActive = true;
}
}
},
methods: {
/**
* Change the active tab and emit change event.
*/
changeTab: function changeTab(newIndex) {
if (this.activeTab === newIndex || this.tabItems[newIndex] === undefined) return;
if (this.activeTab < this.tabItems.length) {
this.tabItems[this.activeTab].deactivate(this.activeTab, newIndex);
}
this.tabItems[newIndex].activate(this.activeTab, newIndex);
this.activeTab = newIndex;
this.$emit('change', newIndex);
},
/**
* Tab click listener, emit input event and change active tab.
*/
tabClick: function tabClick(value) {
if (this.activeTab === value) return;
this.$emit('input', value);
this.changeTab(value);
}
},
mounted: function mounted() {
if (this.activeTab < this.tabItems.length) {
this.tabItems[this.activeTab].isActive = true;
}
}
};
/* script */
const __vue_script__$R = script$R;
/* template */
var __vue_render__$M = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"b-tabs",class:_vm.mainClasses},[_c('nav',{staticClass:"tabs",class:_vm.navClasses},[_c('ul',_vm._l((_vm.tabItems),function(tabItem,index){return _c('li',{directives:[{name:"show",rawName:"v-show",value:(tabItem.visible),expression:"tabItem.visible"}],key:index,class:{ 'is-active': _vm.activeTab === index, 'is-disabled': tabItem.disabled }},[_c('a',{on:{"click":function($event){return _vm.tabClick(index)}}},[(tabItem.$slots.header)?[_c('b-slot-component',{attrs:{"component":tabItem,"name":"header","tag":"span"}})]:[(tabItem.icon)?_c('b-icon',{attrs:{"icon":tabItem.icon,"pack":tabItem.iconPack,"size":_vm.size}}):_vm._e(),_vm._v(" "),_c('span',[_vm._v(_vm._s(tabItem.label))])]],2)])}),0)]),_vm._v(" "),_c('section',{staticClass:"tab-content",class:{'is-transitioning': _vm.isTransitioning}},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$M = [];
/* style */
const __vue_inject_styles__$R = undefined;
/* scoped */
const __vue_scope_id__$R = undefined;
/* module identifier */
const __vue_module_identifier__$R = undefined;
/* functional template */
const __vue_is_functional_template__$R = false;
/* style inject */
/* style inject SSR */
var Tabs = normalizeComponent_1(
{ render: __vue_render__$M, staticRenderFns: __vue_staticRenderFns__$M },
__vue_inject_styles__$R,
__vue_script__$R,
__vue_scope_id__$R,
__vue_is_functional_template__$R,
__vue_module_identifier__$R,
undefined,
undefined
);
var script$S = {
name: 'BTabItem',
props: {
label: String,
icon: String,
iconPack: String,
disabled: Boolean,
visible: {
type: Boolean,
default: true
}
},
data: function data() {
return {
isActive: false,
transitionName: null
};
},
methods: {
/**
* Activate tab, alter animation name based on the index.
*/
activate: function activate(oldIndex, index) {
this.transitionName = index < oldIndex ? 'slide-next' : 'slide-prev';
this.isActive = true;
},
/**
* Deactivate tab, alter animation name based on the index.
*/
deactivate: function deactivate(oldIndex, index) {
this.transitionName = index < oldIndex ? 'slide-next' : 'slide-prev';
this.isActive = false;
}
},
created: function created() {
if (!this.$parent.$data._isTabs) {
this.$destroy();
throw new Error('You should wrap bTabItem on a bTabs');
}
this.$parent.tabItems.push(this);
},
beforeDestroy: function beforeDestroy() {
var index = this.$parent.tabItems.indexOf(this);
if (index >= 0) {
this.$parent.tabItems.splice(index, 1);
}
},
render: function render(createElement) {
var _this = this;
// if destroy apply v-if
if (this.$parent.destroyOnHide) {
if (!this.isActive || !this.visible) {
return;
}
}
var vnode = createElement('div', {
directives: [{
name: 'show',
value: this.isActive && this.visible
}],
class: 'tab-item'
}, this.$slots.default); // check animated prop
if (this.$parent.animated) {
return createElement('transition', {
props: {
'name': this.transitionName
},
on: {
'before-enter': function beforeEnter() {
_this.$parent.isTransitioning = true;
},
'after-enter': function afterEnter() {
_this.$parent.isTransitioning = false;
}
}
}, [vnode]);
}
return vnode;
}
};
/* script */
const __vue_script__$S = script$S;
/* template */
/* style */
const __vue_inject_styles__$S = undefined;
/* scoped */
const __vue_scope_id__$S = undefined;
/* module identifier */
const __vue_module_identifier__$S = undefined;
/* functional template */
const __vue_is_functional_template__$S = undefined;
/* style inject */
/* style inject SSR */
var TabItem = normalizeComponent_1(
{},
__vue_inject_styles__$S,
__vue_script__$S,
__vue_scope_id__$S,
__vue_is_functional_template__$S,
__vue_module_identifier__$S,
undefined,
undefined
);
var Plugin$u = {
install: function install(Vue) {
registerComponent(Vue, Tabs);
registerComponent(Vue, TabItem);
}
};
use(Plugin$u);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script$T = {
name: 'BTag',
props: {
attached: Boolean,
closable: Boolean,
type: String,
size: String,
rounded: Boolean,
disabled: Boolean,
ellipsis: Boolean,
tabstop: {
type: Boolean,
default: true
},
ariaCloseLabel: String
},
methods: {
/**
* Emit close event when delete button is clicked
* or delete key is pressed.
*/
close: function close() {
if (this.disabled) return;
this.$emit('close');
}
}
};
/* script */
const __vue_script__$T = script$T;
/* template */
var __vue_render__$N = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return (_vm.attached && _vm.closable)?_c('div',{staticClass:"tags has-addons"},[_c('span',{staticClass:"tag",class:[_vm.type, _vm.size, { 'is-rounded': _vm.rounded }]},[_c('span',{class:{ 'has-ellipsis': _vm.ellipsis }},[_vm._t("default")],2)]),_vm._v(" "),_c('a',{staticClass:"tag is-delete",class:[_vm.size, { 'is-rounded': _vm.rounded }],attrs:{"role":"button","aria-label":_vm.ariaCloseLabel,"tabindex":_vm.tabstop ? 0 : false,"disabled":_vm.disabled},on:{"click":function($event){return _vm.close()},"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"delete",[8,46],$event.key,["Backspace","Delete","Del"])){ return null; }$event.preventDefault();return _vm.close()}}})]):_c('span',{staticClass:"tag",class:[_vm.type, _vm.size, { 'is-rounded': _vm.rounded }]},[_c('span',{class:{ 'has-ellipsis': _vm.ellipsis }},[_vm._t("default")],2),_vm._v(" "),(_vm.closable)?_c('a',{staticClass:"delete is-small",attrs:{"role":"button","aria-label":_vm.ariaCloseLabel,"disabled":_vm.disabled,"tabindex":_vm.tabstop ? 0 : false},on:{"click":function($event){return _vm.close()},"keyup":function($event){if(!$event.type.indexOf('key')&&_vm._k($event.keyCode,"delete",[8,46],$event.key,["Backspace","Delete","Del"])){ return null; }$event.preventDefault();return _vm.close()}}}):_vm._e()])};
var __vue_staticRenderFns__$N = [];
/* style */
const __vue_inject_styles__$T = undefined;
/* scoped */
const __vue_scope_id__$T = undefined;
/* module identifier */
const __vue_module_identifier__$T = undefined;
/* functional template */
const __vue_is_functional_template__$T = false;
/* style inject */
/* style inject SSR */
var Tag = normalizeComponent_1(
{ render: __vue_render__$N, staticRenderFns: __vue_staticRenderFns__$N },
__vue_inject_styles__$T,
__vue_script__$T,
__vue_scope_id__$T,
__vue_is_functional_template__$T,
__vue_module_identifier__$T,
undefined,
undefined
);
//
//
//
//
//
//
var script$U = {
name: 'BTaglist',
props: {
attached: Boolean
}
};
/* script */
const __vue_script__$U = script$U;
/* template */
var __vue_render__$O = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"tags",class:{ 'has-addons': _vm.attached }},[_vm._t("default")],2)};
var __vue_staticRenderFns__$O = [];
/* style */
const __vue_inject_styles__$U = undefined;
/* scoped */
const __vue_scope_id__$U = undefined;
/* module identifier */
const __vue_module_identifier__$U = undefined;
/* functional template */
const __vue_is_functional_template__$U = false;
/* style inject */
/* style inject SSR */
var Taglist = normalizeComponent_1(
{ render: __vue_render__$O, staticRenderFns: __vue_staticRenderFns__$O },
__vue_inject_styles__$U,
__vue_script__$U,
__vue_scope_id__$U,
__vue_is_functional_template__$U,
__vue_module_identifier__$U,
undefined,
undefined
);
var Plugin$v = {
install: function install(Vue) {
registerComponent(Vue, Tag);
registerComponent(Vue, Taglist);
}
};
use(Plugin$v);
var _components$b;
var script$V = {
name: 'BTaginput',
components: (_components$b = {}, _defineProperty(_components$b, Autocomplete.name, Autocomplete), _defineProperty(_components$b, Tag.name, Tag), _components$b),
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: {
type: Array,
default: function _default() {
return [];
}
},
data: {
type: Array,
default: function _default() {
return [];
}
},
type: String,
rounded: {
type: Boolean,
default: false
},
attached: {
type: Boolean,
default: false
},
maxtags: {
type: [Number, String],
required: false
},
hasCounter: {
type: Boolean,
default: function _default() {
return config.defaultTaginputHasCounter;
}
},
field: {
type: String,
default: 'value'
},
autocomplete: Boolean,
nativeAutocomplete: String,
disabled: Boolean,
ellipsis: Boolean,
closable: {
type: Boolean,
default: true
},
confirmKeyCodes: {
type: Array,
default: function _default() {
return [13, 188];
}
},
removeOnKeys: {
type: Array,
default: function _default() {
return [8];
}
},
allowNew: Boolean,
onPasteSeparators: {
type: Array,
default: function _default() {
return [','];
}
},
beforeAdding: {
type: Function,
default: function _default() {
return true;
}
},
allowDuplicates: {
type: Boolean,
default: false
}
},
data: function data() {
return {
tags: Array.isArray(this.value) ? this.value.slice(0) : this.value || [],
newTag: '',
_elementRef: 'input',
_isTaginput: true
};
},
computed: {
rootClasses: function rootClasses() {
return {
'is-expanded': this.expanded
};
},
containerClasses: function containerClasses() {
return {
'is-focused': this.isFocused,
'is-focusable': this.hasInput
};
},
valueLength: function valueLength() {
return this.newTag.trim().length;
},
defaultSlotName: function defaultSlotName() {
return this.hasDefaultSlot ? 'default' : 'dontrender';
},
emptySlotName: function emptySlotName() {
return this.hasEmptySlot ? 'empty' : 'dontrender';
},
headerSlotName: function headerSlotName() {
return this.hasHeaderSlot ? 'header' : 'dontrender';
},
footerSlotName: function footerSlotName() {
return this.hasFooterSlot ? 'footer' : 'dontrender';
},
hasDefaultSlot: function hasDefaultSlot() {
return !!this.$scopedSlots.default;
},
hasEmptySlot: function hasEmptySlot() {
return !!this.$slots.empty;
},
hasHeaderSlot: function hasHeaderSlot() {
return !!this.$slots.header;
},
hasFooterSlot: function hasFooterSlot() {
return !!this.$slots.footer;
},
/**
* Show the input field if a maxtags hasn't been set or reached.
*/
hasInput: function hasInput() {
return this.maxtags == null || this.tagsLength < this.maxtags;
},
tagsLength: function tagsLength() {
return this.tags.length;
},
/**
* If Taginput has onPasteSeparators prop,
* returning new RegExp used to split pasted string.
*/
separatorsAsRegExp: function separatorsAsRegExp() {
var sep = this.onPasteSeparators;
return sep.length ? new RegExp(sep.map(function (s) {
return s ? s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') : null;
}).join('|'), 'g') : null;
}
},
watch: {
/**
* When v-model is changed set internal value.
*/
value: function value(_value) {
this.tags = _value;
},
hasInput: function hasInput() {
if (!this.hasInput) this.onBlur();
}
},
methods: {
addTag: function addTag(tag) {
var tagToAdd = tag || this.newTag.trim();
if (tagToAdd) {
if (!this.autocomplete) {
var reg = this.separatorsAsRegExp;
if (reg && tagToAdd.match(reg)) {
tagToAdd.split(reg).map(function (t) {
return t.trim();
}).filter(function (t) {
return t.length !== 0;
}).map(this.addTag);
return;
}
} // Add the tag input if it is not blank
// or previously added (if not allowDuplicates).
var add = !this.allowDuplicates ? this.tags.indexOf(tagToAdd) === -1 : true;
if (add && this.beforeAdding(tagToAdd)) {
this.tags.push(tagToAdd);
this.$emit('input', this.tags);
this.$emit('add', tagToAdd);
}
}
this.newTag = '';
},
getNormalizedTagText: function getNormalizedTagText(tag) {
if (_typeof(tag) === 'object') {
return getValueByPath(tag, this.field);
}
return tag;
},
customOnBlur: function customOnBlur($event) {
// Add tag on-blur if not select only
if (!this.autocomplete) this.addTag();
this.onBlur($event);
},
onSelect: function onSelect(option) {
var _this = this;
if (!option) return;
this.addTag(option);
this.$nextTick(function () {
_this.newTag = '';
});
},
removeTag: function removeTag(index) {
var tag = this.tags.splice(index, 1)[0];
this.$emit('input', this.tags);
this.$emit('remove', tag);
return tag;
},
removeLastTag: function removeLastTag() {
if (this.tagsLength > 0) {
this.removeTag(this.tagsLength - 1);
}
},
keydown: function keydown(event) {
if (this.removeOnKeys.indexOf(event.keyCode) !== -1 && !this.newTag.length) {
this.removeLastTag();
} // Stop if is to accept select only
if (this.autocomplete && !this.allowNew) return;
if (this.confirmKeyCodes.indexOf(event.keyCode) >= 0) {
event.preventDefault();
this.addTag();
}
},
onTyping: function onTyping($event) {
this.$emit('typing', $event.trim());
}
}
};
/* script */
const __vue_script__$V = script$V;
/* template */
var __vue_render__$P = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"taginput control",class:_vm.rootClasses},[_c('div',{staticClass:"taginput-container",class:[_vm.statusType, _vm.size, _vm.containerClasses],attrs:{"disabled":_vm.disabled},on:{"click":function($event){_vm.hasInput && _vm.focus($event);}}},[_vm._l((_vm.tags),function(tag,index){return _c('b-tag',{key:index,attrs:{"type":_vm.type,"size":_vm.size,"rounded":_vm.rounded,"attached":_vm.attached,"tabstop":false,"disabled":_vm.disabled,"ellipsis":_vm.ellipsis,"closable":_vm.closable,"title":_vm.ellipsis && _vm.getNormalizedTagText(tag)},on:{"close":function($event){return _vm.removeTag(index)}}},[_vm._v("\n "+_vm._s(_vm.getNormalizedTagText(tag))+"\n ")])}),_vm._v(" "),(_vm.hasInput)?_c('b-autocomplete',_vm._b({ref:"autocomplete",attrs:{"data":_vm.data,"field":_vm.field,"icon":_vm.icon,"icon-pack":_vm.iconPack,"maxlength":_vm.maxlength,"has-counter":false,"size":_vm.size,"disabled":_vm.disabled,"loading":_vm.loading,"autocomplete":_vm.nativeAutocomplete,"keep-first":!_vm.allowNew,"use-html5-validation":_vm.useHtml5Validation},on:{"typing":_vm.onTyping,"focus":_vm.onFocus,"blur":_vm.customOnBlur,"select":_vm.onSelect},nativeOn:{"keydown":function($event){return _vm.keydown($event)}},scopedSlots:_vm._u([{key:_vm.defaultSlotName,fn:function(props){return [_vm._t("default",null,{"option":props.option,"index":props.index})]}}],null,true),model:{value:(_vm.newTag),callback:function ($$v) {_vm.newTag=$$v;},expression:"newTag"}},'b-autocomplete',_vm.$attrs,false),[_c('template',{slot:_vm.headerSlotName},[_vm._t("header")],2),_vm._v(" "),_vm._v(" "),_c('template',{slot:_vm.emptySlotName},[_vm._t("empty")],2),_vm._v(" "),_c('template',{slot:_vm.footerSlotName},[_vm._t("footer")],2)],2):_vm._e()],2),_vm._v(" "),(_vm.hasCounter && (_vm.maxtags || _vm.maxlength))?_c('small',{staticClass:"help counter"},[(_vm.maxlength && _vm.valueLength > 0)?[_vm._v("\n "+_vm._s(_vm.valueLength)+" / "+_vm._s(_vm.maxlength)+"\n ")]:(_vm.maxtags)?[_vm._v("\n "+_vm._s(_vm.tagsLength)+" / "+_vm._s(_vm.maxtags)+"\n ")]:_vm._e()],2):_vm._e()])};
var __vue_staticRenderFns__$P = [];
/* style */
const __vue_inject_styles__$V = undefined;
/* scoped */
const __vue_scope_id__$V = undefined;
/* module identifier */
const __vue_module_identifier__$V = undefined;
/* functional template */
const __vue_is_functional_template__$V = false;
/* style inject */
/* style inject SSR */
var Taginput = normalizeComponent_1(
{ render: __vue_render__$P, staticRenderFns: __vue_staticRenderFns__$P },
__vue_inject_styles__$V,
__vue_script__$V,
__vue_scope_id__$V,
__vue_is_functional_template__$V,
__vue_module_identifier__$V,
undefined,
undefined
);
var Plugin$w = {
install: function install(Vue) {
registerComponent(Vue, Taginput);
}
};
use(Plugin$w);
var Plugin$x = {
install: function install(Vue) {
registerComponent(Vue, Timepicker);
}
};
use(Plugin$x);
//
var script$W = {
name: 'BToast',
mixins: [NoticeMixin],
data: function data() {
return {
newDuration: this.duration || config.defaultToastDuration
};
}
};
/* script */
const __vue_script__$W = script$W;
/* template */
var __vue_render__$Q = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"enter-active-class":_vm.transition.enter,"leave-active-class":_vm.transition.leave}},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"toast",class:[_vm.type, _vm.position],attrs:{"aria-hidden":!_vm.isActive,"role":"alert"}},[_c('div',{domProps:{"innerHTML":_vm._s(_vm.message)}})])])};
var __vue_staticRenderFns__$Q = [];
/* style */
const __vue_inject_styles__$W = undefined;
/* scoped */
const __vue_scope_id__$W = undefined;
/* module identifier */
const __vue_module_identifier__$W = undefined;
/* functional template */
const __vue_is_functional_template__$W = false;
/* style inject */
/* style inject SSR */
var Toast = normalizeComponent_1(
{ render: __vue_render__$Q, staticRenderFns: __vue_staticRenderFns__$Q },
__vue_inject_styles__$W,
__vue_script__$W,
__vue_scope_id__$W,
__vue_is_functional_template__$W,
__vue_module_identifier__$W,
undefined,
undefined
);
var ToastProgrammatic = {
open: function open(params) {
var parent;
if (typeof params === 'string') {
params = {
message: params
};
}
var defaultParam = {
position: config.defaultToastPosition || 'is-top'
};
if (params.parent) {
parent = params.parent;
delete params.parent;
}
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : Vue;
var ToastComponent = vm.extend(Toast);
return new ToastComponent({
parent: parent,
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin$y = {
install: function install(Vue) {
registerComponentProgrammatic(Vue, 'toast', ToastProgrammatic);
}
};
use(Plugin$y);
var Plugin$z = {
install: function install(Vue) {
registerComponent(Vue, Tooltip);
}
};
use(Plugin$z);
//
var script$X = {
name: 'BUpload',
mixins: [FormElementMixin],
inheritAttrs: false,
props: {
value: {
type: [Object, Function, File, Array]
},
multiple: Boolean,
disabled: Boolean,
accept: String,
dragDrop: Boolean,
type: {
type: String,
default: 'is-primary'
},
native: {
type: Boolean,
default: false
}
},
data: function data() {
return {
newValue: this.value,
dragDropFocus: false,
_elementRef: 'input'
};
},
watch: {
/**
* When v-model is changed:
* 1. Get value from input file
* 2. Set internal value.
* 3. Reset input value if array is empty or when input file is not found in newValue
* 4. If it's invalid, validate again.
*/
value: function value(_value) {
var inputFiles = this.$refs.input.files;
this.newValue = _value;
if (!this.newValue || Array.isArray(this.newValue) && this.newValue.length === 0 || !inputFiles[0] || Array.isArray(this.newValue) && !this.newValue.some(function (a) {
return a.name === inputFiles[0].name;
})) {
this.$refs.input.value = null;
}
!this.isValid && !this.dragDrop && this.checkHtml5Validity();
}
},
methods: {
/**
* Listen change event on input type 'file',
* emit 'input' event and validate
*/
onFileChange: function onFileChange(event) {
if (this.disabled || this.loading) return;
if (this.dragDrop) {
this.updateDragDropFocus(false);
}
var value = event.target.files || event.dataTransfer.files;
if (value.length === 0) {
if (!this.newValue) {
return;
}
if (this.native) {
this.newValue = null;
}
} else if (!this.multiple) {
// only one element in case drag drop mode and isn't multiple
if (this.dragDrop && value.length !== 1) return;else {
var file = value[0];
if (this.checkType(file)) {
this.newValue = file;
} else if (this.newValue) {
this.newValue = null;
} else {
return;
}
}
} else {
// always new values if native or undefined local
var newValues = false;
if (this.native || !this.newValue) {
this.newValue = [];
newValues = true;
}
for (var i = 0; i < value.length; i++) {
var _file = value[i];
if (this.checkType(_file)) {
this.newValue.push(_file);
newValues = true;
}
}
if (!newValues) {
return;
}
}
this.$emit('input', this.newValue);
!this.dragDrop && this.checkHtml5Validity();
},
/**
* Listen drag-drop to update internal variable
*/
updateDragDropFocus: function updateDragDropFocus(focus) {
if (!this.disabled && !this.loading) {
this.dragDropFocus = focus;
}
},
/**
* Check mime type of file
*/
checkType: function checkType(file) {
if (!this.accept) return true;
var types = this.accept.split(',');
if (types.length === 0) return true;
var valid = false;
for (var i = 0; i < types.length && !valid; i++) {
var type = types[i].trim();
if (type) {
if (type.substring(0, 1) === '.') {
// check extension
var extIndex = file.name.lastIndexOf('.');
var extension = extIndex >= 0 ? file.name.substring(extIndex) : '';
if (extension.toLowerCase() === type.toLowerCase()) {
valid = true;
}
} else {
// check mime type
if (file.type.match(type)) {
valid = true;
}
}
}
}
return valid;
}
}
};
/* script */
const __vue_script__$X = script$X;
/* template */
var __vue_render__$R = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('label',{staticClass:"upload control"},[(!_vm.dragDrop)?[_vm._t("default")]:_c('div',{staticClass:"upload-draggable",class:[_vm.type, {
'is-loading': _vm.loading,
'is-disabled': _vm.disabled,
'is-hovered': _vm.dragDropFocus
}],on:{"dragover":function($event){$event.preventDefault();return _vm.updateDragDropFocus(true)},"dragleave":function($event){$event.preventDefault();return _vm.updateDragDropFocus(false)},"dragenter":function($event){$event.preventDefault();return _vm.updateDragDropFocus(true)},"drop":function($event){$event.preventDefault();return _vm.onFileChange($event)}}},[_vm._t("default")],2),_vm._v(" "),_c('input',_vm._b({ref:"input",attrs:{"type":"file","multiple":_vm.multiple,"accept":_vm.accept,"disabled":_vm.disabled},on:{"change":_vm.onFileChange}},'input',_vm.$attrs,false))],2)};
var __vue_staticRenderFns__$R = [];
/* style */
const __vue_inject_styles__$X = undefined;
/* scoped */
const __vue_scope_id__$X = undefined;
/* module identifier */
const __vue_module_identifier__$X = undefined;
/* functional template */
const __vue_is_functional_template__$X = false;
/* style inject */
/* style inject SSR */
var Upload = normalizeComponent_1(
{ render: __vue_render__$R, staticRenderFns: __vue_staticRenderFns__$R },
__vue_inject_styles__$X,
__vue_script__$X,
__vue_scope_id__$X,
__vue_is_functional_template__$X,
__vue_module_identifier__$X,
undefined,
undefined
);
var Plugin$A = {
install: function install(Vue) {
registerComponent(Vue, Upload);
}
};
use(Plugin$A);
var components = /*#__PURE__*/Object.freeze({
Autocomplete: Plugin,
Button: Plugin$1,
Carousel: Plugin$2,
Checkbox: Plugin$3,
Clockpicker: Plugin$5,
Collapse: Plugin$4,
Datepicker: Plugin$6,
Datetimepicker: Plugin$7,
Dialog: Plugin$8,
Dropdown: Plugin$9,
Field: Plugin$a,
Icon: Plugin$b,
Input: Plugin$c,
Loading: Plugin$d,
Menu: Plugin$e,
Message: Plugin$f,
Modal: Plugin$g,
Navbar: Plugin$i,
Notification: Plugin$h,
Numberinput: Plugin$j,
Pagination: Plugin$k,
Progress: Plugin$l,
Radio: Plugin$m,
Rate: Plugin$n,
Select: Plugin$o,
Slider: Plugin$p,
Snackbar: Plugin$q,
Steps: Plugin$r,
Switch: Plugin$s,
Table: Plugin$t,
Tabs: Plugin$u,
Tag: Plugin$v,
Taginput: Plugin$w,
Timepicker: Plugin$x,
Toast: Plugin$y,
Tooltip: Plugin$z,
Upload: Plugin$A
});
var Buefy = {
install: function install(Vue) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// Options
setOptions(merge(config, options, true)); // Components
for (var componentKey in components) {
Vue.use(components[componentKey]);
} // Config component
var BuefyProgrammatic = {
getOptions: function getOptions() {
return config;
},
setOptions: function setOptions$1(options) {
setOptions(merge(config, options, true));
}
};
registerComponentProgrammatic(Vue, 'config', BuefyProgrammatic);
}
};
use(Buefy);
exports.Autocomplete = Plugin;
exports.Button = Plugin$1;
exports.Carousel = Plugin$2;
exports.Checkbox = Plugin$3;
exports.Clockpicker = Plugin$5;
exports.Collapse = Plugin$4;
exports.Datepicker = Plugin$6;
exports.Datetimepicker = Plugin$7;
exports.Dialog = Plugin$8;
exports.DialogProgrammatic = DialogProgrammatic;
exports.Dropdown = Plugin$9;
exports.Field = Plugin$a;
exports.Icon = Plugin$b;
exports.Input = Plugin$c;
exports.Loading = Plugin$d;
exports.LoadingProgrammatic = LoadingProgrammatic;
exports.Menu = Plugin$e;
exports.Message = Plugin$f;
exports.Modal = Plugin$g;
exports.ModalProgrammatic = ModalProgrammatic;
exports.Navbar = Plugin$i;
exports.Notification = Plugin$h;
exports.NotificationProgrammatic = NotificationProgrammatic;
exports.Numberinput = Plugin$j;
exports.Pagination = Plugin$k;
exports.Progress = Plugin$l;
exports.Radio = Plugin$m;
exports.Rate = Plugin$n;
exports.Select = Plugin$o;
exports.Slider = Plugin$p;
exports.Snackbar = Plugin$q;
exports.SnackbarProgrammatic = SnackbarProgrammatic;
exports.Steps = Plugin$r;
exports.Switch = Plugin$s;
exports.Table = Plugin$t;
exports.Tabs = Plugin$u;
exports.Tag = Plugin$v;
exports.Taginput = Plugin$w;
exports.Timepicker = Plugin$x;
exports.Toast = Plugin$y;
exports.ToastProgrammatic = ToastProgrammatic;
exports.Tooltip = Plugin$z;
exports.Upload = Plugin$A;
exports.default = Buefy;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2019 all rights reserved
#
# access to the framework
import pyre
# superclass
from .Tool import Tool
from .Library import Library
# the cython package manager
class Cython(Tool, family='pyre.externals.cython'):
"""
The package manager for the cython interpreter
"""
# constants
category = 'cython'
# user configurable state
compiler = pyre.properties.str()
compiler.doc = 'the name of the compiler; may be the full path to the executable'
# support for specific package managers
@classmethod
def dpkgAlternatives(cls, dpkg):
"""
Go through the installed packages and identify those that are relevant for providing
support for my installations
"""
# get the index of installed packages
installed = dpkg.installed()
# the cython 3.x development packages
cython3 = 'cython3',
# find the missing ones
missing = [ pkg for pkg in cython3 if pkg not in installed ]
# if there are no missing ones
if not missing:
# hand back a pyre safe name and the list of packages
yield Cython3.flavor, cython3
# the cython 2.x development packages
cython2 = 'cython',
# find the missing ones
missing = [ pkg for pkg in cython2 if pkg not in installed ]
# if there are no missing ones
if not missing:
# hand back a pyre safe name and the list of packages
yield Cython2.flavor, cython2
# all done
return
@classmethod
def dpkgPackages(cls, packager):
"""
Identify the default implementation of BLAS on dpkg machines
"""
# ask {dpkg} for my options
alternatives = sorted(packager.alternatives(group=cls), reverse=True)
# the order of preference of these implementations
versions = Cython3, Cython2
# go through the versions
for version in versions:
# scan through the alternatives
for name in alternatives:
# if it is match
if name.startswith(version.flavor):
# build an instance and return it
yield version(name=name)
# out of ideas
return
@classmethod
def macportsPackages(cls, packager):
"""
Provide alternative compatible implementations of cython on macports machines, starting
with the package the user has selected as the default
"""
# on macports, {cython3} and {cython2} are in the same package group; try cython3.x
# installations followed by cython 2.x
versions = [ Cython3, Cython2 ]
# go through my choices
for version in versions:
# ask macports for all available alternatives
for package in packager.alternatives(group=version.category):
# instantiate each one using the package name and hand it to the caller
yield version(name=package)
# out of ideas
return
# superclass
from .ToolInstallation import ToolInstallation
# the cython package manager
class Default(
ToolInstallation,
family='pyre.externals.cython.default', implements=Cython):
"""
The package manager for cython instances
"""
# constants
category = Cython.category
flavor = category
# public state
compiler = pyre.properties.str()
compiler.doc = 'the name of the cython compiler'
# configuration
def dpkg(self, packager):
"""
Attempt to repair my configuration
"""
# get the names of the packages that support me
bin, *_ = packager.identify(installation=self)
# get the version info
self.version, _ = packager.info(package=bin)
# get my flavor
flavor = self.flavor
# the name of the interpreter
self.compiler = 'cython' if flavor == 'cython2' else flavor
# look for it in the bin directory so we don't pick up something else
compiler = 'bin/{}'.format(self.compiler)
# find it in order to identify my {bindir}
prefix = packager.findfirst(target=compiler, contents=packager.contents(package=bin))
# and save it
self.bindir = [ prefix / 'bin' ] if prefix else []
# set the prefix
self.prefix = prefix
# all done
return
def macports(self, packager):
"""
Attempt to repair my configuration
"""
# ask macports for help; start by finding out which package is related to me
package = packager.identify(installation=self)
# get the version info
self.version, _ = packager.info(package=package)
# and the package contents
contents = tuple(packager.contents(package=package))
# {cython} is a selection group
group = self.category
# the package deposits its selection alternative here
selection = str(packager.prefix() / 'etc' / 'select' / group / '(?P<alternate>.*)')
# so find it
match = next(packager.find(target=selection, pile=contents))
# extract the name of the alternative
alternative = match.group('alternate')
# ask for the normalization data
normalization = packager.getNormalization(group=group, alternative=alternative)
# build the normalization map
nmap = { base: target for base,target in zip(*normalization) }
# find the binary that supports {cython} and use it to set my compiler
self.compiler = nmap[pyre.primitives.path('bin/cython')].name
# look for it to get my {bindir}
bindir = packager.findfirst(target=self.compiler, contents=contents)
# and save it
self.bindir = [ bindir ] if bindir else []
# now that we have everything, compute the prefix
self.prefix = self.bindir[0].parent
# all done
return
# cython 2
class Cython2(Default, family='pyre.externals.cython.cython2'):
"""
The package manager for cython 2.x instances
"""
# constants
flavor = Default.flavor + '2'
# cython 3
class Cython3(Default, family='pyre.externals.cython.cython3'):
"""
The package manager for cython 3.x instances
"""
# constants
flavor = Default.flavor + '3'
# end of file
|
import React from 'react';
import classes from './Burger.css'
import BurgerIncredients from './BurgerIncredients/BurgerIncredients';
const burger = (props) => {
// console.log(props)
let transformedIngredients = Object.keys(props.ingredients)
.map(igKey => {
return [...Array(props.ingredients[igKey])].map((_, i) => {
return <BurgerIncredients key={igKey + i} type={igKey} />
})
})
.reduce((arr, el) => {
return arr.concat(el)
}, [])
if (transformedIngredients.length === 0){
transformedIngredients = <p>Please start adding ingredients!!</p>
}
return(
<div className={classes.Burger}>
<BurgerIncredients type="bread-top" />
{transformedIngredients}
<BurgerIncredients type="bread-bottom" />
</div>
)
}
export default burger |
(window.webpackJsonp=window.webpackJsonp||[]).push([[10],{yZlL:function(e,t,a){"use strict";a.r(t);var r=a("wTIg"),n=(a("q1tI"),a("Bl7J")),i=a("vrFN"),o=a("qKvR"),b=Object(r.a)("div",{target:"esi98yr0"})({name:"hu0znc",styles:"margin:0 auto;max-width:860px;padding:1.45rem 1.0875rem;"}),d=Object(r.a)("h1",{target:"esi98yr1"})({name:"n1d11z",styles:"display:inline;border-radius:1em 0 1em 0;background-image:linear-gradient( -100deg,rgba(255,250,150,0.15),rgba(255,250,150,0.8) 100%,rgba(255,250,150,0.25) );"}),s=Object(r.a)("h3",{target:"esi98yr2"})({name:"wvcn4j",styles:"margin-top:10px;color:#606060;"}),c=Object(r.a)("div",{target:"esi98yr3"})({name:"157c1zx",styles:"a{text-decoration:none;position:relative;background-image:linear-gradient( rgba(255,250,150,0.8),rgba(255,250,150,0.8) );background-repeat:no-repeat;background-size:100% 0.2em;background-position:0 88%;transition:background-size 0.25s ease-in;&:hover{background-size:100% 88%;}}"});t.default=function(e){var t=e.data.markdownRemark;return Object(o.b)(n.a,null,Object(o.b)(i.a,{title:t.frontmatter.title,description:t.frontmatter.description||t.excerpt}),Object(o.b)(b,null,Object(o.b)(d,null,t.frontmatter.title),Object(o.b)(s,null,t.frontmatter.date," - ",t.fields.readingTime.text),Object(o.b)(c,{dangerouslySetInnerHTML:{__html:t.html}})))}}}]);
//# sourceMappingURL=component---src-templates-blog-post-js-40f03213032577dfd50e.js.map |
import { attachAll } from '../../../../other/boilerplate-utils.js';
const ngModule = angular.module('da.desktop.transactions', []);
attachAll(require.context('./components', true, /\.(component|directive)\.js$/))(ngModule);
attachAll(require.context('./containers', true, /\.(component|directive)\.js$/))(ngModule);
ngModule.config(transactionsConfig);
function transactionsConfig($stateProvider) {
$stateProvider.state('transactions', {
url: '/transactions',
template: '<transactions-container category-filter="$ctrl.categoryFilters"></transactions-container>'
});
}
transactionsConfig.$inject = ['$stateProvider'];
export default ngModule;
|
var IS_TEST_MODE = global.IS_TEST_MODE || false;
var Board = require("../lib/board.js");
var Pins = Board.Pins;
var events = require("events");
var Emitter = require("events").EventEmitter;
var util = require("util");
var __ = require("../lib/fn.js");
var nanosleep = require("../lib/sleep.js").nano;
var Animation = require("../lib/animation.js");
// Servo instance private data
var priv = new Map();
var Controllers = {
PCA9685: {
COMMANDS: {
value: {
PCA9685_MODE1: 0x0,
PCA9685_PRESCALE: 0xFE,
LED0_ON_L: 0x6
}
},
servoWrite: {
value: function(pin, degrees) {
var on, off;
// If same degrees, emit "move:complete" and return immediately.
if (this.last && this.last.degrees === degrees) {
//process.nextTick(this.emit.bind(this, "move:complete"));
this.emit("move:complete");
return this;
}
on = 0;
off = __.map(degrees, 0, 180, this.pwmRange[0]/4, this.pwmRange[1]/4 );
this.io.sendI2CWriteRequest(this.address, [this.COMMANDS.LED0_ON_L + 4 * (pin), on, on >> 8, off, off >> 8]);
}
},
initialize: {
value: function(opts) {
this.address = opts.address || 0x40;
this.pwmRange = opts.pwmRange || [544, 2400];
if (!this.board.Drivers[opts.address]) {
this.io.sendI2CConfig();
this.board.Drivers[opts.address] = {
initialized: false
};
// Reset
this.io.sendI2CWriteRequest(this.address, [this.COMMANDS.PCA9685_MODE1, 0x0]);
// Sleep
this.io.sendI2CWriteRequest(this.address, [this.COMMANDS.PCA9685_MODE1, 0x10]);
// Set prescalar
this.io.sendI2CWriteRequest(this.address, [this.COMMANDS.PCA9685_PRESCALE, 0x70]);
// Wake up
this.io.sendI2CWriteRequest(this.address, [this.COMMANDS.PCA9685_MODE1, 0x0]);
// Wait 5 nanoseconds for restart
nanosleep(5);
// Auto-increment
this.io.sendI2CWriteRequest(this.address, [this.COMMANDS.PCA9685_MODE1, 0xa1]);
this.board.Drivers[this.address].initialized = true;
}
}
}
},
Standard: {
initialize: {
value: function(opts, pinValue) {
// When in debug mode, if pin is not a PWM pin, emit an error
if (opts.debug && !this.board.pins.isServo(this.pin)) {
Board.Pins.Error({
pin: this.pin,
type: "PWM",
via: "Servo",
});
}
if (Array.isArray(opts.pwmRange)) {
this.io.servoConfig(this.pin, opts.pwmRange[0], opts.pwmRange[1]);
} else {
this.io.pinMode(this.pin, this.mode);
}
}
},
servoWrite: {
value: function(pin, degrees) {
// Servo is restricted to integers
degrees |= 0;
// If same degrees, emit "move:complete" and return immediately.
if (this.last && this.last.degrees === degrees) {
//process.nextTick(this.emit.bind(this, "move:complete"));
this.emit("move:complete");
return this;
}
this.io.servoWrite(this.pin, degrees);
}
}
}
};
/**
* Servo
* @constructor
*
* @param {Object} opts Options: pin, type, id, range
*/
function Servo(opts) {
var history = [];
var pinValue;
var controller;
if (!(this instanceof Servo)) {
return new Servo(opts);
}
pinValue = typeof opts === "object" ? opts.pin : opts;
Board.Component.call(
this, opts = Board.Options(opts)
);
this.id = opts.id || Board.uid();
this.range = opts.range || [0, 180];
this.deadband = opts.deadband || [90, 90];
this.fps = opts.fps || 100;
this.offset = opts.offset || 0;
this.mode = this.io.MODES.SERVO;
this.interval = null;
this.value = null;
/**
* Used for adding special controllers (i.e. PCA9685)
**/
controller = typeof opts.controller === "string" ?
Controllers[opts.controller] : Controllers.Standard;
Object.defineProperties(this, controller);
this.initialize(opts, pinValue);
// StandardFirmata on Arduino allows controlling
// servos from analog pins.
// If we're currently operating with an Arduino
// and the user has provided an analog pin name
// (eg. "A0", "A5" etc.), parse out the numeric
// value and capture the fully qualified analog
// pin number.
if (Pins.isFirmata(this)) {
if (typeof pinValue === "string" && pinValue[0] === "A") {
pinValue = this.io.analogPins[+pinValue.slice(1)];
}
pinValue = +pinValue;
// If the board's default pin normalization
// came up with something different, use the
// the local value.
if (this.pin !== pinValue) {
this.pin = pinValue;
}
}
// The type of servo determines certain alternate
// behaviours in the API
this.type = opts.type || "standard";
// Invert the value of all servoWrite operations
// eg. 80 => 100, 90 => 90, 0 => 180
this.isInverted = opts.isInverted || false;
// Specification config
this.specs = opts.specs || {
speed: Servo.Continuous.speeds["@5.0V"]
};
// Collect all movement history for this servo
// history = [
// {
// timestamp: Date.now(),
// degrees: degrees
// }
// ];
priv.set(this, {
history: history
});
// Create a non-writable "last" property
// shortcut to access the last servo movement
Object.defineProperties(this, {
history: {
get: function() {
return history.slice(-5);
}
},
last: {
get: function() {
return history[history.length - 1];
}
},
position: {
get: function() {
return history[history.length - 1].degrees;
}
}
});
// Allow "setup"instructions to come from
// constructor options properties
this.startAt = 90;
// If "startAt" is defined and center is falsy
// set servo to min or max degrees
if (opts.startAt !== undefined) {
this.startAt = opts.startAt;
if (!opts.center) {
this.to(opts.startAt);
}
}
// If "center" true set servo to 90deg
if (opts.center) {
this.center();
}
}
util.inherits(Servo, Emitter);
/**
* to
*
* Set the servo horn's position to given degree over time.
*
* @param {Number} degrees Degrees to turn servo to.
* @param {Number} time Time to spend in motion.
* @param {Number} rate The rate of the motion transiton
*
* @return {Servo} instance
*/
Servo.prototype.to = function(degrees, time, rate) {
var target = degrees;
degrees += this.offset;
// Enforce limited range of motion
degrees = Board.constrain(degrees, this.range[0], this.range[1]);
this.value = degrees;
var last, distance, percent;
var isReverse = false;
var history = priv.get(this).history;
if (this.isInverted) {
degrees = Board.map(
degrees,
this.range[0], this.range[1],
this.range[1], this.range[0]
);
}
if (typeof time !== "undefined") {
// If rate is not passed, calculate based on time and fps
rate = rate || Math.ceil(time / 1000) * this.fps;
last = this.last && this.last.degrees || 0;
distance = Math.abs(last - degrees);
percent = 0;
if (distance === 0) {
process.nextTick(this.emit.bind(this, "move:complete"));
return this;
}
// If steps are limited by Servo resolution
if (distance < rate) {
rate = distance;
}
if (this.interval) {
clearInterval(this.interval);
}
if (degrees < last) {
isReverse = true;
}
this.interval = setInterval(function() {
var delta = ++percent * (distance / rate);
if (isReverse) {
delta *= -1;
}
this.servoWrite(this.pin, last + delta);
history.push({
timestamp: Date.now(),
degrees: last + delta,
target: target
});
if (percent === rate) {
this.emit("move:complete");
clearInterval(this.interval);
}
}.bind(this), time / rate);
} else {
this.servoWrite(this.pin, degrees);
history.push({
timestamp: Date.now(),
degrees: degrees,
target: target
});
}
// return this instance
return this;
};
/**
* Animation.normalize
*
* @param [number || object] keyFrames An array of step values or a keyFrame objects
*/
Servo.prototype[Animation.normalize] = function(keyFrames) {
var last = this.last ? this.last.target : this.startAt;
// If user passes null as the first element in keyFrames use current position
if (keyFrames[0] === null) {
keyFrames[0] = {
degrees: last
};
}
return keyFrames;
};
/**
* Animation.render
*
* @position [number] value to set the servo to
*/
Servo.prototype[Animation.render] = function(position) {
return this.to(position[0]);
};
/**
* step
*
* Update the servo horn's position by specified degrees (over time)
*
* @param {Number} degrees Degrees to turn servo to.
* @param {Number} time Time to spend in motion.
*
* @return {Servo} instance
*/
Servo.prototype.step = function(degrees, time) {
return this.to(this.last.target + degrees, time);
};
/**
* move Alias for Servo.prototype.to
*/
Servo.prototype.move = function(degrees, time) {
console.warn("Servo.prototype.move has been renamed to Servo.prototype.to");
return this.to(degrees, time);
};
/**
* min Set Servo to minimum degrees, defaults to 0deg
* @return {Object} instance
*/
Servo.prototype.min = function() {
return this.to(this.range[0]);
};
/**
* max Set Servo to maximum degrees, defaults to 180deg
* @return {[type]} [description]
*/
Servo.prototype.max = function() {
return this.to(this.range[1]);
};
/**
* center Set Servo to centerpoint, defaults to 90deg
* @return {[type]} [description]
*/
Servo.prototype.center = function() {
return this.to(Math.abs((this.range[0] + this.range[1]) / 2));
};
/**
* sweep Sweep the servo between min and max or provided range
* @param {Array} range constrain sweep to range
*
* @param {Object} options Set range or interval.
*
* @return {[type]} [description]
*/
Servo.prototype.sweep = function(opts) {
var degrees,
range = this.range,
interval = 100,
step = 10;
opts = opts || {};
// If opts is an array, then assume a range was passed
//
// - This implies:
// - an interval of 100ms.
// - a step of 10 degrees
//
if (Array.isArray(opts)) {
range = opts;
} else {
// Otherwise, opts is an object.
//
// - Check for:
// - a range, if present use it, otherwise
// use the servo's range property.
// - an interval, if present use it, otherwise
// use the default interval.
// - a step, if present use it, otherwise
// use the default step
//
range = opts.range || range;
interval = opts.interval || interval;
step = opts.step || step;
}
degrees = range[0];
// If the last recorded movement was not range[0]deg
// move the servo to range[0]deg
if (this.last && this.last.degrees !== degrees) {
this.to(degrees);
}
if (this.interval) {
clearInterval(this.interval);
}
this.interval = setInterval(function() {
var abs;
if (degrees >= range[1] || degrees < range[0]) {
if (degrees >= range[1]) {
this.emit("sweep:half");
}
step *= -1;
}
if (degrees === range[0]) {
if (step !== (abs = Math.abs(step))) {
this.emit("sweep:full");
step = abs;
}
}
degrees += step;
this.to(degrees);
}.bind(this), interval);
return this;
};
/**
* stop Stop a moving servo
* @return {[type]} [description]
*/
Servo.prototype.stop = function() {
if (this.type === "continuous") {
this.to(90);
} else {
clearInterval(this.interval);
}
return this;
};
//
["clockWise", "cw", "counterClockwise", "ccw"].forEach(function(api) {
Servo.prototype[api] = function(rate) {
var range;
rate = rate === undefined ? 1 : rate;
if (this.type !== "continuous") {
this.board.error(
"Servo",
"Servo.prototype." + api + " is only available for continuous servos"
);
}
if (api === "cw" || api === "clockWise") {
range = [rate, 0, 1, this.deadband[1] + 1, this.range[1]];
} else {
range = [rate, 0, 1, this.deadband[0] - 1, this.range[0]];
}
return this.to(__.scale.apply(null, range) | 0);
};
});
/**
*
* Static API
*
*
*/
Servo.Continuous = function(pinOrOpts) {
var opts = {};
if (typeof pinOrOpts === "object") {
__.extend(opts, pinOrOpts);
} else {
opts.pin = pinOrOpts;
}
opts.type = "continuous";
return new Servo(opts);
};
Servo.Continuous.speeds = {
// seconds to travel 60 degrees
"@4.8V": 0.23,
"@5.0V": 0.17,
"@6.0V": 0.18
};
/**
* Servo.Array()
* new Servo.Array()
*
* Constructs an Array-like instance of all servos
*/
Servo.Array = function(numsOrObjects) {
if (!(this instanceof Servo.Array)) {
return new Servo.Array(numsOrObjects);
}
var items = [];
if (numsOrObjects) {
while (numsOrObjects.length) {
var numOrObject = numsOrObjects.shift();
if (!(numOrObject instanceof Servo)) {
numOrObject = new Servo(numOrObject);
}
items.push(numOrObject);
}
} else {
items = items.concat(Array.from(priv.keys()));
}
this.length = items.length;
items.forEach(function(led, index) {
this[index] = led;
}, this);
};
/**
* each Execute callbackFn for each active servo instance
*
* eg.
* array.each(function( servo, index ) {
* `this` refers to the current servo instance
* });
*
* @param {[type]} callbackFn [description]
* @return {[type]} [description]
*/
Servo.Array.prototype.each = function(callbackFn) {
var length = this.length;
for (var i = 0; i < length; i++) {
callbackFn.call(this[i], this[i], i);
}
return this;
};
/**
* Servo.Array, center()
*
* centers all servos to 90deg
*
* eg. array.center();
* Servo.Array, min()
*
* set all servos to the minimum degrees
* defaults to 0
*
* eg. array.min();
* Servo.Array, max()
*
* set all servos to the maximum degrees
* defaults to 180
*
* eg. array.max();
* Servo.Array, stop()
*
* stop all servos
*
* eg. array.stop();
*/
Object.keys(Servo.prototype).forEach(function(method) {
// Create Servo.Array wrappers for each method listed.
// This will allow us control over all Servo instances
// simultaneously.
Servo.Array.prototype[method] = function() {
var length = this.length;
for (var i = 0; i < length; i++) {
this[i][method].apply(this[i], arguments);
}
return this;
};
});
/**
* Animation.normalize
*
* @param [number || object] keyFrames An array of step values or a keyFrame objects
*/
Servo.Array.prototype[Animation.normalize] = function(keyFrames) {
keyFrames.forEach(function(keyFrame, index) {
if (keyFrame !== null) {
var servo = this[index];
// If servo is a servoArray then user servo[0] for default values
if (servo instanceof Servo.Array) {
servo = servo[0];
}
var last = servo.last ? servo.last.target : servo.startAt;
// If the first position is null use the current position
if (keyFrame[0] === null) {
keyFrames[index][0] = {
degrees: last
};
}
if (Array.isArray(keyFrame)) {
if (keyFrame[0] === null) {
keyFrames[index][0] = {
degrees: last
};
}
}
}
}, this);
return keyFrames;
};
/**
* Animation.render
*
* @position [number] array of values to set the servos to
*/
Servo.Array.prototype[Animation.render] = function(position) {
this.each(function(servo, i) {
servo.to(position[i]);
});
return this;
};
// Alias
// TODO: Deprecate and REMOVE
Servo.prototype.write = Servo.prototype.move;
if (IS_TEST_MODE) {
Servo.purge = function() {
priv.clear();
};
}
module.exports = Servo;
// References
//
// http://www.societyofrobots.com/actuators_servos.shtml
// http://www.parallax.com/Portals/0/Downloads/docs/prod/motors/900-00008-CRServo-v2.2.pdf
// http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
// http://servocity.com/html/hs-7980th_servo.html
// http://mbed.org/cookbook/Servo
// Further API info:
// http://www.tinkerforge.com/doc/Software/Bricks/Servo_Brick_Python.html#servo-brick-python-api
// http://www.tinkerforge.com/doc/Software/Bricks/Servo_Brick_Java.html#servo-brick-java-api
|
// @flow
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import routes from '../../constants/routes';
import styles from './styles.scss';
type Props = {};
export default class TvShows extends Component<Props> {
props: Props;
render() {
return (
<div className={styles.container} data-tid="container">
<div className={styles.backButton} data-tid="backButton">
<Link to={routes.HOME}>
<i className="fa fa-arrow-left fa-3x" />
</Link>
</div>
TV Shows
</div>
);
}
}
|
import nltk
import sklearn
import sklearn.naive_bayes
import sklearn.model_selection
import json
import functools
import collections
import numpy
#Load data from file
def load_data(filename):
with open(filename) as f:
data = []
readline = None
while readline != '':
readline = f.readline()
if readline != '':
data.append(json.loads(readline))
return data
def load_NRC_data(filename):
with open(filename) as f:
f.readline() #skip first line
data = {}
readline = None
while readline != '':
readline = f.readline()
if readline != '':
readline = readline.split()
data[readline[0]] = (readline[1], float(readline[2]))
return data
def get_features_ngrams(dataset, labels):
#Seperate training and test data (Note this training data will only be used to generate which ngrams are used as features)
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(dataset, labels, train_size=0.2, test_size=0.8)
#Construct ngrams from data
unigrams = []
bigrams = []
trigrams = []
for headline in X_train:
words = nltk.tokenize.word_tokenize(headline)
for word in words:
unigrams.append(word)
for index in range(len(words) - 1):
bigrams.append((words[index], words[index+1]))
for index in range(len(words) - 2):
trigrams.append((words[index], words[index+1], words[index+2]))
#Count number of each unigram, bigram, and trigram
unigram_frequencies = collections.Counter(unigrams)
bigram_frequencies = collections.Counter(bigrams)
trigram_frequencies = collections.Counter(trigrams)
#Sort ngrams by frequency
sorted_unigrams = sorted(unigram_frequencies, reverse=True, key= lambda x: unigram_frequencies[x])
sorted_bigrams = sorted(bigram_frequencies, reverse=True, key = lambda x: bigram_frequencies[x])
sorted_trigrams = sorted(trigram_frequencies, reverse=True, key = lambda x: trigram_frequencies[x])
testing_instances = numpy.zeros(shape=(len(X_test), 3000))
testing_labels = numpy.zeros(len(X_test))
#Calculate features in test data
for index in range(len(X_test)):
testing_labels[index] = y_test[index]
words = nltk.tokenize.word_tokenize(X_test[index])
for i in range(1000):
for word in words:
if sorted_unigrams[i] == word:
testing_instances[index][i] += 1
bigrams = []
trigrams = []
for index in range(len(words) - 1):
bigrams.append((words[index], words[index+1]))
for index in range(len(words) - 2):
trigrams.append((words[index], words[index+1], words[index+2]))
for i in range(1000):
for bigram in bigrams:
if sorted_bigrams[i] == bigram:
testing_instances[index][i + 1000] += 1
for i in range(1000):
for trigram in trigrams:
if sorted_trigrams[i] == trigram:
testing_instances[index][i + 2000] += 1
return testing_instances, testing_labels
def get_features_mix(dataset, labels):
data = load_NRC_data('NRC-Emotion-Intensity-Lexicon-v1.txt')
emotions = list(set([data[word][0] for word in data]))
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(dataset, labels, train_size=0.2, test_size=0.8)
dataset, labels = X_test, y_test
testing_instances = numpy.zeros(shape=(len(dataset), len(emotions) + 3006))
testing_labels = numpy.zeros(len(dataset))
#Add sum of intensities of an emotion and the number of emotional words
for instance in range(len(dataset)):
testing_labels[instance] = labels[instance]
words = nltk.tokenize.word_tokenize(dataset[instance])
for word in words:
if word in data:
emotion, intensity = data[word]
index = emotions.index(emotion)
testing_instances[instance][3000 + index] += intensity
testing_instances[instance][3000 + len(emotions)] += 1
#Add number of words in headline
for instance in range(len(dataset)):
testing_instances[instance][len(emotions) + 3001] = len(nltk.tokenize.word_tokenize(dataset[instance]))
#Add number of nouns, verbs, adjectives, and adverbs
for instance in range(len(dataset)):
words = nltk.tokenize.word_tokenize(dataset[instance])
words = nltk.pos_tag(words)
for word in words:
#Add nouns
if word[1] == 'NN' or word[1] == 'NNS':
testing_instances[instance][len(emotions) + 3002] += 1
#Add verbs
if word[1] == 'VB' or word[1] == 'VBD' or word[1] == 'VBG' or word[1] == 'VBN' or word[1] == 'VBP' or word[1] == 'VBZ':
testing_instances[instance][len(emotions) + 3003] += 1
#Add adjectives
if word[1] == 'JJR' or word[1] == 'JJS' or word[1] == 'JJ':
testing_instances[instance][len(emotions) + 3004] += 1
#Add adverbs
if word[1] == 'RB' or word[1] == 'RBR' or word[1] == 'RBS':
testing_instances[instance][len(emotions) + 3005] += 1
#Construct ngrams from data
positive_unigrams = []
negative_unigrams = []
unigrams = []
for i in range(len(X_train)):
words = nltk.tokenize.word_tokenize(X_train[i])
for word in words:
unigrams.append(word)
if labels[i] == 1:
positive_unigrams.append(word)
else:
negative_unigrams.append(word)
#Count number of each unigram for positive and negative instances
positive_unigram_counts = collections.Counter(positive_unigrams)
negative_unigram_counts = collections.Counter(negative_unigrams)
unigram_counts = collections.Counter(unigrams)
print (positive_unigram_counts['fsaojioas'])
total_positive_unigrams = sum([unigram for unigram in positive_unigram_counts])
total_negative_unigrams = sum([unigram for unigram in negative_unigrams])
#Sort ngrams by frequency
sorted_unigrams = sorted(unigram_frequencies, reverse=True, key= lambda x: unigram_frequencies[x])
sorted_bigrams = sorted(bigram_frequencies, reverse=True, key = lambda x: bigram_frequencies[x])
sorted_trigrams = sorted(trigram_frequencies, reverse=True, key = lambda x: trigram_frequencies[x])
#Add n-grams
for index in range(len(X_test)):
words = nltk.tokenize.word_tokenize(X_test[index])
for i in range(1000):
for word in words:
if sorted_unigrams[i] == word:
testing_instances[index][i] += 1
bigrams = []
trigrams = []
for index in range(len(words) - 1):
bigrams.append((words[index], words[index+1]))
for index in range(len(words) - 2):
trigrams.append((words[index], words[index+1], words[index+2]))
for i in range(1000):
for bigram in bigrams:
if sorted_bigrams[i] == bigram:
testing_instances[index][i + 1000] += 1
for i in range(1000):
for trigram in trigrams:
if sorted_trigrams[i] == trigram:
testing_instances[index][i + 2000] += 1
return testing_instances, testing_labels
def classifier(X, y, classifier, classifier_name):
#Perform 10-fold cross validation on classifier
scores = sklearn.model_selection.cross_validate(classifier, X, y, cv=10, scoring=('f1_macro', 'f1_micro', 'accuracy'))
#Print out the Accuracy and F1-scores
print('Classifier: ', classifier_name)
print('Average Macro F1 Score: ', sum(scores['test_f1_macro']) / 10)
print('Average Micro F1 Score: ', sum(scores['test_f1_micro']) / 10)
print('Average Accuracy: ', sum(scores['test_accuracy']) / 10)
print()
if __name__ == '__main__':
#Load data from file
data = load_data('Sarcasm_Headlines_Dataset.json')
#Seperate data and labels
dataset = [datum['headline'] for datum in data]
labels = [datum['is_sarcastic'] for datum in data]
#Get percentage of sarcastic examples
percentage_sarcastic = sum(labels) / len(labels)
print('Percentage of dataset that is sarcastic: ', percentage_sarcastic)
print()
#Get features from ngrams
#X, y = get_features_ngrams(dataset, labels)
#Run Naive Bayes
#classifier(X, y, sklearn.naive_bayes.MultinomialNB(), 'Multinomial Naive Bayes (ngrams)')
#Get features from mixed features
X, y = get_features_mix(dataset, labels)
#Run SVM
classifier(X, y, sklearn.svm.LinearSVC(), 'Support Vector Machine (Mixed features)')
|
module.exports = {
"parser" : "babel-eslint",
"plugins": [
"react-native"
],
"extends" : [
"airbnb"
],
"rules": {
// Soft some rules.
"semi": 0,
"max-len": 0,
"global-require": 0, // Used by webpack-isomorphic-tools and React Native.
"new-cap": [2, {"capIsNew": false, "newIsCap": true}], // For Record() etc.
"no-class-assign": 0, // Class assign is used for higher order components.
"no-nested-ternary": 0, // It's nice for JSX.
"no-param-reassign": 0, // We love param reassignment. Naming is hard.
"no-shadow": 0, // Shadowing is a nice language feature. Naming is hard.
"no-underscore-dangle": 0, // It's classic pattern to denote private props.
"object-curly-spacing": 2,
"no-multi-spaces": 0,
"react/prefer-stateless-function": 0, // We are not there yet.
"import/imports-first": 0, // Este sorts by atom/sort-lines natural order.
"react/jsx-filename-extension": 0, // No, JSX belongs to .js files
"jsx-a11y/html-has-lang": 0, // Can't recognize the Helmet.
// React Native.
"no-use-before-define": 0,
"comma-dangle": 0,
"key-spacing": 0,
"react/jsx-boolean-value": 0,
"react-native/no-unused-styles": 2,
"react-native/split-platform-components": 2,
"react-native/no-inline-styles": 0,
"react-native/no-color-literals": 0,
"react/jsx-closing-bracket-location": 0,
}
};
|
/*eslint-env node*/
/*eslint no-unused-vars:0, no-console:0*/
var fs = require('fs'),
got = require('got'),
token = require('../getToken.js')('../token.json'),
color = require('chalk'),
getAllPages = require('./canvas-get-all-pages.js'),
dsv = require('d3-dsv'),
domain = 'https://byuh.instructure.com',
course_id = '1458190',
apiCall = `/api/v1/courses/${course_id}/quizzes`,
query = {
access_token: token,
per_page: 20
};
getAllPages(domain, apiCall, query, function (err, quizes) {
//var onesWeLike = quizes.filter(quiz => quiz.title.match(/Level \d/) !== null);
var onesWeLike = quizes;
console.log("onesWeLike.length:", onesWeLike.length);
var colsWeWant = ['id', 'title', 'html_url', 'mobile_url'];
fs.writeFileSync('allTheQuizes.csv', dsv.csvFormat(onesWeLike));
fs.writeFileSync('allTheQuizesFilteredCols.csv', dsv.csvFormat(onesWeLike, colsWeWant));
});
|
import tempfile
import os
from PIL import Image
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe, Tag, Ingredient
from recipe.serializers import RecipeSerializer, RecipeDetailSerializer
RECIPES_URL = reverse('recipe:recipe-list')
# /api/recipe/recipes
# /api/recipe/recipes/1/
def image_upload_url(recipe_id):
"""Return URL for recipe image upload"""
return reverse('recipe:recipe-upload-image', args=[recipe_id])
def detail_url(recipe_id):
"""Return recipe detail url"""
return reverse('recipe:recipe-detail', args=[recipe_id])
def sample_tag(user, name='Main course'):
"""create and return a sample tag"""
return Tag.objects.create(user=user, name=name)
def sample_ingredient(user, name='Cinnamon'):
"""create and return a sample tag"""
return Ingredient.objects.create(user=user, name=name)
def sample_recipe(user, **params):
"""Create and return a sample recipe"""
defaults = {
'title': 'Sample recipe',
'time_minutes': 10,
'price': 5.00,
}
defaults.update(params)
return Recipe.objects.create(user=user, **defaults)
class PublicRecipeApiTests(TestCase):
"""Test unauthenticated recipe API access"""
def setUp(self):
self.client = APIClient()
def test_required_auth(self):
"""Test the authenticaiton is required"""
res = self.client.get(RECIPES_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateRecipeApiTests(TestCase):
"""Test authenticated recipe API access"""
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objects.create_user(
'[email protected]',
'testpass'
)
self.client.force_authenticate(self.user)
def test_retrieve_recipes(self):
"""Test retrieving list of recipes"""
sample_recipe(user=self.user)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_recipes_limited_to_user(self):
"""Test retrieving recipes for user"""
user2 = get_user_model().objects.create_user(
'[email protected]',
'pass'
)
sample_recipe(user=user2)
sample_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.filter(user=self.user)
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data, serializer.data)
def test_view_recipe_detail(self):
"""Test viewing a recipe detail"""
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
recipe.ingredients.add(sample_ingredient(user=self.user))
url = detail_url(recipe.id)
res = self.client.get(url)
serializer = RecipeDetailSerializer(recipe)
self.assertEqual(res.data, serializer.data)
def test_create_basic_recipe(self):
"""Test creating recipe"""
payload = {
'title': 'Test recipe',
'time_minutes': 30,
'price': 10.00,
}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(recipe, key))
def test_create_recipe_with_tags(self):
"""Test creating a recipe with tags"""
tag1 = sample_tag(user=self.user, name='Tag 1')
tag2 = sample_tag(user=self.user, name='Tag 2')
payload = {
'title': 'Test recipe with two tags',
'tags': [tag1.id, tag2.id],
'time_minutes': 30,
'price': 10.00
}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
tags = recipe.tags.all()
self.assertEqual(tags.count(), 2)
self.assertIn(tag1, tags)
self.assertIn(tag2, tags)
def test_create_recipe_with_ingredients(self):
"""Test creating recipe with ingredients"""
ingredient1 = sample_ingredient(user=self.user, name='Ingredient 1')
ingredient2 = sample_ingredient(user=self.user, name='Ingredient 2')
payload = {
'title': 'Test recipe with ingredients',
'ingredients': [ingredient1.id, ingredient2.id],
'time_minutes': 45,
'price': 15.00
}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
ingredients = recipe.ingredients.all()
self.assertEqual(ingredients.count(), 2)
self.assertIn(ingredient1, ingredients)
self.assertIn(ingredient2, ingredients)
def test_partial_update_recipe(self):
"""Test updating a recipe with patch"""
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
new_tag = sample_tag(user=self.user, name='Curry')
payload = {'title': 'Chicken tikka', 'tags': [new_tag.id]}
url = detail_url(recipe.id)
self.client.patch(url, payload)
recipe.refresh_from_db()
self.assertEqual(recipe.title, payload['title'])
tags = recipe.tags.all()
self.assertEqual(len(tags), 1)
self.assertIn(new_tag, tags)
def test_full_update_recipe(self):
"""Test updating a recipe with put"""
recipe = sample_recipe(user=self.user)
recipe.tags.add(sample_tag(user=self.user))
payload = {
'title': 'Spaghetti carbonara',
'time_minutes': 25,
'price': 5.00
}
url = detail_url(recipe.id)
self.client.put(url, payload)
recipe.refresh_from_db()
self.assertEqual(recipe.title, payload['title'])
self.assertEqual(recipe.time_minutes, payload['time_minutes'])
self.assertEqual(recipe.price, payload['price'])
tags = recipe.tags.all()
self.assertEqual(len(tags), 0)
class RecipeImageUploadTests(TestCase):
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objects.create_user('user', 'testpass')
self.client.force_authenticate(self.user)
self.recipe = sample_recipe(user=self.user)
def tearDown(self):
self.recipe.image.delete()
def test_upload_image_to_recipe(self):
"""Test uploading an image to recipe"""
url = image_upload_url(self.recipe.id)
with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:
img = Image.new('RGB', (10, 10))
img.save(ntf, format='JPEG')
ntf.seek(0)
res = self.client.post(url, {'image': ntf}, format='multipart')
self.recipe.refresh_from_db()
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertIn('image', res.data)
self.assertTrue(os.path.exists(self.recipe.image.path))
def test_upload_image_bad_request(self):
"""Test uploading an invalid image"""
url = image_upload_url(self.recipe.id)
res = self.client.post(url, {'image': 'notimage'}, format='multipart')
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
|
const USER_LOGIN_REQUEST = 'USER_LOGIN_REQUEST';
const USER_LOGIN_REQUEST_FAIL = 'USER_LOGIN_REQUEST_FAIL';
const USER_LOGOUT_REQUEST = 'USER_LOGOUT_REQUEST';
const USER_LOGOUT_REQUEST_SUCCESS = 'USER_LOGOUT_REQUEST_SUCCESS';
const USER_LOGOUT_REQUEST_FAIL = 'USER_LOGOUT_REQUEST_FAIL';
const USER_SAVE = 'USER_SAVE';
const USER_FRIENDS_REQUEST = 'USER_FRIENDS_REQUEST';
const USER_FRIENDS_REQUEST_SUCCESS = 'USER_FRIENDS_REQUEST_SUCCESS';
const USER_FRIENDS_REQUEST_FAIL = 'USER_FRIENDS_REQUEST_FAIL';
const USER_PROFILE_REQUEST = 'USER_PROFILE_REQUEST';
const UserActionTypes = {
USER_LOGIN_REQUEST,
USER_LOGIN_REQUEST_FAIL,
USER_SAVE,
USER_LOGOUT_REQUEST,
USER_LOGOUT_REQUEST_SUCCESS,
USER_LOGOUT_REQUEST_FAIL,
USER_FRIENDS_REQUEST,
USER_FRIENDS_REQUEST_SUCCESS,
USER_FRIENDS_REQUEST_FAIL,
USER_PROFILE_REQUEST,
};
export default UserActionTypes;
|
/*
* grunt-angular-templates
* https://github.com/ericclemmons/grunt-angular-templates
*
* Copyright (c) 2013 Eric Clemmons
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
clean: {
tests: 'tmp'
},
copy: {
tmp: {
files: [{
expand: true,
cwd: 'test/fixtures',
src: ['usemin.html', 'usemin/*'],
dest: 'tmp/'
}]
}
},
nodeunit: {
tests: ['test/*.js']
},
watch: {
tests: '<%= nodeunit.tests %>',
tasks: 'default'
},
jshint: {
all: ['Gruntfile.js', 'tasks/**/*.js', '<%= nodeunit.tests %>'],
options: {
jshintrc: '.jshintrc',
}
},
concat: {
custom_concat: {
src: 'test/fixtures/one.html',
dest: 'tmp/custom_concat_combined.js',
options: {
separator: '\n\n'
}
}
},
usemin: {
html: 'tmp/usemin.html'
},
useminPrepare: {
html: 'test/fixtures/usemin.html',
options: {
dest: 'tmp',
staging: 'tmp'
}
},
cssmin: {},
// All supported examples should be here
ngtemplates: {
// Change `angular` namespace to something else
custom_angular: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_angular.js',
options: {
angular: 'myAngular'
}
},
// Custom CommonJS bootstrapper
custom_bootstrap: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_bootstrap.js',
options: {
bootstrap: function(module, script) {
return 'module.exports = function($templateCache) {\n' + script + '\n};\n';
}
}
},
// Append dest to existing concat target
custom_concat: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_concat.js',
options: {
concat: 'custom_concat'
}
},
custom_usemin: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_concat_usemin.js',
options: {
usemin: 'usemin/all.js'
}
},
custom_usemin_not_found: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_concat_usemin_not_found.js',
options: {
usemin: 'usemin/not_found.js'
}
},
html5: {
src: ['test/fixtures/html5.html'],
dest: 'tmp/html5.js'
},
// Minify the HTML
custom_htmlmin: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_htmlmin.js',
options: {
htmlmin: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true
}
}
},
missing_htmlmin: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/missing_htmlmin.js',
options: {
htmlmin: null
}
},
// Minify the HTML, but using another tasks' settings
task_htmlmin: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/task_htmlmin.js',
options: {
htmlmin: '<%= ngtemplates.custom_htmlmin.options.htmlmin %>'
}
},
// Default `module` option to the sub-task name (`default_module`)
default_module: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/default_module.js'
},
// Customize angular module
custom_module: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_module.js',
options: {
module: 'customModule'
}
},
// Customize angular module
callback_module: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/callback_module.js',
options: {
module: function(url, options) {
return url.split('/').join('.');
},
url: function(file) {
return file.replace('.html', '');
}
}
},
// Customize template URL prefix
custom_prefix: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_prefix.js',
options: {
prefix: '/static'
}
},
// Customize template source
custom_source: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_source.js',
options: {
source: function(source, url) {
return "<!-- Template: " + url + " -->\n" + source;
}
}
},
// Module should be new & have [] defined
standalone: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/standalone.js',
options: {
standalone: true
}
},
// URLs should match path exactly
full_url: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/full_url.js'
},
// URLs should match path, sans the `cwd`
relative_url: {
cwd: 'test/fixtures',
src: ['one.html', 'two/**/*.html'],
dest: 'tmp/relative_url.js'
},
// URLs should match path, sans the `cwd`
relative_url_expand: {
expand: true,
cwd: 'test/fixtures',
src: ['three/**/*.html'],
dest: 'tmp',
ext: '.js'
},
// Customize URLs to not have an extension
custom_url: {
src: ['test/fixtures/one.html', 'test/fixtures/two/**/*.html'],
dest: 'tmp/custom_url.js',
options: {
url: function(url) {
return url.replace('.html', '');
}
}
},
// Empty file
empty_file: {
src: 'test/fixtures/empty.html',
dest: 'tmp/empty_file.js'
},
// undefined file
undefined_file: {
src: 'test/fixtures/undefined.html',
dest: 'tmp/undefined_file.js'
},
single_quotes: {
src: 'test/fixtures/one.html',
dest: 'tmp/single_quotes.js',
options: {
quotes: 'single'
}
},
linebreak: {
src: 'test/fixtures/linebreak.html',
dest: 'tmp/linebreak.js',
},
regexp: {
src: 'test/fixtures/regexp.html',
dest: 'tmp/regexp.js'
}
}
});
// Load local tasks.
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-usemin');
grunt.registerTask('default', ['jshint', 'clean', 'copy', 'useminPrepare', 'ngtemplates', 'concat', 'uglify', 'cssmin', 'usemin', 'nodeunit']);
};
|
// Define the Module
var creo = creo || {};
creo = (function (pub) {
pub.InterfaceObj = function(propsObj) {
// BASE OBJECT
this.advanced = undefined; // boolean - Whether to use the newer Creo 4 file export function.
this.depth = undefined; // integer - Image depth
this.dirname = undefined; // string - Destination directory
this.dpi = undefined; // integer - PDF Image DPI
this.driver = undefined; // string -
this.file = undefined; // string - Model name
this.filename = undefined; // string - Destination file name. May also contain a path to the file.
this.geom_flags = undefined; // string - Geometry type for the export.
this.height = undefined; // double - PDF Image height
this.new_model_type = undefined; // string - New model type
this.new_name = undefined; // string - New model name. Any extension will be stripped off and replaced with one based on new_model_type.
this.script = undefined; // string - The mapkey script to run
this.type = undefined; // string - File type
this.use_drawing_settings = undefined; // boolean - Whether to use special settings for exporting drawings
this.width = undefined; // double - PDF Image width
// VALIDATE and SET ANY REQUESTED PROPERTIES
if (typeof propsObj === "object") {
let propKeys = Object.keys(propsObj);
for (let p=0; p < propKeys.length; p++) {
var key = propKeys[p];
if (this.hasOwnProperty(key)) {
this[key] = propsObj[key];
} else {
throw("ERROR: '"+key+"' NOT A VALID OPTION!")
}
}
}
};
// Export a model to a 3D PDF file
pub.InterfaceObj.prototype.export_3dpdf = function () {
console.log('got into : pub.InterfaceObj.export_3dpdf');
let reqObj = {
command : "interface",
function : "export_3dpdf",
data : {}
};
// set the properties for the request
if (this.file) reqObj.data.file = this.file;
if (this.filename) reqObj.data.filename = this.filename;
if (this.height) reqObj.data.height = this.height;
if (this.width) reqObj.data.width = this.width;
if (this.dpi) reqObj.data.dpi = this.dpi;
if (this.dirname) reqObj.data.dirname = this.dirname;
if (this.use_drawing_settings) reqObj.data.use_drawing_settings = this.use_drawing_settings;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Export a model to a file
pub.InterfaceObj.prototype.export_file = function () {
console.log('got into : pub.InterfaceObj.export_file');
let reqObj = {
command : "interface",
function : "export_file",
data : {}
};
// set the properties for the request
if (this.type) reqObj.data.type = this.type;
if (this.file) reqObj.data.file = this.file;
if (this.filename) reqObj.data.filename = this.filename;
if (this.dirname) reqObj.data.dirname = this.dirname;
if (this.geom_flags) reqObj.data.geom_flags = this.geom_flags;
if (this.advanced) reqObj.data.advanced = this.advanced;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Export a model to an image file
pub.InterfaceObj.prototype.export_image = function () {
console.log('got into : pub.InterfaceObj.export_image');
let reqObj = {
command : "interface",
function : "export_image",
data : {}
};
// set the properties for the request
if (this.type) reqObj.data.type = this.type;
if (this.file) reqObj.data.file = this.file;
if (this.filename) reqObj.data.filename = this.filename;
if (this.height) reqObj.data.height = this.height;
if (this.width) reqObj.data.width = this.width;
if (this.dpi) reqObj.data.dpi = this.dpi;
if (this.depth) reqObj.data.depth = this.depth;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Export a model to a PDF file
pub.InterfaceObj.prototype.export_pdf = function () {
console.log('got into : pub.InterfaceObj.export_pdf');
let reqObj = {
command : "interface",
function : "export_pdf",
data : {}
};
// set the properties for the request
if (this.file) reqObj.data.file = this.file;
if (this.filename) reqObj.data.filename = this.filename;
if (this.height) reqObj.data.height = this.height;
if (this.width) reqObj.data.width = this.width;
if (this.dpi) reqObj.data.dpi = this.dpi;
if (this.dirname) reqObj.data.dirname = this.dirname;
if (this.use_drawing_settings) reqObj.data.use_drawing_settings = this.use_drawing_settings;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Export a model's program to a file
pub.InterfaceObj.prototype.export_program = function () {
console.log('got into : pub.InterfaceObj.export_program');
let reqObj = {
command : "interface",
function : "export_program",
data : {}
};
// set the properties for the request
if (this.file) reqObj.data.file = this.file;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Import a program file for a model
pub.InterfaceObj.prototype.import_program = function () {
console.log('got into : pub.InterfaceObj.import_program');
let reqObj = {
command : "interface",
function : "import_program",
data : {}
};
// set the properties for the request
if (this.dirname) reqObj.data.dirname = this.dirname;
if (this.filename) reqObj.data.filename = this.filename;
if (this.file) reqObj.data.file = this.file;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Import a file as a model
pub.InterfaceObj.prototype.import_file = function () {
console.log('got into : pub.InterfaceObj.import_file');
let reqObj = {
command : "interface",
function : "import_file",
data : {}
};
// set the properties for the request
if (this.type) reqObj.data.type = this.type;
if (this.dirname) reqObj.data.dirname = this.dirname;
if (this.filename) reqObj.data.filename = this.filename;
if (this.new_name) reqObj.data.new_name = this.new_name;
if (this.new_model_type) reqObj.data.new_model_type = this.new_model_type;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Run a Mapkey script in Creo
pub.InterfaceObj.prototype.mapkey = function () {
console.log('got into : pub.InterfaceObj.mapkey');
let reqObj = {
command : "interface",
function : "mapkey",
data : {}
};
// set the properties for the request
if (this.script) reqObj.data.script = this.script;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
// Export a model plot
pub.InterfaceObj.prototype.plot = function () {
console.log('got into : pub.InterfaceObj.plot');
let reqObj = {
command : "interface",
function : "plot",
data : {}
};
// set the properties for the request
if (this.file) reqObj.data.file = this.file;
if (this.dirname) reqObj.data.dirname = this.dirname;
if (this.driver) reqObj.data.driver = this.driver;
return creo.ajax.request(reqObj)
.then(function (respObj) {
if (respObj.data) {
return Promise.resolve(respObj.data);
} else {
return Promise.resolve(respObj);
}
})
.catch(function (err) {
console.log('Error : '+JSON.stringify(err));
return Promise.reject(err);
});
};
return pub;
}(creo || {}));
|
# NOTE(levosos): we do not use TensorFlow's API (tensorflow.python.client.device_lib.list_local_devices())
# because it causes all devices to be mapped to the current process and when using Horovod
# we receive the next error: "TensorFlow device (GPU:0) is being mapped to multiple CUDA devices".
import subprocess
def available():
return count() > 0
def count():
try:
return int(subprocess.check_output('nvidia-smi --list-gpus | wc -l', shell=True))
except subprocess.CalledProcessError:
return 0
|
# This program has been developed by students from the bachelor Computer Science at Utrecht University within the
# Software and Game project course
# ©Copyright Utrecht University Department of Information and Computing Sciences.
"""Handle deadline related feedback."""
import time
from datetime import datetime, timedelta
import assistants.moodle as moodle_api
from courses.models import Course
from lib import moodle_get_parsers as parser
from scheduler.models import (AssignmentNotificationSent,
FirstAssignmentOfCourse)
from scheduler.utils import check_if_ended, get_course_from_db
def get_deadlines_between(assignment_list, start_time, end_time):
"""
Filter the passed deadlines from the given assignment list.
:param assignment_list: List of assignments that need to be checked.
:type assignment_list: list(dict(str,int))
:param start_time: Time that the deadline needs to have passed.
:type start_time: int
:param end_time: Time that the deadline must not have passed yet.
:type end_time: int
:return: Dictionary of all the assignments with its passed deadlines.
:rtype: dict(int, (str, int))
"""
passed_deadlines = {}
for assignment in assignment_list:
assignment_id, due_date, name = parser.parse_single_assignment(assignment)
if start_time < due_date < end_time:
passed_deadlines[assignment_id] = (name, due_date)
return passed_deadlines
def get_assignments(course_id):
"""
Get all assignments in the course.
:param course_id: Id of the course that is checked.
:type course_id: int
:return: List of assignments.
:rtype: list(dict(assignment, assignment_content))
"""
json = moodle_api.get_assignments([course_id])
return parser.parse_assignment_list(json)
def check_assignment_completion(user_id, assignment_id, course_id):
"""
Check whether the assignment is completed by a user.
:param user_id: The user id to check.
:type user_id: int
:param assignment_id: The assignment id to check.
:type assignment_id: int
:param course_id: Id of the course that is checked.
:type course_id: int
:return: Whether the user has completed the assignment or not.
:rtype: bool
"""
json = moodle_api.get_assignment_status(course_id, user_id)['statuses']
assignment_list = [a for a in json if a['cmid'] == assignment_id]
if len(assignment_list) > 0:
return assignment_list[0]['state'] != 0
def get_users(course_id):
"""
Get all users enrolled in a course.
:param course_id: Id of the course that is checked.
:type course_id: int
:return: List of user ids.
:rtype: list(int)
"""
users = moodle_api.get_enrolled_users(course_id)
return parser.parse_enrolled_students(users)
def convert_time(due_date):
"""
Convert time to the due_date (in seconds) to hours and minutes.
:param due_date: The due_date in seconds from the beginning of computers (unix-time).
:type due_date: int
:return: Hours and seconds until due date.
:rtype: tuple(int, int)
"""
remaining_secs = due_date - time.time()
hours = remaining_secs / 3600
minutes = (remaining_secs % 3600) / 60
return int(hours), int(minutes)
def prep_late_warning(assignment_name):
"""
Create a late warning message.
:param assignment_name: Name of the assignment.
:type assignment_name: str
:return: A late warning message.
:rtype: str
"""
return "The deadline for " + assignment_name + " has passed."
def prep_early_warning(hours, minutes, assignment_name):
"""
Create a early warning message.
:param hours: Hours until the deadline.
:type hours: int
:param minutes: Minutes until the deadline.
:type minutes: int
:param assignment_name: Name of the assignment that approaches its deadline.
:type assignment_name: str
:return: An early warning message.
:rtype: str
"""
return f'The deadline for {assignment_name} is in {hours} hours and {minutes} minutes.'
def send_warnings(message_list):
"""
Send all users a deadline message.
:param message_list: List of messages.
:type message_list: list(tuple(int, str))
"""
moodle_api.send_bulk_different_messages(message_list)
def register_assignment_notification(assignment_id, notification_type, assignment_deadline):
"""
Create a database entry informing that the notification for an assignment has been sent
:param assignment_id: ID of assignment.
:type assignment_id: int
:param notification_type: Hardcoded type of notification, defined in scheduler.models.AssignmentNotificationSent
:type notification_type: string
:param assignment_deadline: The deadline of the related assignment.
:type assignment_deadline: datetime.datetime
"""
assignment_notification = AssignmentNotificationSent(str(assignment_id) + notification_type, assignment_id, notification_type, assignment_deadline)
assignment_notification.save()
def check_course_assignment_notifications(course_id, scheduler):
"""
Send all notifications for deadlines that have passed in this course and have not yet had a notification sent.
:param course_id: Course to check the deadlines for.
:type course_id: int
:param scheduler: SchedulerConfig object to call scheduler functions
:type scheduler: SchedulerConfig
"""
# Check if the course has passed and thus the notification job should be removed
if remove_deadline_job_if_course_ended(course_id, scheduler):
return
# get the assignment list from moodle
assignment_list = get_assignments(course_id)
# Track assignments relevant for update, these are assignments that have yet to sent their notification
assignments_to_check_on_update = []
# get the current time, plus a 1 minute buffer
current_time = datetime.timestamp(datetime.today() + timedelta(minutes=1))
time_to_deadline = get_time_before_deadline(course_id)
if time_to_deadline is None:
print('No time to deadline found in check_course_assignment_notifications for course with id: ' + str(course_id))
else:
# get enrolled users
user_id_list = get_users(course_id)
# iterate over all assignments
# send a notification if the deadline has passed or if it's time to send an early notification
for assignment in assignment_list:
assignments_to_check_on_update = send_single_assignment_notification(assignment, course_id, current_time, time_to_deadline, user_id_list, assignments_to_check_on_update)
# update this course again to reschedule itself
update_first_assignment_notification_time_of_course(course_id, scheduler, assignments_to_check_on_update)
def send_single_assignment_notification(assignment, course_id, current_time, time_to_deadline, user_id_list, assignments_to_check_on_update):
"""
Send notifications for the deadline of one assignment to all enrolled users. Only send if the deadline has passed and the message has not been sent earlier.
:param assignment: All information of a single assignment.
:type assignment: dict(str, str)
:param course_id: Course ID of course to check the deadlines for.
:type course_id: int
:param current_time: timestamp of current time
:type current_time: int
:param time_to_deadline: timestamp of time before deadline when early notification should be send ("the deadline will pass soon").
:type time_to_deadline: int
:param user_id_list: List of users of course and so of assignment
:type user_id_list: list(int)
:param assignments_to_check_on_update: List of assignments that still need messages and thus should be checked when scheduling next message time
:type assignments_to_check_on_update: [dict(str, str)]
:return: List of assignments that still need messages and thus should be checked when scheduling next message time
:rtype: [dict(str, str)]
"""
assignment_id, due_date, assignment_name = parser.parse_single_assignment(assignment)
# skip assignments that are older than one day
if due_date <= datetime.timestamp(get_datetime_of_outdated_assignments()):
return assignments_to_check_on_update
# early notification
send_assignment_notification_early_or_late(True, assignment, assignment_id, due_date, assignment_name, course_id, current_time, time_to_deadline, user_id_list, assignments_to_check_on_update)
# late notification
send_assignment_notification_early_or_late(False, assignment, assignment_id, due_date, assignment_name, course_id, current_time, time_to_deadline, user_id_list, assignments_to_check_on_update)
return assignments_to_check_on_update
def send_assignment_notification_early_or_late(assignment_type_is_early_not_late, assignment, assignment_id, due_date, assignment_name, course_id, current_time, time_to_deadline, user_id_list, assignments_to_check_on_update):
"""
Sends a 'early' or 'late' notification for the deadline of one assignment to all enrolled users. Only send if the deadline has passed and the message has not been sent earlier.
:param assignment_type_is_early_not_late: Boolean to give notification type. True is notification type is 'early' else False if 'late'.
:type assignment_type_is_early_not_late: bool
:param assignment: All information of a single assignment.
:type assignment: dict(str, str)
:param assignmen_id: ID of the assignment
:type assignmen_id: int
:param due_date: Timestamp of the assignment's deadline.
:type due_date: int
:param assignment_name: Name of the given assignment.
:type assignment: str
:param course_id: Course ID of course to check the deadlines for.
:type course_id: int
:param current_time: timestamp of current time
:type current_time: int
:param time_to_deadline: timestamp of time before deadline when early notification should be send ("the deadline will pass soon").
:type time_to_deadline: int
:param user_id_list: List of users of course and so of assignment
:type user_id_list: list(int)
:param assignments_to_check_on_update: List of assignments that still need messages and thus should be checked when scheduling next message time
:type assignments_to_check_on_update: [dict(str, str)]
"""
# get notification type as a string
notification_type = 'early' if assignment_type_is_early_not_late else 'late'
# check if an early notification has already been sent
check_already_sent = len(AssignmentNotificationSent.objects.filter(assignment_id=assignment_id, notification_type=notification_type)) > 0
notification_needs_to_be_send = False
if assignment_type_is_early_not_late:
notification_needs_to_be_send = due_date > current_time and due_date - time_to_deadline < current_time
else:
notification_needs_to_be_send = due_date <= current_time
# assignment found with an early notification to send, which has not yet been sent
if not check_already_sent:
if notification_needs_to_be_send:
# prep notification
notify_list = []
for user_id in user_id_list:
status = check_assignment_completion(user_id, assignment_id, course_id)
if not status:
message = None
# early notification type
if assignment_type_is_early_not_late:
hours, minutes = convert_time(due_date)
if hours >= 0 and minutes > 0:
message = prep_early_warning(hours, minutes, assignment_name)
# late notification type
else:
message = prep_late_warning(assignment_name)
if message is not None:
notify_list.append((user_id, message))
# sent notification
if len(notify_list) > 0:
send_warnings(notify_list)
# store that notification is sent
register_assignment_notification(assignment_id, notification_type, datetime.fromtimestamp(due_date))
elif assignment not in assignments_to_check_on_update and (not assignment_type_is_early_not_late or due_date > current_time):
assignments_to_check_on_update.append(assignment)
def update_first_assignment_notification_time_of_course(course_id, scheduler, assignments_to_check=None):
"""
Check if this course's stored first notficiation is still it's actual first notficiation that will need to be send. Else update to the assignment deadline that is earlier.
:param course_id: The ID of the course to update
:type course_id: int
:param scheduler: SchedulerConfig object to reschedule jobs
:type scheduler: SchedulerConfig
:param assignments_to_check: list of assignments to check, if None all course assignments of course will be check
:type assignments_to_check: dict(str, str)
"""
# Check if the course has passed and thus the notification job should be removed
if remove_deadline_job_if_course_ended(course_id, scheduler):
return
# get or create FirstAssignmentOfCourse to track the next schedule time
(first_notification_object, newly_created_first_notification) = get_or_create_first_notificaton_object(course_id)
time_to_deadline = get_time_before_deadline(course_id)
if time_to_deadline is None:
print('Error in deadline notification: Course object with id ' + str(course_id) + ' has no time_to_deadline in database. ')
return
# init and store the variables
planned_assignment_id = first_notification_object.assignment_id
planned_type = first_notification_object.notification_type
planned_time = None if first_notification_object.time is None else datetime.timestamp(first_notification_object.time)
if (planned_time is not None and planned_time < datetime.timestamp(datetime.today() - timedelta(minutes=1))) or assignments_to_check is not None:
planned_time = None
first_notification_object.time = None
# get the assignment list from moodle
assignment_list = get_assignments(course_id) if (assignments_to_check is None) else assignments_to_check
# check if the first planned notification is up to date
for assignment in assignment_list:
(planned_assignment_id, planned_type, planned_time) = update_first_notification_check_single_assignment(assignment, time_to_deadline, planned_assignment_id, planned_type, planned_time)
# check if the first assignment of this course has been updated
updated = planned_time is not None and first_notification_object.time != datetime.fromtimestamp(planned_time)
# if the first deadline notification of this course has been updated, reschedule this course
if(updated or newly_created_first_notification):
# save the found variables and update the table
first_notification_object = update_first_notification_object(first_notification_object, planned_assignment_id, planned_type, planned_time)
if(updated):
scheduler.reschedule_job(str(course_id) + 'assignment_check', 'date', {'run_date': datetime.fromtimestamp(planned_time)}, datetime.fromtimestamp(planned_time))
def update_first_notification_check_single_assignment(assignment, time_to_deadline, planned_assignment_id, planned_type, planned_time):
"""
Check for a single assignment if its deadlines are earlier than the planned deadline. If so, set the new deadline as planned deadline. This planned time will be the earliest that notification will be send for deadlines.
:param assignment: All information of a single assignment.
:type assignment: dict(str, str)
:param time_to_deadline: timestamp of time before deadline when early notification should be send ("the deadline will pass soon").
:type time_to_deadline: int
:param planned_assignment_id: ID of assigment
:type planned_assignment_id: int
:param planned_type: Type of planned notification ('early' or 'late')
:type planned_type: str
:param planned_time: Timestamp of planned time
:type planned_time: int
:return: Tuple containing updated values for (planned_assignment_id, planned_type, planned_time)
:rtype: (int, str, int)
"""
assignment_id, due_date, assignment_name = parser.parse_single_assignment(assignment)
# notifications at the planned time can be skipped, notifcations older than one day can also be skipped
if due_date is planned_time or due_date < datetime.timestamp(datetime.today() - timedelta(days=1)):
return (planned_assignment_id, planned_type, planned_time)
# check if an early notification has already been sent
check_already_sent_early = len(AssignmentNotificationSent.objects.filter(assignment_id=assignment_id, notification_type='early')) > 0
# assignment with earlier 'early' notification found, of which the deadline has not passed yet, which has not yet been sent, which is not already planned
if (planned_time is None or (due_date - time_to_deadline < planned_time)) and due_date > datetime.timestamp(datetime.today()) and not check_already_sent_early and not (planned_assignment_id == assignment_id and planned_type == 'early'):
planned_assignment_id = assignment_id
planned_type = 'early'
planned_time = due_date - time_to_deadline
else:
# check if a late notification has already been sent
check_already_sent_late = len(AssignmentNotificationSent.objects.filter(assignment_id=assignment_id, notification_type='late')) > 0
# assignment with earlier 'late' notification found, which has not yet been sent and which is not already planned
if (planned_time is None or due_date < planned_time) and not check_already_sent_late and not (planned_assignment_id == assignment_id and planned_type == 'late'):
planned_assignment_id = assignment_id
planned_type = 'late'
planned_time = due_date
return (planned_assignment_id, planned_type, planned_time)
def update_first_assignment_notification_time_all_courses(scheduler):
"""
Update the stored first assignment of all courses, so they can be scheduled appropriately.
:param scheduler: SchedulerConfig object to reschedule jobs
:type scheduler: SchedulerConfig
"""
course_list = Course.objects.filter(deadline=True)
for course_object in course_list:
# Update when notifications need to be send again
update_first_assignment_notification_time_of_course(course_object.courseId, scheduler)
remove_outdated_db_assignment_sent_entries()
def remove_deadline_job_if_course_ended(course_id, scheduler):
"""
Removes the deadline notification job if the given course has ended.
:param course_id: The ID of the course to check.
:type course_id: int
:param scheduler: SchedulerConfig object to reschedule jobs
:type scheduler: SchedulerConfig
:return: If the job needed to be removed.
:rtype: bool
"""
# Check if the course has passed and thus the notification job should be removed
if check_if_ended(course_id):
scheduler.remove_deadline_notification(course_id)
print('Removing deadline notificaiton job since course ' + str(course_id) + ' has passed. ')
return True
return False
def remove_outdated_db_assignment_sent_entries():
"""
Removes AssignmentNotificationSent entries that are not relevant anymore because the deadline of the related assignment has passed a while ago.
Therefore notifications will never be send regardless of if it has been sent or still needed to be sent.
"""
all_assignment_sent_entries = AssignmentNotificationSent.objects.all()
redundant_deadline = get_datetime_of_outdated_assignments()
for entry in all_assignment_sent_entries:
if entry.time < redundant_deadline:
entry.delete()
def get_datetime_of_outdated_assignments():
"""
Returns the current date minus one day. From that point assignment notifications should not be send if the deadline was earlier.
:return: date minus one day.
:rtype: datetime.datetime
"""
return datetime.today() - timedelta(days=1)
def get_or_create_first_notificaton_object(course_id):
"""
Gets the FirstAssignmentOfCourse object from the database.
If it does not exist for the requested course, it will be created.
:param course_id: ID of the course of the course object to retrieve from the database.
:type course_id: int
:return: Tuple containing the requested FirstAssignmentOfCourse and a boolean that is True if the FirstAssignmentOfCourse was created in the method.
:rtype: (FirstAssignmentOfCourse, bool)
"""
first_notification_object = get_first_notification_object(course_id, False)
object_was_created = first_notification_object is None
if first_notification_object is None:
first_notification_object = FirstAssignmentOfCourse(course_id=course_id,
assignment_id=-1,
notification_type='late',
time=None)
return (first_notification_object, object_was_created)
def update_first_notification_object(first_notification_object, assignment_id, notifcation_type, time):
"""
Gets the FirstAssignmentOfCourse object from the database.
If it does not exist for the requested course, it will be created.
:param first_notification_object: FirstAssignmentOfCourse object that needs to be updated.
:type first_notification_object: FirstAssignmentOfCourse
:param assignmen_id: ID of the assignment the notification is for.
:type assignmen_id: int
:param notifcation_type: Type of planned notification ('early' or 'late').
:type notifcation_type: str
:param time: Timestamp of when the notification will need to be send.
:type time: int
:return: FirstAssignmentOfCourse object that is updated.
:rtype: FirstAssignmentOfCourse
"""
first_notification_object.assignment_id = assignment_id
first_notification_object.notification_type = notifcation_type
first_notification_object.time = None if time is None else datetime.fromtimestamp(time)
first_notification_object.save()
return first_notification_object
def get_time_before_deadline(course_id):
"""Returns the timestamp of time before deadline when early notification should be send ("the deadline will pass soon") while error handling.
:param course_id: ID of the course of the course object to retrieve from the database.
:type course_id: int
:return: Timestamp of length of notification time before deadline
:rtype: int
"""
course = get_course_from_db(course_id)
if course is not None:
return course.hours_before * 3600
else:
return None
def get_first_notification_object(course_id, error_on_not_found=True):
"""Returns the timestamp of time before deadline when early notification should be send ("the deadline will pass soon") while error handling.
:param course_id: ID of the course of the course object to retrieve from the database.
:type course_id: int
:param error_on_not_found: True if an exception needs to be thrown when requested object is not found
:type error_on_not_found: bool
:return: Requested FirstAssignmentOfCourse object
:rtype: scheduler.models.FirstAssignmentOfCourse
"""
try:
return FirstAssignmentOfCourse.objects.get(course_id=course_id)
except FirstAssignmentOfCourse.DoesNotExist:
if error_on_not_found:
print("Course: " + str(course_id) + " could not be found in FirstAssignmentOfCourse when searched in get_first_notification_object")
return None
except FirstAssignmentOfCourse.MultipleObjectsReturned:
print("Course: " + str(course_id) + " has multiple entries in FirstAssignmentOfCourse when searched in get_first_notification_object")
return None
|
// Copyright (c) 2012-2015, Matt Godbolt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
CodeMirror.defineMode("asm", function () {
function tokenString(quote) {
return function (stream) {
var escaped = false, next, end = false;
while ((next = stream.next()) !== null) {
if (next == quote && !escaped) {
end = true;
break;
}
escaped = !escaped && next == "\\";
}
return "string";
};
}
return {
token: function (stream) {
if (stream.match(/^.+:$/)) {
return "variable-2";
}
if (stream.sol() && stream.match(/^\s*\.\w+/)) {
return "header";
}
if (stream.sol() && stream.match(/^\s\w+/)) {
return "keyword";
}
if (stream.eatSpace()) return null;
var ch = stream.next();
if (ch == '"' || ch == "'") {
return tokenString(ch)(stream);
}
if (/[\[\]{}\(\),;\:]/.test(ch)) return null;
if (/[\d$]/.test(ch) || (ch == '-' && stream.peek().match(/[0-9]/))) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == '%') {
stream.eatWhile(/\w+/);
return "variable-3";
}
if (ch == '#') {
stream.eatWhile(/.*/);
return "comment";
}
stream.eatWhile(/[\w\$_]/);
return "word";
}
};
});
CodeMirror.defineMIME("text/x-asm", "asm");
|
import { createSelector } from 'reselect'
import { getEvents } from 'store/selectors/event'
import { getOracles } from 'store/selectors/oracle'
import { getEventDescriptions } from 'store/selectors/eventDescription'
import { eventSharesSelector, enhanceShares } from 'store/selectors/marketShares'
import { getCurrentAccount } from 'integrations/store/selectors'
import { hexWithPrefix } from 'utils/helpers'
const eventMarketSelector = marketAddress => (state) => {
if (!state.entities) {
return {}
}
if (!state.entities.markets) {
return {}
}
if (!state.entities.markets[marketAddress]) {
return {}
}
const market = state.entities.markets[marketAddress]
const eventAddress = hexWithPrefix(market.event)
return { [eventAddress]: market }
}
const getMarketShares = marketAddress =>
createSelector(
getOracles,
getEvents,
getEventDescriptions,
eventMarketSelector(marketAddress),
eventSharesSelector,
getCurrentAccount,
enhanceShares,
)
export default getMarketShares
|
"""
Test whether rate limit leaky bucket controls number of simultaneous incoming requests
Rewrite:
spec/functional_specs/policies/rate_limit/leaky_bucket/
liquid/rate_limit_bucket_liquid_service_false_spec.rb
liquid/rate_limit_bucket_liquid_service_true_spec.rb
liquid/rate_limit_bucket_matches_false_spec.rb
liquid/rate_limit_bucket_matches_true_spec.rb
plain_text/false_condition/rate_limit_bucket_global_false_spec.rb
false_condition/rate_limit_bucket_service_false_spec.rb
false_condition/rate_limit_multiple_bucket_global_false_spec.rb
false_condition/rate_limit_multiple_bucket_service_false_spec.rb
false_condition/rate_limit_multiple_prepend_bucket_global_false_spec.rb
true_condition/rate_limit_bucket_global_true_spec.rb
true_condition/rate_limit_bucket_service_true_spec.rb
true_condition/rate_limit_multiple_bucket_global_true_spec.rb
true_condition/rate_limit_multiple_bucket_service_true_spec.rb
true_condition/rate_limit_multiple_prepend_bucket_global_true_spec.rb
"""
import asyncio
from concurrent.futures.thread import ThreadPoolExecutor
import backoff
import pytest
import pytest_cases
from pytest_cases import parametrize_with_cases
from testsuite import rawobj
from testsuite.capabilities import Capability
from testsuite.tests.apicast.policy.rate_limit.leaky_bucket import config_cases
from testsuite.utils import blame
TOTAL_REQUESTS = 6
pytestmark = pytest.mark.flaky
@pytest_cases.fixture
def service(service_proxy_settings, custom_service, request):
"""Service configured with config"""
return custom_service({"name": blame(request, "svc")}, service_proxy_settings)
@pytest_cases.fixture
def service2(service_proxy_settings, custom_service, request):
"""Service configured with parametrized config"""
return custom_service({"name": blame(request, "svc")}, service_proxy_settings)
@pytest_cases.fixture
@parametrize_with_cases('case_data', cases=config_cases)
def config(case_data, service, service2):
"""Configuration for rate limit policy"""
policy_config, apply_rate_limit, scope = case_data
service.proxy.list().policies.append(policy_config)
service2.proxy.list().policies.append(policy_config)
# When scope=service we want 2 application for same service
if scope == 'service':
return apply_rate_limit, service
# when scope=global we want 1 application for each service
return apply_rate_limit, service2
@pytest_cases.fixture
def application(service, custom_app_plan, custom_application, request):
"""First application bound to the account and service_plus"""
plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), service)
return custom_application(rawobj.Application(blame(request, "app"), plan))
@pytest_cases.fixture
def application2(config, custom_app_plan, custom_application, request):
"""Second application bound to the account and service_plus"""
svc = config[1]
plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), svc)
return custom_application(rawobj.Application(blame(request, "app"), plan))
@pytest_cases.fixture
def client(application):
"""api client for application"""
client = application.api_client()
yield client
client.close()
@pytest_cases.fixture
def client2(application2):
"""api client for application2"""
client = application2.api_client()
yield client
client.close()
@backoff.on_predicate(backoff.fibo, lambda x: x[0], 8, jitter=None)
def retry_requests(client, client2, rate_limit_applied):
"""
Retries requests to both clients
If rate limit policy configuration was applied it will retry requests until at least one request was rejected
otherwise it will retry requests untill each request was successful
:param client: client of the first application
:param client2: client of the second application
:param rate_limit_applied: true if the condition will be true, false otherwise
:return: tuple: 1st: boolean if this function should be repeated, false otherwise
2nd: list of status codes
"""
loop = asyncio.get_event_loop()
responses = []
with ThreadPoolExecutor(max_workers=TOTAL_REQUESTS + 1) as pool:
futures = []
for _ in range(TOTAL_REQUESTS // 2):
futures.append(loop.run_in_executor(pool, client.get, "/get"))
futures.append(loop.run_in_executor(pool, client2.get, "/get"))
responses = loop.run_until_complete(asyncio.gather(*futures))
status_codes = [response.status_code for response in responses]
if rate_limit_applied:
return status_codes.count(429) == 0, status_codes
return status_codes.count(200) == 6, status_codes
@pytest.mark.required_capabilities(Capability.SAME_CLUSTER)
def test_leaky_bucket(client, client2, config):
"""
Test rate limit policy with leaky bucket limiters configurations.
This test is the same for the different configuration which are specified in the config_cases.py file.
Based on the config[0] value, this test method tests:
- True: the rate limit was applied to requests (at least one request should be rejected)
- False: the rate limit was not applied to requests (every requests should be successful)
:param client: api_client for the first application
:param client2: api_client for the second application
:param config: configuration of the actual test
"""
status_codes = retry_requests(client, client2, config[0])[1]
successful = status_codes.count(200)
if config[0]: # is the condition of the leaky bucket limiter true?
assert successful >= 2 # at least 2 requests should be successful
assert status_codes.count(429) >= 1 # at least 1 requests should be rejected
else:
assert successful == TOTAL_REQUESTS # all responses should be 200
|
const desmenu = ( prefijo , pushname ) => {
volver '
* Comandos De Descargas ✅ *
══════════════
*AUDIO*
$ { prefix } play2
Una alternativa por si * play llego a su limite de canciones
$ { prefix } jugar
Coloca el nombre de la cancion, o el link del video YT
$ { prefix } reproducir https://www.youtube.com/xxxxxxxxxxxxx
══════════════
* COMUNICADO *
* ytmp4 y * ytmp3 estan en mantenimiento, muy pronto sacare una actualización de esos comandos mas renovados :)
══════════════
_ * play y * play2 tiene un limite de 2000 canciones en el server, si llega a su limite se restablecera dentro de 24 horas_
ву ѕнαη∂υу`
}
Exportaciones . desmenu = desmenu
|
import { RoomType } from '@rocket.chat/apps-engine/definition/rooms';
import { Rooms, Users, LivechatVisitors, LivechatDepartment } from '../../../models';
import { transformMappedData } from '../../lib/misc/transformMappedData';
export class AppRoomsConverter {
constructor(orch) {
this.orch = orch;
}
convertById(roomId) {
const room = Rooms.findOneById(roomId);
return this.convertRoom(room);
}
convertByName(roomName) {
const room = Rooms.findOneByName(roomName);
return this.convertRoom(room);
}
convertAppRoom(room) {
if (!room) {
return undefined;
}
let u;
if (room.creator) {
const creator = Users.findOneById(room.creator.id);
u = {
_id: creator._id,
username: creator.username,
};
}
let v;
if (room.visitor) {
const visitor = LivechatVisitors.findOneById(room.visitor.id);
v = {
_id: visitor._id,
username: visitor.username,
token: visitor.token,
};
}
let departmentId;
if (room.department) {
const department = LivechatDepartment.findOneById(room.department.id);
departmentId = department._id;
}
let servedBy;
if (room.servedBy) {
const user = Users.findOneById(room.servedBy.id);
servedBy = {
_id: user._id,
username: user.username,
};
}
let closedBy;
if (room.closedBy) {
const user = Users.findOneById(room.closedBy.id);
closedBy = {
_id: user._id,
username: user.username,
};
}
const newRoom = {
...room.id && { _id: room.id },
fname: room.displayName,
name: room.slugifiedName,
t: room.type,
u,
v,
departmentId,
servedBy,
closedBy,
members: room.members,
uids: room.userIds,
default: typeof room.isDefault === 'undefined' ? false : room.isDefault,
ro: typeof room.isReadOnly === 'undefined' ? false : room.isReadOnly,
sysMes: typeof room.displaySystemMessages === 'undefined' ? true : room.displaySystemMessages,
waitingResponse: typeof room.isWaitingResponse === 'undefined' ? undefined : !!room.isWaitingResponse,
open: typeof room.isOpen === 'undefined' ? undefined : !!room.isOpen,
msgs: room.messageCount || 0,
ts: room.createdAt,
_updatedAt: room.updatedAt,
closedAt: room.closedAt,
lm: room.lastModifiedAt,
customFields: room.customFields,
livechatData: room.livechatData,
prid: typeof room.parentRoom === 'undefined' ? undefined : room.parentRoom.id,
//makhn 24/12/2020
//makhn 28
//isTask: typeof room.parentRoom === 'undefined' ? undefined : room.parentRoom.id,
...room._USERNAMES && { _USERNAMES: room._USERNAMES },
};
return Object.assign(newRoom, room._unmappedProperties_);
}
convertRoom(room) {
if (!room) {
return undefined;
}
const map = {
id: '_id',
displayName: 'fname',
slugifiedName: 'name',
members: 'members',
userIds: 'uids',
messageCount: 'msgs',
createdAt: 'ts',
updatedAt: '_updatedAt',
closedAt: 'closedAt',
lastModifiedAt: 'lm',
customFields: 'customFields',
livechatData: 'livechatData',
isWaitingResponse: 'waitingResponse',
isOpen: 'open',
_USERNAMES: '_USERNAMES',
isDefault: (room) => {
const result = !!room.default;
delete room.default;
return result;
},
isReadOnly: (room) => {
const result = !!room.ro;
delete room.ro;
return result;
},
displaySystemMessages: (room) => {
const { sysMes } = room;
if (typeof sysMes === 'undefined') {
return true;
}
delete room.sysMes;
return sysMes;
},
type: (room) => {
const result = this._convertTypeToApp(room.t);
delete room.t;
return result;
},
creator: (room) => {
const { u } = room;
if (!u) {
return undefined;
}
delete room.u;
return this.orch.getConverters().get('users').convertById(u._id);
},
visitor: (room) => {
const { v } = room;
if (!v) {
return undefined;
}
delete room.v;
return this.orch.getConverters().get('visitors').convertById(v._id);
},
department: (room) => {
const { departmentId } = room;
if (!departmentId) {
return undefined;
}
delete room.departmentId;
return this.orch.getConverters().get('departments').convertById(departmentId);
},
servedBy: (room) => {
const { servedBy } = room;
if (!servedBy) {
return undefined;
}
delete room.servedBy;
return this.orch.getConverters().get('users').convertById(servedBy._id);
},
responseBy: (room) => {
const { responseBy } = room;
if (!responseBy) {
return undefined;
}
delete room.responseBy;
return this.orch.getConverters().get('users').convertById(responseBy._id);
},
parentRoom: (room) => {
const { prid } = room;
if (!prid) {
return undefined;
}
delete room.prid;
return this.orch.getConverters().get('rooms').convertById(prid);
},
};
return transformMappedData(room, map);
}
_convertTypeToApp(typeChar) {
switch (typeChar) {
case 'c':
return RoomType.CHANNEL;
case 'p':
return RoomType.PRIVATE_GROUP;
case 'd':
return RoomType.DIRECT_MESSAGE;
case 'l':
return RoomType.LIVE_CHAT;
default:
return typeChar;
}
}
}
|
const defaultConfig = require('./defaultConfig');
var argv = require('yargs/yargs')(process.argv.slice(2))
.option('directory', {
alias: 'd',
description: 'Provide a path to your build directory.',
default: defaultConfig.directory,
type: 'string',
})
.option('config', {
alias: 'c',
description: 'Provide a path to your config file.',
default: 'compress-cra.json',
type: 'string',
})
.help()
.alias('help', 'h').argv;
module.exports = argv;
|
""" Spider for parsing katastr nemovitosti.
Output is owners of the units in the building.
"""
import argparse
import json
import urllib.parse
import urllib3
from typing import Dict, List
import scrapy
import scrapy.http as http
from scrapy.crawler import CrawlerProcess
def parse_owners(response: http.TextResponse) -> List[Dict]:
rows = response.css("table.vlastnici tr")
owners: List[Dict[str, str]] = []
person_index = 0
for row in rows[1:]:
if row.css(".partnerSJM"):
person = row.xpath(".//i/text()").get()
if person_index == 0:
owners[-1]["person1"] = person
else:
owners[-1]["person2"] = person
person_index += 1
else:
person_index = 0
name = row.xpath("td[1]/text()").get()
if not name:
# we are reading another header - different part of the table
break
fraction_el = row.css(".right").xpath("text()").get()
owners.append({"name": name, "fraction": fraction_el or "1"})
return owners
class KatastrSpider(scrapy.Spider):
name: str = "katastr" # type: ignore
start_urls = ["https://nahlizenidokn.cuzk.cz/VyberBudovu.aspx?typ=Jednotka"]
download_delay = 1.0
allowed_domains = ["nahlizenidokn.cuzk.cz"]
def __init__(self, region: str, street: str, home_number: str):
self.region = region
self.street = street
self.home_number = home_number
def parse(self, response: http.TextResponse) -> http.FormRequest:
yield scrapy.FormRequest.from_response(
response,
formdata={
"ctl00$bodyPlaceHolder$vyberObec$txtObec": self.region,
"ctl00$bodyPlaceHolder$vyberObec$btnObec": "Vyhledat",
},
callback=self.parse_address,
)
def parse_address(self, response: http.TextResponse) -> http.FormRequest:
yield scrapy.FormRequest.from_response(
response,
formdata={
"ctl00$bodyPlaceHolder$listTypBudovy": "1",
"ctl00$bodyPlaceHolder$txtBudova": "",
"ctl00$bodyPlaceHolder$txtUlice": self.street,
"ctl00$bodyPlaceHolder$txtCisloDomovni": self.home_number,
"ctl00$bodyPlaceHolder$txtCisloOr": "",
"ctl00$bodyPlaceHolder$txtJednotka": "",
"ctl00$bodyPlaceHolder$btnVyhledat": "Vyhledat",
"ctl00$bodyPlaceHolder$tabPanelIndex": "1",
},
callback=self.parse_building,
)
def parse_building(self, response: http.TextResponse) -> http.FormRequest:
for link in response.xpath("//table[@summary='Nalezené jednotky']//a"):
yield scrapy.Request(
response.urljoin(link.attrib["href"]), callback=self.parse_flat
)
def parse_flat(self, response: http.TextResponse) -> http.FormRequest:
table = response.xpath("//table[@summary='Atributy jednotky']")
yield {
"name": table.xpath("tr[1]/td[2]/strong/text()").get(),
"fraction": table.xpath("tr[last()]/td[2]/text()").get(),
"owners": parse_owners(response),
}
def download_building(
file_name: str, street: str, home_number: str, region: str
) -> None:
process = CrawlerProcess(settings={"FEED_URI": file_name, "FEED_FORMAT": "json"})
pool = urllib3.PoolManager()
response = pool.request(
"GET",
"https://nahlizenidokn.cuzk.cz/AutoCompleteObecHandler.ashx?{}".format(
urllib.parse.urlencode({"query": region})
),
)
regions = json.loads(response.data)["suggestions"]
if len(regions) != 1:
raise ValueError("Different number of regions then 1: {}".format(regions))
full_region = regions[0]
process.crawl(
KatastrSpider, region=full_region, street=street, home_number=home_number
)
process.start()
def main() -> None:
parser = argparse.ArgumentParser(
description="Download flat information from katasrt nemovitosti"
)
parser.add_argument("--region", required=True, help="Name of region e.g. Praha")
parser.add_argument(
"--street", required=True, help="Exact name of the street with diacritics"
)
parser.add_argument("--home_number", required=True, help="Home number")
parser.add_argument("-o", "--output", help="Output filename", default="flats.json")
args = parser.parse_args()
download_building(
args.output,
region=args.region,
street=args.street,
home_number=args.home_number,
)
if __name__ == "__main__":
main()
|
var path = require('path');
var express = require('express');
var handlebars = require('express-handlebars');
var session = require('express-session');
var flash = require('express-flash');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var passport = require('passport');
var rest = require('./helpers/rest');
var dbConfig = require('./config/db');
require('mongoose').connect(dbConfig.url);
var app = express();
var server = require('http').Server(app);
var io = require('./modules/io')(server);
app.engine('hbs', handlebars({
extname: 'hbs',
defaultLayout: 'main',
helpers: require('./helpers/handlebars')
}));
app.set('view engine', 'hbs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser('topkek'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ resave: false, saveUninitialized: true, secret: 'topkek' }));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
require('./modules/localAuth')(app, passport);
require('./modules/socialAuth')(app, passport);
app.use('/', require('./routes'))
app.use('/api/v1', require('./routes/api'));
module.exports = server;
|
OC.L10N.register(
"gallery",
{
"Gallery" : "Галерея",
"There was a problem reading files from this album" : "Проблема при чтении файлов из этого альбома",
"Aborting preview. Could not find the file" : "Предпросмотр отменен. Не удалось найти файл",
"Could not move \"{file}\", target exists" : "Невозможно переместить «{file}», файл уже существует в каталоге назначения",
"Could not move \"{file}\"" : "Невозможно переместить «{file}»",
"No compatible server found at {remote}" : "Совместимый сервер на {remote} не найден",
"Invalid server url" : "Неверный URL-адрес сервера",
"Could not load the description" : "Не удалось загрузить описание",
"Could not load the description: " : "Не удалось загрузить описание:",
"Copyright" : "Авторские права защищены",
"Could not load the copyright notice: " : "Не удалось загрузить уведомление об авторских правах:",
"Copyright notice" : "Уведомление об авторских правах",
"Link to copyright document" : "Ссылка на документ об авторских правах",
"This application may not work properly on your browser." : "Это приложение может некорректно работать в вашем браузере.",
"For an improved experience, please install one of the following alternatives" : "Для наилучшего результата, пожалуйста, установите одну из следующих альтернатив",
"Your browser is not supported!" : "Используемый браузер не поддерживается.",
"please install one of the following alternatives" : "используйте один из следующих предложенных вариантов:",
"Album cannot be shown" : "Этот альбом не может быть отображен",
"No media files found" : "Медиафайлы не найдены",
"Upload pictures in the Files app to display them here" : "Загрузите изображения в приложении «Файлы» для их просмотра",
"Upload new files via drag and drop or by using the [+] button above" : "Перетащите файлы или используйте кнопку [ + ] выше",
"Configuration error" : "Ошибка конфигурации",
"Hide Album" : "Скрыть альбом",
"Could not hide album" : "Не удалось скрыть альбом",
"Error loading slideshow template" : "Ошибка при загрузке шаблона слайд-шоу",
"<strong>Error!</strong> Could not generate a preview of this file.<br>Please go to the next slide while we remove this image from the slideshow" : "<strong>Ошибка!</strong> Не удалось создать предварительный просмотр этого файла.<br>Это изображение будет исключено из показа слайдов, перейдите к следующему",
"Next" : "Следующий",
"Play" : "Проиграть",
"Pause" : "Пауза",
"Previous" : "Предыдущий",
"Close" : "Закрыть",
"Download" : "Скачать",
"Toggle background" : "Переключить фон",
"Delete" : "Удалить",
"Share" : "Открыть доступ",
"Could not create file \"{file}\" because it already exists" : "Невозможно создать файл «{file}», он уже существует",
"Could not create file \"{file}\"" : "Невозможно создать файл «{file}»",
"\"{name}\" is an invalid file name." : "«{name}» — недопустимое имя файла.",
"File name cannot be empty." : "Имя файла не может быть пустым.",
"\"{name}\" is not an allowed filetype" : "«{name}» - недопустимый тип файла.",
"Upload" : "Передать на сервер",
"Error" : "Ошибка",
"Error while sharing" : "При открытии общего доступа произошла ошибка",
"Error while unsharing" : "При закрытии доступа произошла ошибка",
"Error while changing permissions" : "При изменении прав доступа произошла ошибка",
"Shared with you and the group {group} by {owner}" : "{owner} поделился с вами и группой {group} ",
"Shared with you by {owner}" : "С вами поделился {owner} ",
"Share with users or groups …" : "Поделиться с пользователями или группами…",
"Share with users, groups or remote users …" : "Поделиться с пользователями, группами или удаленными пользователями…",
"Share link" : "Поделиться ссылкой",
"The public link will expire no later than {days} days after it is created" : "Срок действия публичной ссылки истекает не позже чем через {days} дней после её создания",
"Link" : "Ссылка",
"Password protect" : "Защитить паролем",
"Password" : "Пароль",
"Choose a password for the public link" : "Укажите пароль для публичной ссылки",
"Allow editing" : "Разрешить редактирование",
"Email link to person" : "Отправить ссылку по электронной почте",
"Send" : "Отправить",
"Set expiration date" : "Установить срок действия",
"Expiration" : "Срок действия",
"Expiration date" : "Срок действия",
"This list is maybe truncated - please refine your search term to see more results." : "Этот список может быть показан не полностью - уточните запрос что бы просмотреть больше результатов.",
"No users or groups found for {search}" : "Не найдено пользователей или групп по запросу {search}",
"No users found for {search}" : "Не найдено пользователей по запросу {search}",
"An error occurred (\"{message}\"). Please try again" : "Произошла ошибка («{message}»). Попробуйте ещё раз",
"An error occurred. Please try again" : "Произошла ошибка. Попробуйте ещё раз",
"Adding user..." : "Добавляем пользователя…",
"group" : "группа",
"remote" : "на другом сервере",
"Resharing is not allowed" : "Повторное открытие доступа запрещено",
"Error while retrieving shares" : "Ошибка получения списка общих ресурсов",
"Unshare" : "Закрыть доступ",
"notify by email" : "уведомить по эл. почте",
"can share" : "можно поделиться",
"can edit" : "можно редактировать",
"access control" : "контроль доступа",
"create" : "создать",
"change" : "изменить",
"delete" : "удалить",
"Password protected" : "Защищено паролем",
"Error unsetting expiration date" : "Ошибка при отмене срока доступа",
"Error setting expiration date" : "Ошибка при установке срока доступа",
"Sending…" : "Отправка…",
"Email sent" : "Письмо отправлено",
"Warning" : "Предупреждение",
"shared by %s" : "поделился %s",
"Direct link" : "Прямая ссылка",
"Add to your Nextcloud" : "Добавить в свой Nextcloud",
"Media gallery for Nextcloud" : "Медиа-галерея для Nextcloud",
"Media gallery for Nextcloud with the following features:\n\n\t\t- Support for large selection of media types (depending on server setup)\n\n\t\t- Upload and organise images and albums straight from the app\n\n\t\t- Large, zoomable previews which can be shown in fullscreen mode\n\n\t\t- Sort images by name or date\n\n\t\t- Per album design, description and copyright statement\n\n\t\t- A la carte features (external shares, browser svg rendering, etc.)\n\n\t\t- Image download straight from the slideshow or the gallery\n\n\t\t- Switch to Gallery from any folder in files and vice-versa\n\n\t\t- Ignore folders containing a \".nomedia\" file\n\n\t\t- Browser rendering of SVG images (disabled by default)\n\n\t\t- Native SVG support\n\n\t\t- Mobile support\n\n\t\tProvides a dedicated view of all images in a grid, adds image viewing capabilities to the\n\t\tfiles app and adds a gallery view to public links.\n\t\tCompatible with Firefox, Chrome and Internet Explorer 11" : "Медиа-галерея для Nextcloud поддерживает следующие функции:\n\n- Поддержка большого количества типов носителей (в зависимости от настройки сервера)\n\n- Загрузка и упорядочивание изображений и альбомов прямо из приложения\n\n- Большие, масштабируемые предварительные просмотры, которые могут отображаться в полноэкранном режиме\n\n- Сортировка изображений по имени или дате\n\n- Дизайн, описание и авторское право на каждый альбом\n\n- Особенности a la carte (внешние акции, рендеринг svg браузера и т. Д.)\n\n- Загрузка изображения прямо из слайд-шоу или галереи\n\n- Переключиться в Галерею из любой папки в Файлах и наоборот\n\n- Игнорировать папки, содержащие файл «.nomedia»\n\n- Отображение браузера изображений SVG (по умолчанию отключено)\n\n- Поддержка родных SVG\n\n- Мобильная поддержка\n\nПредоставляет выделенный вид всех изображений в сетке, добавляет возможности просмотра изображений в приложении Файлы и добавляет галерею в общие ссылки.\nСовместимость с Firefox, Chrome и Internet Explorer 11",
"This share is password-protected" : "Общий ресурс защищен паролем",
"The password is wrong. Try again." : "Неверный пароль. Попробуйте еще раз.",
"Sort by name" : "Сортировать по имени",
"Sort by date" : "Сортировать по дате",
"Cancel upload" : "Отменить загрузку",
"Album information" : "Сведения об альбоме",
"File list" : "Список файлов",
"Sorry, this file could not be found." : "К сожалению, файл не найден.",
"Reasons might be:" : "Причиной может быть:",
"the wrong file ID was provided" : "предоставлен ошибочный ID файла",
"the file was removed" : "файл был удален",
"the file is corrupt" : "файл поврежден",
"the encryption key is missing" : "отсутствует ключ шифрования",
"Here is the error message returned by the server: " : "Вот сообщение об ошибке, возвращенное сервером:",
"For more information, please contact your friendly Nextcloud administrator." : "Для получения более подробной информации, пожалуйста, обратитесь к администратору вашего Nextcloud.",
"Sorry, but the server could not fulfill your request." : "К сожалению, сервер не смог выполнить ваш запрос.",
"Possible reasons for the problem:" : "Возможные причины проблемы:",
"a conflicting app was installed" : "было установлено конфликтующее приложение",
"a required component is missing or was disconnected" : "необходимый компонент отсутствует или был отключен",
"the filesystem is not readable" : "файловая система нечитаема",
"Sorry, this link doesn't seem to work anymore." : "К сожалению, эта ссылка более недоступна.",
"the item was removed" : "объект был удалён",
"the link has expired" : "истёк срок действия ссылки",
"sharing is disabled" : "закрыт общий доступ",
"For more information, please ask the person who has sent you this link." : "Для получения дополнительной информации, свяжитесь с тем, кто отправил вам эту ссылку.",
"Picture view" : "Просмотр изображения",
"New" : "Новый",
"Share with people on other servers using their Federated Cloud ID [email protected]/cloud" : "Предоставить доступ людям на других серверах, используя их идентификатор в федерации облачных хранилищ [email protected]/cloud",
"An error occured. Please try again" : "Произошла ошибка. Попробуйте ещё раз",
"Sending ..." : "Отправляется…"
},
"nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);");
|
from struct import pack, unpack
data = bytes()
key, value, index = 'tagon', 'underline', '1.0'
data += pack('', key, value, index)
print(data)
|
// source: google/ads/googleads/v3/common/text_label.proto
/**
* @fileoverview
* @enhanceable
* @suppress {messageConventions} JS Compiler reports an error if a variable or
* field starts with 'MSG_' and isn't a translatable message.
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
var jspb = require('google-protobuf');
var goog = jspb;
var global = Function('return this')();
var google_protobuf_wrappers_pb = require('google-protobuf/google/protobuf/wrappers_pb.js');
goog.object.extend(proto, google_protobuf_wrappers_pb);
var google_api_annotations_pb = require('../../../../../google/api/annotations_pb.js');
goog.object.extend(proto, google_api_annotations_pb);
goog.exportSymbol('proto.google.ads.googleads.v3.common.TextLabel', null, global);
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.google.ads.googleads.v3.common.TextLabel = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.google.ads.googleads.v3.common.TextLabel, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.google.ads.googleads.v3.common.TextLabel.displayName = 'proto.google.ads.googleads.v3.common.TextLabel';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.toObject = function(opt_includeInstance) {
return proto.google.ads.googleads.v3.common.TextLabel.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.google.ads.googleads.v3.common.TextLabel} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.google.ads.googleads.v3.common.TextLabel.toObject = function(includeInstance, msg) {
var f, obj = {
backgroundColor: (f = msg.getBackgroundColor()) && google_protobuf_wrappers_pb.StringValue.toObject(includeInstance, f),
description: (f = msg.getDescription()) && google_protobuf_wrappers_pb.StringValue.toObject(includeInstance, f)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.google.ads.googleads.v3.common.TextLabel}
*/
proto.google.ads.googleads.v3.common.TextLabel.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.google.ads.googleads.v3.common.TextLabel;
return proto.google.ads.googleads.v3.common.TextLabel.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.google.ads.googleads.v3.common.TextLabel} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.google.ads.googleads.v3.common.TextLabel}
*/
proto.google.ads.googleads.v3.common.TextLabel.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new google_protobuf_wrappers_pb.StringValue;
reader.readMessage(value,google_protobuf_wrappers_pb.StringValue.deserializeBinaryFromReader);
msg.setBackgroundColor(value);
break;
case 2:
var value = new google_protobuf_wrappers_pb.StringValue;
reader.readMessage(value,google_protobuf_wrappers_pb.StringValue.deserializeBinaryFromReader);
msg.setDescription(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.google.ads.googleads.v3.common.TextLabel.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.google.ads.googleads.v3.common.TextLabel} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.google.ads.googleads.v3.common.TextLabel.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getBackgroundColor();
if (f != null) {
writer.writeMessage(
1,
f,
google_protobuf_wrappers_pb.StringValue.serializeBinaryToWriter
);
}
f = message.getDescription();
if (f != null) {
writer.writeMessage(
2,
f,
google_protobuf_wrappers_pb.StringValue.serializeBinaryToWriter
);
}
};
/**
* optional google.protobuf.StringValue background_color = 1;
* @return {?proto.google.protobuf.StringValue}
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.getBackgroundColor = function() {
return /** @type{?proto.google.protobuf.StringValue} */ (
jspb.Message.getWrapperField(this, google_protobuf_wrappers_pb.StringValue, 1));
};
/**
* @param {?proto.google.protobuf.StringValue|undefined} value
* @return {!proto.google.ads.googleads.v3.common.TextLabel} returns this
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.setBackgroundColor = function(value) {
return jspb.Message.setWrapperField(this, 1, value);
};
/**
* Clears the message field making it undefined.
* @return {!proto.google.ads.googleads.v3.common.TextLabel} returns this
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.clearBackgroundColor = function() {
return this.setBackgroundColor(undefined);
};
/**
* Returns whether this field is set.
* @return {boolean}
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.hasBackgroundColor = function() {
return jspb.Message.getField(this, 1) != null;
};
/**
* optional google.protobuf.StringValue description = 2;
* @return {?proto.google.protobuf.StringValue}
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.getDescription = function() {
return /** @type{?proto.google.protobuf.StringValue} */ (
jspb.Message.getWrapperField(this, google_protobuf_wrappers_pb.StringValue, 2));
};
/**
* @param {?proto.google.protobuf.StringValue|undefined} value
* @return {!proto.google.ads.googleads.v3.common.TextLabel} returns this
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.setDescription = function(value) {
return jspb.Message.setWrapperField(this, 2, value);
};
/**
* Clears the message field making it undefined.
* @return {!proto.google.ads.googleads.v3.common.TextLabel} returns this
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.clearDescription = function() {
return this.setDescription(undefined);
};
/**
* Returns whether this field is set.
* @return {boolean}
*/
proto.google.ads.googleads.v3.common.TextLabel.prototype.hasDescription = function() {
return jspb.Message.getField(this, 2) != null;
};
goog.object.extend(exports, proto.google.ads.googleads.v3.common);
|
function carregar() {
var msg = window.document.getElementById('msg')
var img = window.document.getElementById('imagem')
var data = new Date()
var hora = data.getHours();
msg.innerHTML = `Agora são ${hora} horas.`
if (hora >= 0 && hora < 12) {
// BOM DIA!
img.src="Modelo/fotomanha4.jpg"
document.body.style.background = '#FFFF00'
} else if (hora >= 12 && hora <= 18) {
// boa tarde
img.src="Modelo/fototarde4.jpg"
document.body.style.background = '#FFA500'
} else {
//boa noite
img.src="Modelo/fotonoite4.jpg"
document.body.style.background = '#808080'
}
}
|
'use strict';
var torrentStream = require('torrent-stream');
var _ = require('lodash');
var net = require('net');
var BITTORRENT_PORT = 6881;
var tryPort = new Promise(function (resolve) {
function findPort(port) {
var s = net.createServer();
s.on('error', function() {
findPort(0);
});
s.listen(port, function() {
var port = s.address().port;
s.close(function() {
resolve(port);
});
});
}
findPort(BITTORRENT_PORT);
});
module.exports = function (torrent, opts) {
var engine = torrentStream(torrent, _.cloneDeep(opts));
engine.once('verifying', function () {
var totalPieces = engine.torrent.pieces.length;
var verifiedPieces = 0;
console.log('verifying ' + engine.infoHash);
engine.files.forEach(function (file, i) {
console.log(i + ' ' + file.name);
});
engine.on('verify', function () {
if (++verifiedPieces === totalPieces) {
engine.emit('finished');
console.log('finished ' + engine.infoHash);
}
});
});
engine.once('ready', function () {
console.log('ready ' + engine.infoHash);
engine.ready = true;
});
engine.on('uninterested', function () {
console.log('uninterested ' + engine.infoHash);
});
engine.on('interested', function () {
console.log('interested ' + engine.infoHash);
});
engine.on('idle', function () {
console.log('idle ' + engine.infoHash);
});
engine.on('error', function (e) {
console.log('error ' + engine.infoHash + ': ' + e);
});
engine.once('destroyed', function () {
console.log('destroyed ' + engine.infoHash);
engine.removeAllListeners();
});
tryPort.then(function (port) {
engine.listen(port, function () {
console.log('listening ' + engine.infoHash + ' on port ' + engine.port);
});
});
return engine;
};
|
import gurobipy as gp
from gurobipy import GRB
from . import partition
from ..useful_methods import get_leaves
from collections import defaultdict
import datetime
import random
import os
from ..reporting_tools import reporting_tools
def main(graph, graph_nx, hw_details):
leaf_set= set(get_leaves(graph_nx))
list_of_chosen_sets, status_dict= partition.first_partition(graph, graph_nx, hw_details)
map_cu_to_node= defaultdict(set)
map_node_to_cu= {}
for cu, node_set in enumerate(list_of_chosen_sets):
for n in node_set:
for p in graph_nx.predecessors(n):
map_node_to_cu[p] = cu + 1
assert len(list(graph_nx.predecessors(n))) != 0
for n, cu in map_node_to_cu.items():
map_cu_to_node[cu].add(n)
all_nodes= set(graph_nx.nodes())
mapped_set= set(map_node_to_cu.keys())
unmapped_set= all_nodes - mapped_set
n_unmapped= len(unmapped_set)
cu_set= list(sorted(list(range(1, hw_details.N_PE + 1))))
n_CU= hw_details.N_PE
active_edges= [e for n in unmapped_set for e in graph_nx.in_edges(n)]
print(map_node_to_cu)
print(cu_set)
print('Constructing model ..')
m= gp.Model('mapping')
fname= os.path.basename(__file__)
log_file= './gurobi_' + fname +'.log'
m.Params.LogFile= log_file
# m.Params.Method= 3
# m.Params.Presolve= -1
## m.Params.MIPFocus= 1
m.Params.Threads= 12
## m.Params.ConcurrentMIP=4
# # Setting MIPGap is risky for the output mapping in muxes
## m.Params.MIPGap= 0.1
# m.Params.TimeLimit= 1000
m.Params.Symmetry= 2
# obj= m.getAttr("ObjBound")
# print(dir(m))
# print(dir(GRB))
# Variables
done= m.addVars(all_nodes, vtype= GRB.BINARY)
done_CU= m.addVars(all_nodes, vtype= GRB.INTEGER, lb=0, ub= max(cu_set)) # cu= 0 means it is not assigned
mapped= m.addVars(unmapped_set, vtype= GRB.BINARY)
# mapped_per_CU= m.addVars(cu_set, vtype= GRB.INTEGER, lb=0, ub= n_unmapped)
mapped_per_CU= m.addVars(cu_set, vtype= GRB.INTEGER, lb=55, ub= 65)
cu_indicator= m.addVars(cu_set, unmapped_set, vtype= GRB.BINARY)
max_mapped= m.addVar(vtype= GRB.INTEGER, lb=0, ub= n_unmapped)
min_mapped= m.addVar(vtype= GRB.INTEGER, lb=0, ub= n_unmapped)
gap_per_CU= m.addVars(cu_set, vtype= GRB.INTEGER, lb=0, ub= n_unmapped)
edge_cost= m.addVars(active_edges, vtype= GRB.BINARY)
same_cu= m.addVars(active_edges, vtype= GRB.BINARY)
# Constraints
print('Adding constraints ..')
# init constraints
m.addConstrs(done_CU[n] == map_node_to_cu[n] for n in mapped_set)
m.addConstrs(done_CU[n] >= 1 for n in mapped_set)
m.addConstrs(done[n] == 1 for n in mapped_set)
m.addConstrs(done[n] == 0 for n in unmapped_set)
m.addConstrs(((same_cu[e] == 1) >> (done_CU[e[0]] == done_CU[e[1]]) for e in active_edges))
# m.addConstrs(((done_CU[e[0]] == done_CU[e[1]]) >> (same_cu[e] == 1) for e in active_edges))
m.addConstrs(((done_CU[e[0]] - done_CU[e[1]]) <= n_CU * (1 - same_cu[e]) for e in active_edges))
m.addConstrs(((done_CU[e[1]] - done_CU[e[0]]) <= n_CU * (1 - same_cu[e]) for e in active_edges))
m.addConstrs(((done[e[0]] + same_cu[e] >= mapped[e[1]]) for e in active_edges))
m.addConstrs((mapped[n] == 1) >> (done_CU[n] >= 1) for n in unmapped_set)
m.addConstrs(done_CU[n] >= mapped[n] for n in unmapped_set)
m.addConstrs(done_CU[n] <= n_CU*mapped[n] for n in unmapped_set)
# edge cost
m.addConstrs(edge_cost[e] <= mapped[e[1]] for e in active_edges)
m.addConstrs(edge_cost[e] >= (mapped[e[1]] - same_cu[e]) for e in active_edges)
# workload balance cost
# m.addConstrs(mapped_per_CU[c] == sum([1 for n in unmapped_set if (mapped[n] and (done_CU[n]==cu))]) for c in cu_set)
# m.addConstrs((((done_CU[n] == cu) >> (cu_indicator[cu, n] == 1)) for cu in cu_set for n in unmapped_set))
m.addConstrs((done_CU[n] == sum([cu_indicator[cu, n] * cu for cu in cu_set]) for n in unmapped_set))
m.addConstrs(cu_indicator.sum('*', n) <= 1 for n in unmapped_set)
m.addConstrs((mapped_per_CU[cu] == cu_indicator.sum(cu, '*') for cu in cu_set))
m.addConstrs(mapped_per_CU[cu] <= max_mapped for cu in cu_set)
m.addConstrs(mapped_per_CU[cu] >= min_mapped for cu in cu_set)
m.addConstrs(gap_per_CU[cu] == max_mapped - mapped_per_CU[cu] for cu in cu_set)
total_mapped_nodes = mapped.sum('*')
w_tot= 10
w_balance= 5
w_edges= 1
obj= w_tot* total_mapped_nodes - w_edges*(edge_cost.sum('*')) - w_balance*(gap_per_CU.sum('*'))
# obj= w_tot* total_mapped_nodes - w_edges*(edge_cost.sum('*')) - w_balance*(max_mapped - min_mapped)
m.setObjective(obj, GRB.MAXIMIZE)
m.optimize()
print('done_CU', [(n, done_CU[n].X) for n in all_nodes])
print('cu_indicator', [cu_indicator[round(done_CU[n].X), n].X for n in unmapped_set if mapped[n].X > 0.5])
print('mapped', [(n, mapped[n].X) for n in unmapped_set])
print('max_mapped',round( max_mapped.X))
print('min_mapped', round(min_mapped.X))
print('total',sum([round(mapped[n].X) for n in unmapped_set]))
final_done_CU= {n:round(done_CU[n].X)%4 for n in all_nodes}
|
import numpy as np
import torch
import random
import logging
import os
import torch.multiprocessing as mp
import torch.distributed as dist
import subprocess
import pickle
import shutil
def check_numpy_to_torch(x):
if isinstance(x, np.ndarray):
return torch.from_numpy(x).float(), True
return x, False
def limit_period(val, offset=0.5, period=np.pi):
val, is_numpy = check_numpy_to_torch(val)
ans = val - torch.floor(val / period + offset) * period
return ans.numpy() if is_numpy else ans
def drop_info_with_name(info, name):
ret_info = {}
keep_indices = [i for i, x in enumerate(info['name']) if x != name]
for key in info.keys():
ret_info[key] = info[key][keep_indices]
return ret_info
def rotate_points_along_z(points, angle):
"""
Args:
points: (B, N, 3 + C)
angle: (B), angle along z-axis, angle increases x ==> y
Returns:
"""
points, is_numpy = check_numpy_to_torch(points)
angle, _ = check_numpy_to_torch(angle)
cosa = torch.cos(angle)
sina = torch.sin(angle)
zeros = angle.new_zeros(points.shape[0])
ones = angle.new_ones(points.shape[0])
rot_matrix = torch.stack((
cosa, sina, zeros,
-sina, cosa, zeros,
zeros, zeros, ones
), dim=1).view(-1, 3, 3).float()
points_rot = torch.matmul(points[:, :, 0:3], rot_matrix)
points_rot = torch.cat((points_rot, points[:, :, 3:]), dim=-1)
return points_rot.numpy() if is_numpy else points_rot
def mask_points_by_range(points, limit_range):
mask = (points[:, 0] >= limit_range[0]) & (points[:, 0] <= limit_range[3]) \
& (points[:, 1] >= limit_range[1]) & (points[:, 1] <= limit_range[4])
return mask
def get_voxel_centers(voxel_coords, downsample_times, voxel_size, point_cloud_range):
"""
Args:
voxel_coords: (N, 3)
downsample_times:
voxel_size:
point_cloud_range:
Returns:
"""
assert voxel_coords.shape[1] == 3
voxel_centers = voxel_coords[:, [2, 1, 0]].float() # (xyz)
voxel_size = torch.tensor(voxel_size, device=voxel_centers.device).float() * downsample_times
pc_range = torch.tensor(point_cloud_range[0:3], device=voxel_centers.device).float()
voxel_centers = (voxel_centers + 0.5) * voxel_size + pc_range
return voxel_centers
def create_logger(log_file=None, rank=0, log_level=logging.INFO):
logger = logging.getLogger(__name__)
logger.setLevel(log_level if rank == 0 else 'ERROR')
formatter = logging.Formatter('%(asctime)s %(levelname)5s %(message)s')
console = logging.StreamHandler()
console.setLevel(log_level if rank == 0 else 'ERROR')
console.setFormatter(formatter)
logger.addHandler(console)
if log_file is not None:
file_handler = logging.FileHandler(filename=log_file)
file_handler.setLevel(log_level if rank == 0 else 'ERROR')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def keep_arrays_by_name(gt_names, used_classes):
inds = [i for i, x in enumerate(gt_names) if x in used_classes]
inds = np.array(inds, dtype=np.int64)
return inds
def init_dist_slurm(batch_size, tcp_port, local_rank, backend='nccl'):
"""
modified from https://github.com/open-mmlab/mmdetection
Args:
batch_size:
tcp_port:
backend:
Returns:
"""
proc_id = int(os.environ['SLURM_PROCID'])
ntasks = int(os.environ['SLURM_NTASKS'])
node_list = os.environ['SLURM_NODELIST']
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(proc_id % num_gpus)
addr = subprocess.getoutput('scontrol show hostname {} | head -n1'.format(node_list))
os.environ['MASTER_PORT'] = str(tcp_port)
os.environ['MASTER_ADDR'] = addr
os.environ['WORLD_SIZE'] = str(ntasks)
os.environ['RANK'] = str(proc_id)
dist.init_process_group(backend=backend)
total_gpus = dist.get_world_size()
assert batch_size % total_gpus == 0, 'Batch size should be matched with GPUS: (%d, %d)' % (batch_size, total_gpus)
batch_size_each_gpu = batch_size // total_gpus
rank = dist.get_rank()
return batch_size_each_gpu, rank
def init_dist_pytorch(batch_size, tcp_port, local_rank, backend='nccl'):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(local_rank % num_gpus)
dist.init_process_group(
backend=backend,
init_method='tcp://127.0.0.1:%d' % tcp_port,
rank=local_rank,
world_size=num_gpus
)
assert batch_size % num_gpus == 0, 'Batch size should be matched with GPUS: (%d, %d)' % (batch_size, num_gpus)
batch_size_each_gpu = batch_size // num_gpus
rank = dist.get_rank()
return batch_size_each_gpu, rank
def get_dist_info():
if torch.__version__ < '1.0':
initialized = dist._initialized
else:
if dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
rank = 0
world_size = 1
return rank, world_size
def merge_results_dist(result_part, size, tmpdir):
rank, world_size = get_dist_info()
os.makedirs(tmpdir, exist_ok=True)
dist.barrier()
pickle.dump(result_part, open(os.path.join(tmpdir, 'result_part_{}.pkl'.format(rank)), 'wb'))
dist.barrier()
if rank != 0:
return None
part_list = []
for i in range(world_size):
part_file = os.path.join(tmpdir, 'result_part_{}.pkl'.format(i))
part_list.append(pickle.load(open(part_file, 'rb')))
ordered_results = []
for res in zip(*part_list):
ordered_results.extend(list(res))
ordered_results = ordered_results[:size]
shutil.rmtree(tmpdir)
return ordered_results
def merge_results_dist_Objects(result_part, size, tmpdir):
from waymo_open_dataset.protos import metrics_pb2
rank, world_size = get_dist_info()
os.makedirs(tmpdir, exist_ok=True)
dist.barrier()
pickle.dump(result_part, open(os.path.join(tmpdir, 'result_part_{}.pkl'.format(rank)), 'wb'))
dist.barrier()
if rank != 0:
return None
part_list = []
for i in range(world_size):
part_file = os.path.join(tmpdir, 'result_part_{}.pkl'.format(i))
part_list.append(pickle.load(open(part_file, 'rb')))
total_objects = metrics_pb2.Objects()
for objects in part_list:
total_objects.MergeFrom(objects)
return total_objects
|
// Copyright 2013 The Closure Library 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.
/**
* @fileoverview This file contain classes that add support for cross-domain XHR
* requests (see http://www.w3.org/TR/cors/). Most modern browsers are able to
* use a regular XMLHttpRequest for that, but IE 8 use XDomainRequest object
* instead. This file provides an adapter from this object to a goog.net.XhrLike
* and a factory to allow using this with a goog.net.XhrIo instance.
*
* IE 7 and older versions are not supported (given that they do not support
* CORS requests).
*/
goog.provide('goog.net.CorsXmlHttpFactory');
goog.provide('goog.net.IeCorsXhrAdapter');
goog.require('goog.net.HttpStatus');
goog.require('goog.net.XhrLike');
goog.require('goog.net.XmlHttp');
goog.require('goog.net.XmlHttpFactory');
/**
* A factory of XML http request objects that supports cross domain requests.
* This class should be instantiated and passed as the parameter of a
* goog.net.XhrIo constructor to allow cross-domain requests in every browser.
*
* @extends {goog.net.XmlHttpFactory}
* @constructor
* @final
*/
goog.net.CorsXmlHttpFactory = function() {
goog.net.XmlHttpFactory.call(this);
};
goog.inherits(goog.net.CorsXmlHttpFactory, goog.net.XmlHttpFactory);
/** @override */
goog.net.CorsXmlHttpFactory.prototype.createInstance = function() {
var xhr = new XMLHttpRequest();
if (('withCredentials' in xhr)) {
return xhr;
} else if (typeof XDomainRequest != 'undefined') {
return new goog.net.IeCorsXhrAdapter();
} else {
throw new Error('Unsupported browser');
}
};
/** @override */
goog.net.CorsXmlHttpFactory.prototype.internalGetOptions = function() {
return {};
};
/**
* An adapter around Internet Explorer's XDomainRequest object that makes it
* look like a standard XMLHttpRequest. This can be used instead of
* XMLHttpRequest to support CORS.
*
* @implements {goog.net.XhrLike}
* @constructor
* @struct
* @final
*/
goog.net.IeCorsXhrAdapter = function() {
/**
* The underlying XDomainRequest used to make the HTTP request.
* @type {!XDomainRequest}
* @private
*/
this.xdr_ = new XDomainRequest();
/**
* The simulated ready state.
* @type {number}
*/
this.readyState = goog.net.XmlHttp.ReadyState.UNINITIALIZED;
/**
* The simulated ready state change callback function.
* @type {?function()|undefined}
*/
this.onreadystatechange = null;
/** @override */
this.response = '';
/**
* The simulated response text parameter.
* @type {string}
*/
this.responseText = '';
/**
* This implementation only supports text response.
* @type {string}
* @override
*/
this.responseType = '';
/**
* The simulated status code
* @type {number}
*/
this.status = -1;
/** @override */
this.responseXML = null;
/** @override */
this.statusText = '';
this.xdr_.onload = goog.bind(this.handleLoad_, this);
this.xdr_.onerror = goog.bind(this.handleError_, this);
this.xdr_.onprogress = goog.bind(this.handleProgress_, this);
this.xdr_.ontimeout = goog.bind(this.handleTimeout_, this);
};
/**
* Opens a connection to the provided URL.
* @param {string} method The HTTP method to use. Valid methods include GET and
* POST.
* @param {string} url The URL to contact. The authority of this URL must match
* the authority of the current page's URL (e.g. http or https).
* @param {?boolean=} opt_async Whether the request is asynchronous, defaulting
* to true. XDomainRequest does not support syncronous requests, so setting
* it to false will actually raise an exception.
* @override
*/
goog.net.IeCorsXhrAdapter.prototype.open = function(method, url, opt_async) {
if (opt_async != null && (!opt_async)) {
throw new Error('Only async requests are supported.');
}
this.xdr_.open(method, url);
};
/**
* Sends the request to the remote server. Before calling this function, always
* call {@link open}.
* @param {(ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string)=}
* opt_content The content to send as POSTDATA, if any. Only string data is
* supported by this implementation.
* @override
*/
goog.net.IeCorsXhrAdapter.prototype.send = function(opt_content) {
if (opt_content) {
if (typeof opt_content == 'string') {
this.xdr_.send(opt_content);
} else {
throw new Error('Only string data is supported');
}
} else {
this.xdr_.send();
}
};
/**
* @override
*/
goog.net.IeCorsXhrAdapter.prototype.abort = function() {
this.xdr_.abort();
};
/**
* Sets a request header to send to the remote server. Because this
* implementation does not support request headers, this function does nothing.
* @param {string} key The name of the HTTP header to set. Ignored.
* @param {string} value The value to set for the HTTP header. Ignored.
* @override
*/
goog.net.IeCorsXhrAdapter.prototype.setRequestHeader = function(key, value) {
// Unsupported; ignore the header.
};
/**
* Returns the value of the response header identified by key. This
* implementation only supports the 'content-type' header.
* @param {string} key The request header to fetch. If this parameter is set to
* 'content-type' (case-insensitive), this function returns the value of
* the 'content-type' request header. If this parameter is set to any other
* value, this function always returns an empty string.
* @return {string} The value of the response header, or an empty string if key
* is not 'content-type' (case-insensitive).
* @override
*/
goog.net.IeCorsXhrAdapter.prototype.getResponseHeader = function(key) {
if (key.toLowerCase() == 'content-type') {
return this.xdr_.contentType;
}
return '';
};
/**
* Handles a request that has fully loaded successfully.
* @private
*/
goog.net.IeCorsXhrAdapter.prototype.handleLoad_ = function() {
// IE only calls onload if the status is 200, so the status code must be OK.
this.status = goog.net.HttpStatus.OK;
this.response = this.responseText = this.xdr_.responseText;
this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);
};
/**
* Handles a request that has failed to load.
* @private
*/
goog.net.IeCorsXhrAdapter.prototype.handleError_ = function() {
// IE doesn't tell us what the status code actually is (other than the fact
// that it is not 200), so simulate an INTERNAL_SERVER_ERROR.
this.status = goog.net.HttpStatus.INTERNAL_SERVER_ERROR;
this.response = this.responseText = '';
this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);
};
/**
* Handles a request that timed out.
* @private
*/
goog.net.IeCorsXhrAdapter.prototype.handleTimeout_ = function() {
this.handleError_();
};
/**
* Handles a request that is in the process of loading.
* @private
*/
goog.net.IeCorsXhrAdapter.prototype.handleProgress_ = function() {
// IE only calls onprogress if the status is 200, so the status code must be
// OK.
this.status = goog.net.HttpStatus.OK;
this.setReadyState_(goog.net.XmlHttp.ReadyState.LOADING);
};
/**
* Sets this XHR's ready state and fires the onreadystatechange listener (if one
* is set).
* @param {number} readyState The new ready state.
* @private
*/
goog.net.IeCorsXhrAdapter.prototype.setReadyState_ = function(readyState) {
this.readyState = readyState;
if (this.onreadystatechange) {
this.onreadystatechange();
}
};
/**
* Returns the response headers from the server. This implemntation only returns
* the 'content-type' header.
* @return {string} The headers returned from the server.
* @override
*/
goog.net.IeCorsXhrAdapter.prototype.getAllResponseHeaders = function() {
return 'content-type: ' + this.xdr_.contentType;
};
|
import React, { createRef, Component, PureComponent } from 'react';
import PropTypes from 'prop-types';
import { storiesOf } from '@storybook/react';
import { FormClose } from 'grommet-icons';
import { Box, Button, CheckBox, Grommet, Select, Text } from 'grommet';
import { grommet } from 'grommet/themes';
import { deepMerge } from 'grommet/utils';
import { theme as customSearchTheme } from './theme';
import { SearchInputContext } from './components/SearchInputContext';
const customRoundedTheme = deepMerge(grommet, {
global: {
control: {
border: {
radius: '24px',
},
},
input: {
weight: 400,
},
font: {
size: '12px',
},
},
text: {
medium: '13px',
},
textInput: {
extend: 'padding: 0 12px;',
},
select: {
control: {
extend: 'padding: 3px 6px;',
},
},
});
class SimpleSelect extends Component {
static propTypes = {
theme: PropTypes.shape({}),
};
static defaultProps = {
theme: undefined,
};
state = {
options: ['one', 'two'],
value: '',
};
render() {
const { theme } = this.props;
const { options, value } = this.state;
return (
<Grommet full theme={theme || grommet}>
<Box fill align="center" justify="start" pad="large">
<Select
id="select"
name="select"
placeholder="Select"
value={value}
options={options}
onChange={({ option }) => this.setState({ value: option })}
/>
</Box>
</Grommet>
);
}
}
const defaultOptions = [];
const objectOptions = [];
for (let i = 1; i <= 200; i += 1) {
defaultOptions.push(`option ${i}`);
objectOptions.push({
lab: `option ${i}`,
val: i,
dis: i % 5 === 0,
sel: i % 13 === 0,
});
}
class SearchSelect extends Component {
state = {
options: defaultOptions,
value: '',
};
render() {
const { options, value } = this.state;
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="start" pad="large">
<Select
size="medium"
placeholder="Select"
value={value}
options={options}
onChange={({ option }) => this.setState({ value: option })}
onClose={() => this.setState({ options: defaultOptions })}
onSearch={text => {
const exp = new RegExp(text, 'i');
this.setState({
options: defaultOptions.filter(o => exp.test(o)),
});
}}
/>
</Box>
</Grommet>
);
}
}
class SimpleMultiSelect extends Component {
state = {
options: defaultOptions,
value: '',
};
render() {
const { options, value } = this.state;
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="start" pad="large">
<Select
size="medium"
placeholder="Select"
multiple
value={value}
options={options}
onChange={({ value: nextValue }) =>
this.setState({ value: nextValue })
}
onClose={() => this.setState({ options: defaultOptions })}
onSearch={text => {
const exp = new RegExp(text, 'i');
this.setState({
options: defaultOptions.filter(o => exp.test(o)),
});
}}
/>
</Box>
</Grommet>
);
}
}
class ObjectMultiSelect extends Component {
state = {
options: objectOptions,
value: '',
};
render() {
const { options, value } = this.state;
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="start" pad="large">
<Select
size="medium"
placeholder="Select"
multiple
closeOnChange={false}
disabledKey="dis"
labelKey="lab"
valueKey="val"
value={value}
options={options}
onChange={({ value: nextValue }) =>
this.setState({ value: nextValue })
}
onClose={() => this.setState({ options: objectOptions })}
onSearch={text => {
const exp = new RegExp(text, 'i');
this.setState({
options: objectOptions.filter(o => exp.test(o.lab)),
});
}}
/>
</Box>
</Grommet>
);
}
}
const allSeasons = [
'S01',
'S02',
'S03',
'S04',
'S05',
'S06',
'S07',
'S08',
'S09',
'S10',
];
class SeasonsSelect extends Component {
state = { selected: [] };
onRemoveSeason = season => {
const { selected } = this.state;
const nextSelected = [...selected];
nextSelected.splice(nextSelected.indexOf(allSeasons.indexOf(season)), 1);
this.setState({ selected: nextSelected });
};
renderSeason = season => (
<Button
key={`season_tag_${season}`}
href="#"
onClick={event => {
event.preventDefault();
event.stopPropagation();
this.onRemoveSeason(season);
}}
onFocus={event => event.stopPropagation()}
>
<Box
align="center"
direction="row"
gap="xsmall"
pad={{ vertical: 'xsmall', horizontal: 'small' }}
margin="xsmall"
background="accent-1"
round="large"
>
<Text size="small" color="white">
{season}
</Text>
<Box background="white" round="full" margin={{ left: 'xsmall' }}>
<FormClose
color="accent-1"
size="small"
style={{ width: '12px', height: '12px' }}
/>
</Box>
</Box>
</Button>
);
renderOption = (option, index, options, state) => (
<Box pad="small" background={state.active ? 'active' : undefined}>
{option}
</Box>
);
render() {
const { selected } = this.state;
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="center">
<Select
closeOnChange={false}
multiple
value={
<Box wrap direction="row" width="small">
{selected && selected.length ? (
selected.map(index => this.renderSeason(allSeasons[index]))
) : (
<Box
pad={{ vertical: 'xsmall', horizontal: 'small' }}
margin="xsmall"
>
Select Season
</Box>
)}
</Box>
}
options={allSeasons}
selected={selected}
disabled={[2, 6]}
onChange={({ selected: nextSelected }) => {
this.setState({ selected: nextSelected.sort() });
}}
>
{this.renderOption}
</Select>
</Box>
</Grommet>
);
}
}
const allContentPartners = [
{
name: 'Test Partner',
id: '32131232',
},
{
name: 'Test Partner 1',
id: '32131232',
},
{
name: 'Test Partner 2',
id: '32131242',
},
{
name: 'Test Partner 3',
id: '32131252',
},
{
name: 'Test Partner 4',
id: '32131262',
},
{
name: 'Test Partner 5',
id: '32131272',
},
{
name: 'Test Partner 6',
id: '32131231',
},
{
name: 'Test Partner 7',
id: '32131234',
},
{
name: 'Test Partner 8',
id: '32131245',
},
{
name: 'Test Partner 9',
id: '32131256',
},
{
name: 'Test Partner 10',
id: '32131269',
},
{
name: 'Test Partner 11',
id: '32131244',
},
];
class CustomSearchSelect extends Component {
state = {
contentPartners: allContentPartners,
selectedContentPartners: [],
searching: false,
};
selectRef = createRef();
clearContentPartners = () => this.setState({ selectedContentPartners: [] });
renderOption = ({ name }) => {
const { selectedContentPartners } = this.state;
return (
<Box direction="row" align="center" pad="small" flex={false}>
<CheckBox
tabIndex="-1"
checked={selectedContentPartners.some(
partner => partner.name === name,
)}
label={<Text size="small">{name}</Text>}
onChange={() => {}}
/>
</Box>
);
};
renderContentPartners = () => {
const { selectedContentPartners } = this.state;
return (
<Box
direction="row"
gap="xsmall"
pad={{ left: 'small', vertical: 'small' }}
align="center"
flex
>
<Box
background="brand"
round="medium"
align="center"
justify="center"
pad={{ horizontal: 'xsmall' }}
style={{ minWidth: '21px' }}
>
<Text size="small">{selectedContentPartners.length}</Text>
</Box>
<Box flex>
<Text size="small" truncate>
{selectedContentPartners.map(({ name }) => name).join(', ')}
</Text>
</Box>
<Button
href="#"
onFocus={event => event.stopPropagation()}
onClick={event => {
event.preventDefault();
event.stopPropagation();
this.clearContentPartners();
this.selectRef.current.focus();
}}
>
<Box background="gray" round="full">
<FormClose style={{ width: '12px', height: '12px' }} />
</Box>
</Button>
</Box>
);
};
render() {
const { contentPartners, searching, selectedContentPartners } = this.state;
return (
<Grommet full theme={customSearchTheme}>
<Box fill align="center" justify="center" width="medium">
<SearchInputContext.Provider value={{ searching }}>
<Select
ref={this.selectRef}
closeOnChange={false}
placeholder="Select Content Partners"
searchPlaceholder="Search Content Partners"
emptySearchMessage="No partners found"
multiple
value={
selectedContentPartners.length
? this.renderContentPartners()
: undefined
}
selected={selectedContentPartners.map(option =>
contentPartners.indexOf(option),
)}
options={contentPartners}
onChange={({ option }) => {
const newSelectedPartners = [...selectedContentPartners];
const seasonIndex = newSelectedPartners
.map(({ name }) => name)
.indexOf(option.name);
if (seasonIndex >= 0) {
newSelectedPartners.splice(seasonIndex, 1);
} else {
newSelectedPartners.push(option);
}
const selectedPartnerNames = newSelectedPartners.map(
({ name }) => name,
);
this.setState({
selectedContentPartners: newSelectedPartners,
contentPartners: allContentPartners.sort((p1, p2) => {
const p1Exists = selectedPartnerNames.includes(p1.name);
const p2Exists = selectedPartnerNames.includes(p2.name);
if (!p1Exists && p2Exists) {
return 1;
}
if (p1Exists && !p2Exists) {
return -1;
}
if (p1.name.toLowerCase() < p2.name.toLowerCase()) {
return -1;
}
return 1;
}),
});
}}
onSearch={query => {
this.setState({ searching: true }, () => {
setTimeout(() => {
this.setState({
searching: false,
contentPartners: allContentPartners.filter(
s =>
s.name.toLowerCase().indexOf(query.toLowerCase()) >=
0,
),
});
}, 500);
});
}}
>
{this.renderOption}
</Select>
</SearchInputContext.Provider>
</Box>
</Grommet>
);
}
}
class DarkSelect extends Component {
state = {
options: ['one', 'two'],
value: '',
};
render() {
const { options, value } = this.state;
return (
<Grommet full theme={grommet} {...this.props}>
<Box fill background="dark-1" align="center" justify="center">
<Select
placeholder="Select"
value={value}
options={options}
onChange={({ option }) => this.setState({ value: option })}
/>
</Box>
</Grommet>
);
}
}
class Option extends PureComponent {
render() {
const { value, selected } = this.props;
return (
<Box direction="row" gap="small" align="center" pad="xsmall">
<CheckBox tabIndex="-1" checked={selected} onChange={() => {}} />
{value}
</Box>
);
}
}
const dummyOptions = Array(2000)
.fill()
.map((_, i) => `option ${i}`)
.sort((a, b) =>
a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }),
);
class ManyOptions extends Component {
state = {
selected: [],
options: dummyOptions,
};
render() {
const { options, selected } = this.state;
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="start" pad="large">
<Select
multiple
closeOnChange={false}
placeholder="select an option..."
selected={selected}
options={options}
dropHeight="medium"
onClose={() =>
this.setState({
options: options.sort((p1, p2) => {
const p1Exists = selected.includes(p1);
const p2Exists = selected.includes(p2);
if (!p1Exists && p2Exists) {
return 1;
}
if (p1Exists && !p2Exists) {
return -1;
}
return p1.localeCompare(p2, undefined, {
numeric: true,
sensitivity: 'base',
});
}),
})
}
onChange={({ selected: nextSelected }) => {
this.setState({ selected: nextSelected });
}}
>
{(option, index) => (
<Option
value={option}
selected={selected.indexOf(index) !== -1}
/>
)}
</Select>
</Box>
</Grommet>
);
}
}
storiesOf('Select', module)
.add('Simple', () => <SimpleSelect />)
.add('Search', () => <SearchSelect />)
.add('Simple Multiple', () => <SimpleMultiSelect />)
.add('Object Multiple', () => <ObjectMultiSelect />)
.add('Seasons', () => <SeasonsSelect />)
.add('Custom Search', () => <CustomSearchSelect />)
.add('Dark', () => <DarkSelect />)
.add('Custom Colors', () => (
<DarkSelect
theme={{
global: { font: { family: 'Arial' } },
select: { background: '#000000', iconColor: '#d3d3d3' },
}}
/>
))
.add('Custom Rounded', () => <SimpleSelect theme={customRoundedTheme} />)
.add('Lots of options', () => <ManyOptions />);
|
import _ from 'underscore';
import Introduction from '../game/entity/character/player/quest/misc/introduction';
import BulkySituation from '../game/entity/character/player/quest/misc/bulkysituation';
import QuestData from '../../data/quests.json';
import AchievementData from '../../data/achievements.json';
import Achievement from '../game/entity/character/player/achievement';
export default class Quests {
constructor(player) {
this.player = player;
this.quests = {};
this.achievements = {};
this.load();
}
load() {
let questCount = 0;
_.each(QuestData, (quest) => {
if (questCount === 0) this.quests[quest.id] = new Introduction(this.player, quest);
else if (questCount === 1) this.quests[quest.id] = new BulkySituation(this.player, quest);
questCount += 1;
});
_.each(AchievementData, (achievement) => {
this.achievements[achievement.id] = new Achievement(
achievement.id,
this.player,
);
});
}
updateQuests(ids, stages) {
for (let id = 0; id < ids.length; id += 1) {
if (parseInt(ids[id], 10) && this.quests[id]) {
this.quests[id].load(stages[id]);
}
}
}
updateAchievements(ids, progress) {
for (let id = 0; id < ids.length; id += 1) {
if (parseInt(ids[id], 10) && this.achievements[id]) {
this.achievements[id].setProgress(progress[id]);
}
}
if (this.readyCallback) this.readyCallback();
}
getQuest(id) {
if (id in this.quests) return this.quests[id];
return null;
}
getQuests() {
let ids = '';
let stages = '';
for (let id = 0; id < this.getQuestSize(); id += 1) {
ids += `${id} `;
stages += `${this.quests[id].stage} `;
}
return {
username: this.player.username,
ids,
stages,
};
}
getAchievements() {
let ids = '';
let progress = '';
for (let id = 0; id < this.getAchievementSize(); id += 1) {
ids += `${id} `;
progress += `${this.achievements[id].progress} `;
}
return {
username: this.player.username,
ids,
progress,
};
}
getData() {
const quests = [];
const achievements = [];
this.forEachQuest((quest) => {
quests.push(quest.getInfo());
});
this.forEachAchievement((achievement) => {
achievements.push(achievement.getInfo());
});
return {
quests,
achievements,
};
}
forEachQuest(callback) {
_.each(this.quests, (quest) => {
callback(quest);
});
}
forEachAchievement(callback) {
_.each(this.achievements, (achievement) => {
callback(achievement);
});
}
getQuestsCompleted() {
let count = 0;
for (const id in this.quests) {
if (this.quests.hasOwnProperty(id)) {
if (this.quests[id].isFinished()) {
count += 1;
}
}
}
return count;
}
getAchievementsCompleted() {
let count = 0;
for (const id in this.achievements) {
if (this.achievements.hasOwnProperty(id)) {
if (this.achievements[id].isFinished()) {
count += 1;
}
}
}
return count;
}
getQuestSize() {
return Object.keys(this.quests).length;
}
getAchievementSize() {
return Object.keys(this.achievements).length;
}
getQuestByNPC(npc) {
/**
* Iterate through the quest list in the order it has been
* added so that NPC's that are required by multiple quests
* follow the proper order.
*/
for (const id in this.quests) {
if (this.quests.hasOwnProperty(id)) {
const quest = this.quests[id];
if (quest.hasNPC(npc.id)) return quest;
}
}
return null;
}
getAchievementByNPC(npc) {
for (const id in this.achievements) {
if (this.achievements.hasOwnProperty(id) && this.achievements[id].data.npc === npc.id
&& !this.achievements[id].isFinished()
) return this.achievements[id];
}
return null;
}
getAchievementByMob(mob) {
for (const id in this.achievements) {
if (this.achievements.hasOwnProperty(id) && this.achievements[id].data.mob === mob.id) {
return this.achievements[id];
}
}
return null;
}
isQuestMob(mob) {
for (const id in this.quests) {
if (this.quests.hasOwnProperty(id)) {
const quest = this.quests[id];
if (!quest.isFinished() && quest.hasMob(mob.id)) {
return true;
}
}
}
return false;
}
isAchievementMob(mob) {
for (const id in this.achievements) {
if (this.achievements.hasOwnProperty(id)) {
if (
this.achievements[id].data.mob === mob.id
&& !this.achievements[id].isFinished()
) return true;
}
}
return false;
}
isQuestNPC(npc) {
for (const id in this.quests) {
if (this.quests.hasOwnProperty(id)) {
const quest = this.quests[id];
if (!quest.isFinished() && quest.hasNPC(npc.id)) {
return true;
}
}
}
return false;
}
isAchievementNPC(npc) {
for (const id in this.achievements) {
if (this.achievements.hasOwnProperty(id)) {
if (
this.achievements[id].data.npc === npc.id
&& !this.achievements[id].isFinished()
) return true;
}
}
return false;
}
onReady(callback) {
this.readyCallback = callback;
}
}
|
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility methods for checking properties of matrices."""
from typing import cast, List, Optional, Sequence, Union, Tuple
import numpy as np
from cirq.linalg import tolerance, transformations
from cirq import value
def is_diagonal(matrix: np.ndarray, *, atol: float = 1e-8) -> bool:
"""Determines if a matrix is a approximately diagonal.
A matrix is diagonal if i!=j implies m[i,j]==0.
Args:
matrix: The matrix to check.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is diagonal within the given tolerance.
"""
matrix = np.copy(matrix)
for i in range(min(matrix.shape)):
matrix[i, i] = 0
return tolerance.all_near_zero(matrix, atol=atol)
def is_hermitian(matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately Hermitian.
A matrix is Hermitian if it's square and equal to its adjoint.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is Hermitian within the given tolerance.
"""
return matrix.shape[0] == matrix.shape[1] and np.allclose(
matrix, np.conj(matrix.T), rtol=rtol, atol=atol
)
def is_orthogonal(matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately orthogonal.
A matrix is orthogonal if it's square and real and its transpose is its
inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is orthogonal within the given tolerance.
"""
return (
matrix.shape[0] == matrix.shape[1]
and np.all(np.imag(matrix) == 0).item()
and np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]), rtol=rtol, atol=atol)
)
def is_special_orthogonal(matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately special orthogonal.
A matrix is special orthogonal if it is square and real and its transpose
is its inverse and its determinant is one.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is special orthogonal within the given tolerance.
"""
return is_orthogonal(matrix, rtol=rtol, atol=atol) and (
matrix.shape[0] == 0 or np.allclose(np.linalg.det(matrix), 1, rtol=rtol, atol=atol)
)
def is_unitary(matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is unitary within the given tolerance.
"""
return matrix.shape[0] == matrix.shape[1] and np.allclose(
matrix.dot(np.conj(matrix.T)), np.eye(matrix.shape[0]), rtol=rtol, atol=atol
)
def is_special_unitary(matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary with unit determinant.
A matrix is special-unitary if it is square and its adjoint is its inverse
and its determinant is one.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is unitary with unit determinant within the given
tolerance.
"""
return is_unitary(matrix, rtol=rtol, atol=atol) and (
matrix.shape[0] == 0 or np.allclose(np.linalg.det(matrix), 1, rtol=rtol, atol=atol)
)
def is_normal(matrix: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately normal.
A matrix is normal if it's square and commutes with its adjoint.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is normal within the given tolerance.
"""
return matrix_commutes(matrix, matrix.T.conj(), rtol=rtol, atol=atol)
def is_cptp(*, kraus_ops: Sequence[np.ndarray], rtol: float = 1e-5, atol: float = 1e-8):
"""Determines if a channel is completely positive trace preserving (CPTP).
A channel composed of Kraus operators K[0:n] is a CPTP map if the sum of
the products `adjoint(K[i]) * K[i])` is equal to 1.
Args:
kraus_ops: The Kraus operators of the channel to check.
rtol: The relative tolerance on equality.
atol: The absolute tolerance on equality.
"""
sum_ndarray = cast(np.ndarray, sum(matrix.T.conj() @ matrix for matrix in kraus_ops))
return np.allclose(sum_ndarray, np.eye(*sum_ndarray.shape), rtol=rtol, atol=atol)
def matrix_commutes(
m1: np.ndarray, m2: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8
) -> bool:
"""Determines if two matrices approximately commute.
Two matrices A and B commute if they are square and have the same size and
AB = BA.
Args:
m1: One of the matrices.
m2: The other matrix.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the two matrices have compatible sizes and a commutator equal
to zero within tolerance.
"""
return (
m1.shape[0] == m1.shape[1]
and m1.shape == m2.shape
and np.allclose(m1.dot(m2), m2.dot(m1), rtol=rtol, atol=atol)
)
def allclose_up_to_global_phase(
a: np.ndarray,
b: np.ndarray,
*,
rtol: float = 1.0e-5,
atol: float = 1.0e-8,
equal_nan: bool = False,
) -> bool:
"""Determines if a ~= b * exp(i t) for some t.
Args:
a: A numpy array.
b: Another numpy array.
rtol: Relative error tolerance.
atol: Absolute error tolerance.
equal_nan: Whether or not NaN entries should be considered equal to
other NaN entries.
"""
if a.shape != b.shape:
return False
a, b = transformations.match_global_phase(a, b)
# Should now be equivalent.
return np.allclose(a=a, b=b, rtol=rtol, atol=atol, equal_nan=equal_nan)
def slice_for_qubits_equal_to(
target_qubit_axes: Sequence[int],
little_endian_qureg_value: int = 0,
*, # Forces keyword args.
big_endian_qureg_value: int = 0,
num_qubits: Optional[int] = None,
qid_shape: Optional[Tuple[int, ...]] = None,
) -> Tuple[Union[slice, int, 'ellipsis'], ...]:
"""Returns an index corresponding to a desired subset of an np.ndarray.
It is assumed that the np.ndarray's shape is of the form (2, 2, 2, ..., 2).
Example:
```python
# A '4 qubit' tensor with values from 0 to 15.
r = np.array(range(16)).reshape((2,) * 4)
# We want to index into the subset where qubit #1 and qubit #3 are ON.
s = cirq.slice_for_qubits_equal_to([1, 3], 0b11)
print(s)
# (slice(None, None, None), 1, slice(None, None, None), 1, Ellipsis)
# Get that subset. It corresponds to numbers of the form 0b*1*1.
# where here '*' indicates any possible value.
print(r[s])
# [[ 5 7]
# [13 15]]
```
Args:
target_qubit_axes: The qubits that are specified by the index bits. All
other axes of the slice are unconstrained.
little_endian_qureg_value: An integer whose bits specify what value is
desired for of the target qubits. The integer is little endian
w.r.t. the target qubit axes, meaning the low bit of the integer
determines the desired value of the first targeted qubit, and so
forth with the k'th targeted qubit's value set to
bool(qureg_value & (1 << k)).
big_endian_qureg_value: Same as `little_endian_qureg_value` but big
endian w.r.t. to target qubit axes, meaning the low bit of the
integer dertemines the desired value of the last target qubit, and
so forth. Specify exactly one of the `*_qureg_value` arguments.
num_qubits: If specified the slices will extend all the way up to
this number of qubits, otherwise if it is None, the final element
return will be Ellipsis. Optional and defaults to using Ellipsis.
qid_shape: The qid shape of the state vector being sliced. Specify this
instead of `num_qubits` when using qids with dimension != 2. The
qureg value is interpreted to store digits with corresponding bases
packed into an int.
Returns:
An index object that will slice out a mutable view of the desired subset
of a tensor.
Raises:
ValueError: If the `qid_shape` mismatches `num_qubits` or exactly one of
`little_endian_qureg_value` and `big_endian_qureg_value` is not
specified.
"""
qid_shape_specified = qid_shape is not None
if qid_shape is not None or num_qubits is not None:
if num_qubits is None:
num_qubits = len(cast(Tuple[int, ...], qid_shape))
elif qid_shape is None:
qid_shape = (2,) * num_qubits
if num_qubits != len(cast(Tuple[int, ...], qid_shape)):
raise ValueError('len(qid_shape) != num_qubits')
if little_endian_qureg_value and big_endian_qureg_value:
raise ValueError(
'Specify exactly one of the arguments little_endian_qureg_value '
'or big_endian_qureg_value.'
)
out_size_specified = num_qubits is not None
out_size = (
cast(int, num_qubits) if out_size_specified else max(target_qubit_axes, default=-1) + 1
)
result = cast(List[Union[slice, int, 'ellipsis']], [slice(None)] * out_size)
if not out_size_specified:
result.append(Ellipsis)
if qid_shape is None:
qid_shape = (2,) * out_size
target_shape = tuple(qid_shape[i] for i in target_qubit_axes)
if big_endian_qureg_value:
digits = value.big_endian_int_to_digits(big_endian_qureg_value, base=target_shape)
else:
if little_endian_qureg_value < 0 and not qid_shape_specified:
# Allow negative binary numbers
little_endian_qureg_value &= (1 << len(target_shape)) - 1
digits = value.big_endian_int_to_digits(little_endian_qureg_value, base=target_shape[::-1])[
::-1
]
for axis, digit in zip(target_qubit_axes, digits):
result[axis] = digit
return tuple(result)
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import "./mock/mockUsrLogin";
import App from './App';
Vue.config.productionTip = false;
Vue.use(ElementUI,{ size: 'medium'});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
|
from simplerpa.core.action.ActionData import ActionData
from simplerpa.core.action.ActionImage import ActionImage
from simplerpa.core.action.ActionScreen import ActionScreen
from simplerpa.core.data.Action import Evaluation
from simplerpa.core.data.ScreenRect import ScreenRect
from simplerpa.core.data.StateBlockBase import StateBlockBase
from simplerpa.core.data.Transition import Transition
from simplerpa.core.detection.ImageDetection import ImageDetection
class PartSplitter(StateBlockBase):
start: ImageDetection = None
end: ImageDetection = None
def split_parts(self, snapshot, image):
image_current = image
if self.start is None and self.end is None:
print("start and end template are all none in splitter '{}'".format(self.name))
return
start_found_list = None
if self.start is not None:
self.start.snapshot = snapshot
start_found_list = self.start.do_detection(image_current)
if start_found_list is None:
print("start template not found in splitter '{}'".format(self.name))
if start_found_list is None:
return None
start_found_list.sort(key=lambda x: x.rect_on_image.top, reverse=False)
end_found_list = None
if self.end is not None:
self.end.snapshot = snapshot
end_found_list = self.end.do_detection(image_current)
if end_found_list is None:
print("end template not found in splitter '{}'".format(self.name))
if end_found_list is None:
return None
end_found_list.sort(key=lambda x: x.rect_on_image.top, reverse=False)
pre_top = None
pre_bottom = None
parts = []
if self.start is not None and self.end is None:
for start_found in start_found_list:
start_top = start_found.rect_on_image.top
if pre_top is not None:
part = image[pre_top:start_top, :]
parts.append(part)
pre_top = start_top
elif self.start is None and self.end is not None:
for end_found in end_found_list:
end_bottom = end_found.rect_on_image.bottom
if pre_bottom is not None:
part = image[pre_bottom:end_bottom, :]
parts.append(part)
pre_bottom = end_bottom
else:
start_len = len(start_found_list)
end_len = len(end_found_list)
start_i = 0
end_i = 0
while True:
start_top = start_found_list[start_i].rect_on_image.top
end_bottom = end_found_list[end_i].rect_on_image.bottom
if start_top >= end_bottom:
end_i += 1
continue
part = image[start_top:end_bottom, :]
parts.append(part)
start_i += 1
end_i += 1
if start_i >= start_len or end_i >= end_len:
break
return parts
class Extractor(StateBlockBase):
snapshot: ScreenRect = None
part_splitter: PartSplitter = None
file: str = "result.csv"
in_data: Evaluation = None
fail: Transition = None
def __init__(self):
self.image = None
self.in_data_dict = None
def prepare(self):
data_dict = self.in_data.call_once()
self.in_data_dict = data_dict
df = ActionData.create_dataframe(data_dict.keys() if data_dict is not None else None)
return df
def do_once(self, image):
raise RuntimeError("do_once method must bu implemented by sub class of Extractor!")
def do(self):
if self.snapshot is None:
raise RuntimeError('There should be a "snapshot" attribute in extractor named "{}"!'.format(self.name))
df = self.prepare()
screen_image = ActionScreen.snapshot(self.snapshot.evaluate())
image_source = ActionImage.pil_to_cv(screen_image)
if self.part_splitter is not None:
image_parts = self.part_splitter.split_parts(self.snapshot, image_source)
if image_parts is None:
return None
for index, part in enumerate(image_parts):
ActionImage.log_image('part-{}'.format(index), part)
data_dict = self.do_once(part)
data_dict.update(self.in_data_dict)
df = df.append(data_dict, ignore_index=True)
else:
data_dict = self.do_once(image_source)
data_dict.update(self.in_data_dict)
df = df.append(data_dict, ignore_index=True)
with open(self.file, 'a', encoding="utf-8", newline='') as f:
df.to_csv(f, header=f.tell() == 0)
return df
|
var slideIndex = [1,1];
var slideId=["fire", "b&w", "nature", "other"];
var dotIndex=[1,1];
var dotId=["fireDot", "b&wDot", "natureDot", "otherDot"];
showDivs(1,0);
showDivs(1,1);
showDivs(0, 2);
showDivs(0, 3);
function plusDivs(n, no) {
showDivs(slideIndex[no] += n, no);
}
function currentDiv(n) {
showDivs(slideIndex[no] = n);
}
function showDivs(n, no) {
var i;
var x = document.getElementsByClassName(slideId[no]);
var dots=document.getElementsByClassName(dotId[no]);
if (n > x.length) {slideIndex[no] = 1}
if (n < 1) {slideIndex[no] = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
for(i=0; i<dots.length; i++){
dots[i].className=dots[i].className.replace("w3-white", "");
}
x[slideIndex[no]-1].style.display = "block";
dots[slideIndex[no]-1].className+=" w3-white";
}
|
sap.ui.define(["sap/ui/test/Opa5",
"sap/suite/ui/generic/template/integration/SalesOrderMultiEntitySets/pages/Common",
"sap/suite/ui/generic/template/integration/SalesOrderMultiEntitySets/pages/actions/ObjectPageActions",
"sap/suite/ui/generic/template/integration/SalesOrderMultiEntitySets/pages/assertions/ObjectPageAssertions"],
function(Opa5, Common, ObjectPageActions, ObjectPageAssertions) {
"use strict";
var VIEWNAME = "Details";
var VIEWNAMESPACE = "sap.suite.ui.generic.template.ObjectPage.view.";
var OP_PREFIX_ID = "SOMULTIENTITY::sap.suite.ui.generic.template.ObjectPage.view.Details::C_STTA_SalesOrder_WD_20--";
var SALESORDER_ENTITY_TYPE = "STTA_SALES_ORDER_WD_20_SRV.C_STTA_SalesOrder_WD_20Type";
var SALESORDER_ENTITY_SET = "C_STTA_SalesOrder_WD_20";
console.log ( "OPA5::ObjectPage::CONSTANTS "
+ " VIEWNAME: " + VIEWNAME
+ " VIEWNAMESPACE: " + VIEWNAMESPACE
+ " OP_PREFIX_ID: " + OP_PREFIX_ID
+ " SALESORDER_ENTITY_TYPE: " + SALESORDER_ENTITY_TYPE
+ " SALESORDER_ENTITY_SET: " + SALESORDER_ENTITY_SET
);
Opa5.createPageObjects({
onTheObjectPage: {
baseClass: Common,
actions: ObjectPageActions(OP_PREFIX_ID, VIEWNAME, VIEWNAMESPACE),
assertions: ObjectPageAssertions(OP_PREFIX_ID, VIEWNAME, VIEWNAMESPACE)
}
});
}
);
|
/*
THIS FILE WAS AUTOGENERATED BY mode_highlight_rules.tmpl.js (UUID: 958518BC-799F-477A-99F9-5B28EBF230F6) */
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DartHighlightRules = function() {
var constantLanguage = "true|false|null";
var variableLanguage = "this|super";
var keywordControl = "try|catch|finally|throw|break|case|continue|default|do|else|for|if|in|return|switch|while|new";
var keywordDeclaration = "abstract|class|extends|external|factory|implements|interface|get|native|operator|set|typedef";
var storageModifier = "static|final|const";
var storageType = "void|bool|num|int|double|Dynamic|var|String";
var keywordMapper = this.createKeywordMapper({
"constant.language.dart": constantLanguage,
"variable.language.dart": variableLanguage,
"keyword.control.dart": keywordControl,
"keyword.declaration.dart": keywordDeclaration,
"storage.modifier.dart": storageModifier,
"storage.type.primitive.dart": storageType
}, "identifier");
var stringfill = {
token : "string",
regex : ".+"
};
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules =
{
"start": [
{
token : "comment",
regex : /\/\/.*$/
},
{
token : "comment", // multi line comment
regex : /\/\*/,
next : "comment"
},
{
token: ["meta.preprocessor.script.dart"],
regex: "^(#!.*)$"
},
{
token: "keyword.other.import.dart",
regex: "#(?:\\b)(?:library|import|source|resource)(?:\\b)"
},
{
token : ["keyword.other.import.dart", "text"],
regex : "(?:\\b)(prefix)(\\s*:)"
},
{
regex: "\\bas\\b",
token: "keyword.cast.dart"
},
{
regex: "\\?|:",
token: "keyword.control.ternary.dart"
},
{
regex: "(?:\\b)(is\\!?)(?:\\b)",
token: ["keyword.operator.dart"]
},
{
regex: "(<<|>>>?|~|\\^|\\||&)",
token: ["keyword.operator.bitwise.dart"]
},
{
regex: "((?:&|\\^|\\||<<|>>>?)=)",
token: ["keyword.operator.assignment.bitwise.dart"]
},
{
regex: "(===?|!==?|<=?|>=?)",
token: ["keyword.operator.comparison.dart"]
},
{
regex: "((?:[+*/%-]|\\~)=)",
token: ["keyword.operator.assignment.arithmetic.dart"]
},
{
regex: "=",
token: "keyword.operator.assignment.dart"
},
{
token : "string",
regex : "'''",
next : "qdoc"
},
{
token : "string",
regex : '"""',
next : "qqdoc"
},
{
token : "string",
regex : "'",
next : "qstring"
},
{
token : "string",
regex : '"',
next : "qqstring"
},
{
regex: "(\\-\\-|\\+\\+)",
token: ["keyword.operator.increment-decrement.dart"]
},
{
regex: "(\\-|\\+|\\*|\\/|\\~\\/|%)",
token: ["keyword.operator.arithmetic.dart"]
},
{
regex: "(!|&&|\\|\\|)",
token: ["keyword.operator.logical.dart"]
},
{
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
},
{
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
},
{
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
],
"qdoc" : [
{
token : "string",
regex : ".*?'''",
next : "start"
}, stringfill],
"qqdoc" : [
{
token : "string",
regex : '.*?"""',
next : "start"
}, stringfill],
"qstring" : [
{
token : "string",
regex : "[^\\\\']*(?:\\\\.[^\\\\']*)*'",
next : "start"
}, stringfill],
"qqstring" : [
{
token : "string",
regex : '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',
next : "start"
}, stringfill]
}
};
oop.inherits(DartHighlightRules, TextHighlightRules);
exports.DartHighlightRules = DartHighlightRules;
});
|
import React from 'react';
import { Icon } from './Icon';
export var RoundFiberSmartRecord =
/*#__PURE__*/
function RoundFiberSmartRecord(props) {
return React.createElement(Icon, props, React.createElement("circle", {
cx: "9",
cy: "12",
r: "8"
}), React.createElement("path", {
d: "M17 5.55v.18c0 .37.23.69.57.85C19.6 7.54 21 9.61 21 12s-1.4 4.46-3.43 5.42c-.34.16-.57.47-.57.84v.18c0 .68.71 1.11 1.32.82C21.08 18.01 23 15.23 23 12s-1.92-6.01-4.68-7.27c-.61-.28-1.32.14-1.32.82z"
}));
}; |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._enums import *
__all__ = [
'AssignmentInfoResponse',
'AssignmentReportResourceComplianceReasonResponse',
'AssignmentReportResourceResponse',
'AssignmentReportResponse',
'ConfigurationInfoResponse',
'ConfigurationParameterResponse',
'ConfigurationSettingResponse',
'GuestConfigurationAssignmentPropertiesResponse',
'GuestConfigurationNavigationResponse',
'VMInfoResponse',
]
@pulumi.output_type
class AssignmentInfoResponse(dict):
"""
Information about the guest configuration assignment.
"""
def __init__(__self__, *,
name: str,
configuration: Optional['outputs.ConfigurationInfoResponse'] = None):
"""
Information about the guest configuration assignment.
:param str name: Name of the guest configuration assignment.
:param 'ConfigurationInfoResponse' configuration: Information about the configuration.
"""
pulumi.set(__self__, "name", name)
if configuration is not None:
pulumi.set(__self__, "configuration", configuration)
@property
@pulumi.getter
def name(self) -> str:
"""
Name of the guest configuration assignment.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def configuration(self) -> Optional['outputs.ConfigurationInfoResponse']:
"""
Information about the configuration.
"""
return pulumi.get(self, "configuration")
@pulumi.output_type
class AssignmentReportResourceComplianceReasonResponse(dict):
"""
Reason and code for the compliance of the guest configuration assignment resource.
"""
def __init__(__self__, *,
code: str,
phrase: str):
"""
Reason and code for the compliance of the guest configuration assignment resource.
:param str code: Code for the compliance of the guest configuration assignment resource.
:param str phrase: Reason for the compliance of the guest configuration assignment resource.
"""
pulumi.set(__self__, "code", code)
pulumi.set(__self__, "phrase", phrase)
@property
@pulumi.getter
def code(self) -> str:
"""
Code for the compliance of the guest configuration assignment resource.
"""
return pulumi.get(self, "code")
@property
@pulumi.getter
def phrase(self) -> str:
"""
Reason for the compliance of the guest configuration assignment resource.
"""
return pulumi.get(self, "phrase")
@pulumi.output_type
class AssignmentReportResourceResponse(dict):
"""
The guest configuration assignment resource.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "complianceStatus":
suggest = "compliance_status"
elif key == "resourceId":
suggest = "resource_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in AssignmentReportResourceResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
AssignmentReportResourceResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
AssignmentReportResourceResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
compliance_status: str,
properties: Any,
resource_id: str,
reasons: Optional[Sequence['outputs.AssignmentReportResourceComplianceReasonResponse']] = None):
"""
The guest configuration assignment resource.
:param str compliance_status: A value indicating compliance status of the machine for the assigned guest configuration.
:param Any properties: Properties of a guest configuration assignment resource.
:param str resource_id: Name of the guest configuration assignment resource setting.
:param Sequence['AssignmentReportResourceComplianceReasonResponse'] reasons: Compliance reason and reason code for a resource.
"""
pulumi.set(__self__, "compliance_status", compliance_status)
pulumi.set(__self__, "properties", properties)
pulumi.set(__self__, "resource_id", resource_id)
if reasons is not None:
pulumi.set(__self__, "reasons", reasons)
@property
@pulumi.getter(name="complianceStatus")
def compliance_status(self) -> str:
"""
A value indicating compliance status of the machine for the assigned guest configuration.
"""
return pulumi.get(self, "compliance_status")
@property
@pulumi.getter
def properties(self) -> Any:
"""
Properties of a guest configuration assignment resource.
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter(name="resourceId")
def resource_id(self) -> str:
"""
Name of the guest configuration assignment resource setting.
"""
return pulumi.get(self, "resource_id")
@property
@pulumi.getter
def reasons(self) -> Optional[Sequence['outputs.AssignmentReportResourceComplianceReasonResponse']]:
"""
Compliance reason and reason code for a resource.
"""
return pulumi.get(self, "reasons")
@pulumi.output_type
class AssignmentReportResponse(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "complianceStatus":
suggest = "compliance_status"
elif key == "endTime":
suggest = "end_time"
elif key == "operationType":
suggest = "operation_type"
elif key == "reportId":
suggest = "report_id"
elif key == "startTime":
suggest = "start_time"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in AssignmentReportResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
AssignmentReportResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
AssignmentReportResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
compliance_status: str,
end_time: str,
id: str,
operation_type: str,
report_id: str,
start_time: str,
assignment: Optional['outputs.AssignmentInfoResponse'] = None,
resources: Optional[Sequence['outputs.AssignmentReportResourceResponse']] = None,
vm: Optional['outputs.VMInfoResponse'] = None):
"""
:param str compliance_status: A value indicating compliance status of the machine for the assigned guest configuration.
:param str end_time: End date and time of the guest configuration assignment compliance status check.
:param str id: ARM resource id of the report for the guest configuration assignment.
:param str operation_type: Type of report, Consistency or Initial
:param str report_id: GUID that identifies the guest configuration assignment report under a subscription, resource group.
:param str start_time: Start date and time of the guest configuration assignment compliance status check.
:param 'AssignmentInfoResponse' assignment: Configuration details of the guest configuration assignment.
:param Sequence['AssignmentReportResourceResponse'] resources: The list of resources for which guest configuration assignment compliance is checked.
:param 'VMInfoResponse' vm: Information about the VM.
"""
pulumi.set(__self__, "compliance_status", compliance_status)
pulumi.set(__self__, "end_time", end_time)
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "operation_type", operation_type)
pulumi.set(__self__, "report_id", report_id)
pulumi.set(__self__, "start_time", start_time)
if assignment is not None:
pulumi.set(__self__, "assignment", assignment)
if resources is not None:
pulumi.set(__self__, "resources", resources)
if vm is not None:
pulumi.set(__self__, "vm", vm)
@property
@pulumi.getter(name="complianceStatus")
def compliance_status(self) -> str:
"""
A value indicating compliance status of the machine for the assigned guest configuration.
"""
return pulumi.get(self, "compliance_status")
@property
@pulumi.getter(name="endTime")
def end_time(self) -> str:
"""
End date and time of the guest configuration assignment compliance status check.
"""
return pulumi.get(self, "end_time")
@property
@pulumi.getter
def id(self) -> str:
"""
ARM resource id of the report for the guest configuration assignment.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="operationType")
def operation_type(self) -> str:
"""
Type of report, Consistency or Initial
"""
return pulumi.get(self, "operation_type")
@property
@pulumi.getter(name="reportId")
def report_id(self) -> str:
"""
GUID that identifies the guest configuration assignment report under a subscription, resource group.
"""
return pulumi.get(self, "report_id")
@property
@pulumi.getter(name="startTime")
def start_time(self) -> str:
"""
Start date and time of the guest configuration assignment compliance status check.
"""
return pulumi.get(self, "start_time")
@property
@pulumi.getter
def assignment(self) -> Optional['outputs.AssignmentInfoResponse']:
"""
Configuration details of the guest configuration assignment.
"""
return pulumi.get(self, "assignment")
@property
@pulumi.getter
def resources(self) -> Optional[Sequence['outputs.AssignmentReportResourceResponse']]:
"""
The list of resources for which guest configuration assignment compliance is checked.
"""
return pulumi.get(self, "resources")
@property
@pulumi.getter
def vm(self) -> Optional['outputs.VMInfoResponse']:
"""
Information about the VM.
"""
return pulumi.get(self, "vm")
@pulumi.output_type
class ConfigurationInfoResponse(dict):
"""
Information about the configuration.
"""
def __init__(__self__, *,
name: str,
version: str):
"""
Information about the configuration.
:param str name: Name of the configuration.
:param str version: Version of the configuration.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "version", version)
@property
@pulumi.getter
def name(self) -> str:
"""
Name of the configuration.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def version(self) -> str:
"""
Version of the configuration.
"""
return pulumi.get(self, "version")
@pulumi.output_type
class ConfigurationParameterResponse(dict):
"""
Represents a configuration parameter.
"""
def __init__(__self__, *,
name: Optional[str] = None,
value: Optional[str] = None):
"""
Represents a configuration parameter.
:param str name: Name of the configuration parameter.
:param str value: Value of the configuration parameter.
"""
if name is not None:
pulumi.set(__self__, "name", name)
if value is not None:
pulumi.set(__self__, "value", value)
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
Name of the configuration parameter.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def value(self) -> Optional[str]:
"""
Value of the configuration parameter.
"""
return pulumi.get(self, "value")
@pulumi.output_type
class ConfigurationSettingResponse(dict):
"""
Configuration setting of LCM (Local Configuration Manager).
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "actionAfterReboot":
suggest = "action_after_reboot"
elif key == "allowModuleOverwrite":
suggest = "allow_module_overwrite"
elif key == "configurationMode":
suggest = "configuration_mode"
elif key == "configurationModeFrequencyMins":
suggest = "configuration_mode_frequency_mins"
elif key == "rebootIfNeeded":
suggest = "reboot_if_needed"
elif key == "refreshFrequencyMins":
suggest = "refresh_frequency_mins"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in ConfigurationSettingResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
ConfigurationSettingResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
ConfigurationSettingResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
action_after_reboot: Optional[str] = None,
allow_module_overwrite: Optional[bool] = None,
configuration_mode: Optional[str] = None,
configuration_mode_frequency_mins: Optional[float] = None,
reboot_if_needed: Optional[bool] = None,
refresh_frequency_mins: Optional[float] = None):
"""
Configuration setting of LCM (Local Configuration Manager).
:param str action_after_reboot: Specifies what happens after a reboot during the application of a configuration. The possible values are ContinueConfiguration and StopConfiguration
:param bool allow_module_overwrite: If true - new configurations downloaded from the pull service are allowed to overwrite the old ones on the target node. Otherwise, false
:param str configuration_mode: Specifies how the LCM(Local Configuration Manager) actually applies the configuration to the target nodes. Possible values are ApplyOnly, ApplyAndMonitor, and ApplyAndAutoCorrect.
:param float configuration_mode_frequency_mins: How often, in minutes, the current configuration is checked and applied. This property is ignored if the ConfigurationMode property is set to ApplyOnly. The default value is 15.
:param bool reboot_if_needed: Set this to true to automatically reboot the node after a configuration that requires reboot is applied. Otherwise, you will have to manually reboot the node for any configuration that requires it. The default value is false. To use this setting when a reboot condition is enacted by something other than DSC (such as Windows Installer), combine this setting with the xPendingReboot module.
:param float refresh_frequency_mins: The time interval, in minutes, at which the LCM checks a pull service to get updated configurations. This value is ignored if the LCM is not configured in pull mode. The default value is 30.
"""
if action_after_reboot is not None:
pulumi.set(__self__, "action_after_reboot", action_after_reboot)
if allow_module_overwrite is not None:
pulumi.set(__self__, "allow_module_overwrite", allow_module_overwrite)
if configuration_mode is not None:
pulumi.set(__self__, "configuration_mode", configuration_mode)
if configuration_mode_frequency_mins is None:
configuration_mode_frequency_mins = 15
if configuration_mode_frequency_mins is not None:
pulumi.set(__self__, "configuration_mode_frequency_mins", configuration_mode_frequency_mins)
if reboot_if_needed is not None:
pulumi.set(__self__, "reboot_if_needed", reboot_if_needed)
if refresh_frequency_mins is None:
refresh_frequency_mins = 30
if refresh_frequency_mins is not None:
pulumi.set(__self__, "refresh_frequency_mins", refresh_frequency_mins)
@property
@pulumi.getter(name="actionAfterReboot")
def action_after_reboot(self) -> Optional[str]:
"""
Specifies what happens after a reboot during the application of a configuration. The possible values are ContinueConfiguration and StopConfiguration
"""
return pulumi.get(self, "action_after_reboot")
@property
@pulumi.getter(name="allowModuleOverwrite")
def allow_module_overwrite(self) -> Optional[bool]:
"""
If true - new configurations downloaded from the pull service are allowed to overwrite the old ones on the target node. Otherwise, false
"""
return pulumi.get(self, "allow_module_overwrite")
@property
@pulumi.getter(name="configurationMode")
def configuration_mode(self) -> Optional[str]:
"""
Specifies how the LCM(Local Configuration Manager) actually applies the configuration to the target nodes. Possible values are ApplyOnly, ApplyAndMonitor, and ApplyAndAutoCorrect.
"""
return pulumi.get(self, "configuration_mode")
@property
@pulumi.getter(name="configurationModeFrequencyMins")
def configuration_mode_frequency_mins(self) -> Optional[float]:
"""
How often, in minutes, the current configuration is checked and applied. This property is ignored if the ConfigurationMode property is set to ApplyOnly. The default value is 15.
"""
return pulumi.get(self, "configuration_mode_frequency_mins")
@property
@pulumi.getter(name="rebootIfNeeded")
def reboot_if_needed(self) -> Optional[bool]:
"""
Set this to true to automatically reboot the node after a configuration that requires reboot is applied. Otherwise, you will have to manually reboot the node for any configuration that requires it. The default value is false. To use this setting when a reboot condition is enacted by something other than DSC (such as Windows Installer), combine this setting with the xPendingReboot module.
"""
return pulumi.get(self, "reboot_if_needed")
@property
@pulumi.getter(name="refreshFrequencyMins")
def refresh_frequency_mins(self) -> Optional[float]:
"""
The time interval, in minutes, at which the LCM checks a pull service to get updated configurations. This value is ignored if the LCM is not configured in pull mode. The default value is 30.
"""
return pulumi.get(self, "refresh_frequency_mins")
@pulumi.output_type
class GuestConfigurationAssignmentPropertiesResponse(dict):
"""
Guest configuration assignment properties.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "assignmentHash":
suggest = "assignment_hash"
elif key == "complianceStatus":
suggest = "compliance_status"
elif key == "lastComplianceStatusChecked":
suggest = "last_compliance_status_checked"
elif key == "latestReportId":
suggest = "latest_report_id"
elif key == "provisioningState":
suggest = "provisioning_state"
elif key == "targetResourceId":
suggest = "target_resource_id"
elif key == "guestConfiguration":
suggest = "guest_configuration"
elif key == "latestAssignmentReport":
suggest = "latest_assignment_report"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in GuestConfigurationAssignmentPropertiesResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
GuestConfigurationAssignmentPropertiesResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
GuestConfigurationAssignmentPropertiesResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
assignment_hash: str,
compliance_status: str,
last_compliance_status_checked: str,
latest_report_id: str,
provisioning_state: str,
target_resource_id: str,
context: Optional[str] = None,
guest_configuration: Optional['outputs.GuestConfigurationNavigationResponse'] = None,
latest_assignment_report: Optional['outputs.AssignmentReportResponse'] = None):
"""
Guest configuration assignment properties.
:param str assignment_hash: Combined hash of the configuration package and parameters.
:param str compliance_status: A value indicating compliance status of the machine for the assigned guest configuration.
:param str last_compliance_status_checked: Date and time when last compliance status was checked.
:param str latest_report_id: Id of the latest report for the guest configuration assignment.
:param str provisioning_state: The provisioning state, which only appears in the response.
:param str target_resource_id: VM resource Id.
:param str context: The source which initiated the guest configuration assignment. Ex: Azure Policy
:param 'GuestConfigurationNavigationResponse' guest_configuration: The guest configuration to assign.
:param 'AssignmentReportResponse' latest_assignment_report: Last reported guest configuration assignment report.
"""
pulumi.set(__self__, "assignment_hash", assignment_hash)
pulumi.set(__self__, "compliance_status", compliance_status)
pulumi.set(__self__, "last_compliance_status_checked", last_compliance_status_checked)
pulumi.set(__self__, "latest_report_id", latest_report_id)
pulumi.set(__self__, "provisioning_state", provisioning_state)
pulumi.set(__self__, "target_resource_id", target_resource_id)
if context is not None:
pulumi.set(__self__, "context", context)
if guest_configuration is not None:
pulumi.set(__self__, "guest_configuration", guest_configuration)
if latest_assignment_report is not None:
pulumi.set(__self__, "latest_assignment_report", latest_assignment_report)
@property
@pulumi.getter(name="assignmentHash")
def assignment_hash(self) -> str:
"""
Combined hash of the configuration package and parameters.
"""
return pulumi.get(self, "assignment_hash")
@property
@pulumi.getter(name="complianceStatus")
def compliance_status(self) -> str:
"""
A value indicating compliance status of the machine for the assigned guest configuration.
"""
return pulumi.get(self, "compliance_status")
@property
@pulumi.getter(name="lastComplianceStatusChecked")
def last_compliance_status_checked(self) -> str:
"""
Date and time when last compliance status was checked.
"""
return pulumi.get(self, "last_compliance_status_checked")
@property
@pulumi.getter(name="latestReportId")
def latest_report_id(self) -> str:
"""
Id of the latest report for the guest configuration assignment.
"""
return pulumi.get(self, "latest_report_id")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> str:
"""
The provisioning state, which only appears in the response.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="targetResourceId")
def target_resource_id(self) -> str:
"""
VM resource Id.
"""
return pulumi.get(self, "target_resource_id")
@property
@pulumi.getter
def context(self) -> Optional[str]:
"""
The source which initiated the guest configuration assignment. Ex: Azure Policy
"""
return pulumi.get(self, "context")
@property
@pulumi.getter(name="guestConfiguration")
def guest_configuration(self) -> Optional['outputs.GuestConfigurationNavigationResponse']:
"""
The guest configuration to assign.
"""
return pulumi.get(self, "guest_configuration")
@property
@pulumi.getter(name="latestAssignmentReport")
def latest_assignment_report(self) -> Optional['outputs.AssignmentReportResponse']:
"""
Last reported guest configuration assignment report.
"""
return pulumi.get(self, "latest_assignment_report")
@pulumi.output_type
class GuestConfigurationNavigationResponse(dict):
"""
Guest configuration is an artifact that encapsulates DSC configuration and its dependencies. The artifact is a zip file containing DSC configuration (as MOF) and dependent resources and other dependencies like modules.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "assignmentType":
suggest = "assignment_type"
elif key == "configurationParameter":
suggest = "configuration_parameter"
elif key == "configurationSetting":
suggest = "configuration_setting"
elif key == "contentHash":
suggest = "content_hash"
elif key == "contentUri":
suggest = "content_uri"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in GuestConfigurationNavigationResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
GuestConfigurationNavigationResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
GuestConfigurationNavigationResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
assignment_type: Optional[str] = None,
configuration_parameter: Optional[Sequence['outputs.ConfigurationParameterResponse']] = None,
configuration_setting: Optional['outputs.ConfigurationSettingResponse'] = None,
content_hash: Optional[str] = None,
content_uri: Optional[str] = None,
kind: Optional[str] = None,
name: Optional[str] = None,
version: Optional[str] = None):
"""
Guest configuration is an artifact that encapsulates DSC configuration and its dependencies. The artifact is a zip file containing DSC configuration (as MOF) and dependent resources and other dependencies like modules.
:param str assignment_type: Specifies the assignment type and execution of the configuration. Possible values are Audit, DeployAndAutoCorrect, ApplyAndAutoCorrect and ApplyAndMonitor.
:param Sequence['ConfigurationParameterResponse'] configuration_parameter: The configuration parameters for the guest configuration.
:param 'ConfigurationSettingResponse' configuration_setting: The configuration setting for the guest configuration.
:param str content_hash: Combined hash of the guest configuration package and configuration parameters.
:param str content_uri: Uri of the storage where guest configuration package is uploaded.
:param str kind: Kind of the guest configuration. For example:DSC
:param str name: Name of the guest configuration.
:param str version: Version of the guest configuration.
"""
if assignment_type is not None:
pulumi.set(__self__, "assignment_type", assignment_type)
if configuration_parameter is not None:
pulumi.set(__self__, "configuration_parameter", configuration_parameter)
if configuration_setting is not None:
pulumi.set(__self__, "configuration_setting", configuration_setting)
if content_hash is not None:
pulumi.set(__self__, "content_hash", content_hash)
if content_uri is not None:
pulumi.set(__self__, "content_uri", content_uri)
if kind is not None:
pulumi.set(__self__, "kind", kind)
if name is not None:
pulumi.set(__self__, "name", name)
if version is not None:
pulumi.set(__self__, "version", version)
@property
@pulumi.getter(name="assignmentType")
def assignment_type(self) -> Optional[str]:
"""
Specifies the assignment type and execution of the configuration. Possible values are Audit, DeployAndAutoCorrect, ApplyAndAutoCorrect and ApplyAndMonitor.
"""
return pulumi.get(self, "assignment_type")
@property
@pulumi.getter(name="configurationParameter")
def configuration_parameter(self) -> Optional[Sequence['outputs.ConfigurationParameterResponse']]:
"""
The configuration parameters for the guest configuration.
"""
return pulumi.get(self, "configuration_parameter")
@property
@pulumi.getter(name="configurationSetting")
def configuration_setting(self) -> Optional['outputs.ConfigurationSettingResponse']:
"""
The configuration setting for the guest configuration.
"""
return pulumi.get(self, "configuration_setting")
@property
@pulumi.getter(name="contentHash")
def content_hash(self) -> Optional[str]:
"""
Combined hash of the guest configuration package and configuration parameters.
"""
return pulumi.get(self, "content_hash")
@property
@pulumi.getter(name="contentUri")
def content_uri(self) -> Optional[str]:
"""
Uri of the storage where guest configuration package is uploaded.
"""
return pulumi.get(self, "content_uri")
@property
@pulumi.getter
def kind(self) -> Optional[str]:
"""
Kind of the guest configuration. For example:DSC
"""
return pulumi.get(self, "kind")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
Name of the guest configuration.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def version(self) -> Optional[str]:
"""
Version of the guest configuration.
"""
return pulumi.get(self, "version")
@pulumi.output_type
class VMInfoResponse(dict):
"""
Information about the VM.
"""
def __init__(__self__, *,
id: str,
uuid: str):
"""
Information about the VM.
:param str id: Azure resource Id of the VM.
:param str uuid: UUID(Universally Unique Identifier) of the VM.
"""
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "uuid", uuid)
@property
@pulumi.getter
def id(self) -> str:
"""
Azure resource Id of the VM.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def uuid(self) -> str:
"""
UUID(Universally Unique Identifier) of the VM.
"""
return pulumi.get(self, "uuid")
|
/**
* Created by Ziga & Primoz on 1.4.2016.
*/
import {Camera} from '../cameras/Camera.js';
export class PerspectiveCamera extends Camera {
/**
* Create new PerspectiveCamera object.
*
* @param fov Vertical field of view given in degrees.
* @param aspect Aspect ratio (width / height).
* @param near Distance to the near clipping plane of the projection camera frustum.
* @param far Distance to the far clipping plane of the projection camera frustum.
*/
//Modified by Sebastien
constructor(fov, aspect, near, far, left = undefined, right = undefined, top = undefined, bottom = undefined) {
super(Camera);
this.type = "PerspectiveCamera";
this._fov = fov || 50;
this._aspect = aspect || 1;
this._near = near || 0.1;
this._far = far || 1000;
//Added by Sebastien
this._top = top || this._near * Math.tan((Math.PI/180) * 0.5 * this._fov);
this._bottom = bottom || -this._top;
this._left = left || -0.5 * (this._aspect * (2 * this._top));
this._right = right || -this._left;
this.updateProjectionMatrix();
}
/**
* Update projection matrix based on current values of properties.
*/
updateProjectionMatrix() {
//Modified by Sebastien
/*let top = this._near * Math.tan((Math.PI/180) * 0.5 * this._fov),
height = 2 * top,
width = this._aspect * height,
left = - 0.5 * width;
this.projectionMatrix.makePerspective(left, left + width, top, top - height, this._near, this._far);*/
this.projectionMatrix.makePerspective(this._left, this._right, this._top, this._bottom, this._near, this._far);
}
_updateTBLR(){
this._top = this._near * Math.tan((Math.PI/180) * 0.5 * this._fov);
this._bottom = -this._top;
this._updateLR();
}
_updateLR(){
this._left = -0.5 * (this._aspect * (2 * this._top));
this._right = -this._left;
}
/**
* Get field of view.
*
* @returns Field of view.
*/
get fov() { return this._fov; }
/**
* Get aspect ratio.
*
* @returns Aspect ratio.
*/
get aspect() { return this._aspect; }
/**
* Get distance to the near clipping plane.
*
* @returns Distance to the near clipping plane.
*/
get near() { return this._near; }
/**
* Get distance to the far clipping plane.
*
* @returns Distance to the far clipping plane.
*/
get far() { return this._far; }
//Added by Sebastien
get left() { return this._left; }
get right() { return this._right; }
get top() { return this._top; }
get bottom() { return this._bottom; }
/**
* Set field of view.
*
* @param val Field of view to be set.
*/
set fov(val) {
if (val !== this._fov) {
this._fov = val;
this._updateTBLR(); //Added by Sebastien
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {fov: this._fov}};
this._onChangeListener.objectUpdate(update)
}
}
}
/**
* Set aspect ratio.
*
* @param val Aspect ratio to be set.
*/
set aspect(val) {
if (val !== this._aspect) {
this._aspect = val;
this._updateLR(); //Added by Sebastien
this.updateProjectionMatrix();
}
}
/**
* Set distance to the near clipping plane.
*
* @param val Distance to the near clipping plane to be set.
*/
set near(val) {
if (val !== this._near) {
this._near = val;
this._updateTBLR(); //Added by Sebastien
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {near: this._near}};
this._onChangeListener.objectUpdate(update)
}
}
}
/**
* Set distance to the far clipping plane.
*
* @param val Distance to the far clipping plane to be set.
*/
set far(val) {
if (val !== this._far) {
this._far = val;
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {far: this._far}};
this._onChangeListener.objectUpdate(update)
}
}
}
//Added by Sebastien
set left(val) {
if (val !== this._left) {
this._left = val;
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {left: this._left}};
this._onChangeListener.objectUpdate(update)
}
}
}
set right(val) {
if (val !== this._right) {
this._right = val;
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {right: this._right}};
this._onChangeListener.objectUpdate(update)
}
}
}
set top(val) {
if (val !== this._top) {
this._top = val;
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {top: this._top}};
this._onChangeListener.objectUpdate(update)
}
}
}
set bottom(val) {
if (val !== this._bottom) {
this._bottom = val;
this.updateProjectionMatrix();
// Notify onChange subscriber
if (this._onChangeListener) {
var update = {uuid: this._uuid, changes: {bottom: this._bottom}};
this._onChangeListener.objectUpdate(update)
}
}
}
/**
* Serialize object to JSON.
*
* @returns JSON object.
*/
toJson() {
// Export Object3D parameters
var obj = super.toJson();
// Export perspective camera parameters
obj.fov = this._fov;
obj.near = this._near;
obj.far = this._far;
return obj;
}
/**
* Create a new camera from the JSON data.
*
* @param data JSON data.
* @param aspect Aspect ratio.
*/
static fromJson(data, aspect) {
// Create new object with the given camera parameters
var camera = new PerspectiveCamera(data.fov, aspect, data.near, data.far);
// Import underlying Object3D parameters
return super.fromJson(data, camera);
}
/**
* Updates the camera with settings from data.
*
* @param data Update data.
*/
update(data) {
super.update(data);
// Check if there are any camera parameter updates
var modified = false;
for (var prop in data) {
switch (prop) {
case "fov":
this._fov = data.fov;
delete data.fov;
modified = true;
break;
case "near":
this._near = data.near;
delete data.near;
modified = true;
break;
case "far":
this._far = data.far;
delete data.far;
modified = true;
break;
case "left":
this._left = data.left;
delete data.left;
modified = true;
break;
case "right":
this._right = data.right;
delete data.right;
modified = true;
break;
case "top":
this._top = data.top;
delete data.top;
modified = true;
break;
case "bottom":
this._bottom = data.bottom;
delete data.bottom;
modified = true;
break;
}
}
// If the camera parameters have been modified update the projection matrix
if (modified) {
this.updateProjectionMatrix();
}
}
}; |
import React, { useState, createContext } from "react";
import API from "../utils/API";
export const LoginStatusContext = createContext();
export const LoginStatusProvider = ({ children }) => {
const [loginState, setLoginState] = useState(false)
function authenticateLogin (id, input) {
API.authLogin(id, input)
.then(res => {
if (res.data) {setLoginState(true)}
})
}
function logout () {
setLoginState(false)
}
return (
<LoginStatusContext.Provider value={{loginState, authenticateLogin, logout}}>
{children}
</LoginStatusContext.Provider>
);
};
|
var mock = require('mock-fs');
var assert = require('../helper').assert;
var util = require('../../lib/util');
describe('util', function() {
function nullOverride(filePath, time, include) {
include(false);
}
describe('filterPathsByTime()', function() {
beforeEach(function() {
mock({
src: {
js: {
'a.js': mock.file({
mtime: new Date(100)
}),
'b.js': mock.file({
mtime: new Date(200)
}),
'c.js': mock.file({
mtime: new Date(300)
})
}
}
});
});
afterEach(mock.restore);
it('calls callback with files newer than provided time', function(done) {
var paths = [
'src/js/a.js',
'src/js/b.js',
'src/js/c.js'
];
util.filterPathsByTime(paths, new Date(150), nullOverride,
function(err, results) {
if (err) {
return done(err);
}
assert.equal(results.length, 2);
assert.deepEqual(results.sort(), ['src/js/b.js', 'src/js/c.js']);
done();
});
});
it('calls override with older files and comparison time', function(done) {
var paths = [
'src/js/a.js',
'src/js/b.js',
'src/js/c.js'
];
function customOverride(filePath, time, include) {
assert.equal(filePath, 'src/js/a.js');
assert.equal(time.getTime(), 150);
include(false);
}
util.filterPathsByTime(paths, new Date(150), customOverride,
function(err, results) {
if (err) {
return done(err);
}
assert.equal(results.length, 2);
assert.deepEqual(results.sort(), ['src/js/b.js', 'src/js/c.js']);
done();
});
});
it('allows override to force inclusion of older files', function(done) {
var paths = [
'src/js/a.js',
'src/js/b.js',
'src/js/c.js'
];
function customOverride(filePath, time, include) {
assert.equal(filePath, 'src/js/a.js');
assert.equal(time.getTime(), 150);
include(true);
}
util.filterPathsByTime(paths, new Date(150), customOverride,
function(err, results) {
if (err) {
return done(err);
}
assert.equal(results.length, 3);
assert.deepEqual(results.sort(),
['src/js/a.js', 'src/js/b.js', 'src/js/c.js']);
done();
});
});
it('calls callback error if file not found', function(done) {
var paths = [
'src/bogus-file.js'
];
util.filterPathsByTime(paths, new Date(150), nullOverride,
function(err, results) {
assert.instanceOf(err, Error);
assert.equal(results, undefined);
done();
});
});
});
describe('anyNewer()', function() {
beforeEach(function() {
mock({
src: {
js: {
'a.js': mock.file({
mtime: new Date(100)
}),
'b.js': mock.file({
mtime: new Date(200)
}),
'c.js': mock.file({
mtime: new Date(300)
})
}
}
});
});
afterEach(mock.restore);
var paths = [
'src/js/a.js',
'src/js/b.js',
'src/js/c.js'
];
it('calls callback with true if any file is newer', function(done) {
util.anyNewer(paths, new Date(250), nullOverride, function(err, newer) {
if (err) {
return done(err);
}
assert.isTrue(newer);
done();
});
});
it('does not call override if all files are newer', function(done) {
function override(filePath, time, include) {
done(new Error('Override should not be called'));
}
util.anyNewer(paths, new Date(1), override, function(err, newer) {
if (err) {
return done(err);
}
assert.isTrue(newer);
done();
});
});
it('calls callback with false if no files are newer', function(done) {
util.anyNewer(paths, new Date(350), nullOverride, function(err, newer) {
if (err) {
return done(err);
}
assert.isFalse(newer);
done();
});
});
it('calls callback with false if no files are provided', function(done) {
util.anyNewer([], new Date(), nullOverride, function(err, newer) {
if (err) {
return done(err);
}
assert.isFalse(newer);
done();
});
});
it('calls override with older file and time', function(done) {
function override(filePath, time, include) {
assert.equal(filePath, 'src/js/a.js');
assert.equal(time.getTime(), 150);
include(false);
}
util.anyNewer(paths, new Date(150), override, function(err, newer) {
if (err) {
return done(err);
}
assert.isTrue(newer);
done();
});
});
it('allows override to force inclusion of older files', function(done) {
function override(filePath, time, include) {
include(true);
}
util.anyNewer(paths, new Date(1000), override, function(err, newer) {
if (err) {
return done(err);
}
assert.isTrue(newer);
done();
});
});
it('calls callback with error if file not found', function(done) {
util.anyNewer(['bogus/file.js'], new Date(350), nullOverride,
function(err, newer) {
assert.instanceOf(err, Error);
assert.equal(newer, undefined);
done();
});
});
});
describe('filterFilesByTime()', function() {
beforeEach(function() {
mock({
src: {
js: {
'a.js': mock.file({
mtime: new Date(100)
}),
'b.js': mock.file({
mtime: new Date(200)
}),
'c.js': mock.file({
mtime: new Date(300)
})
},
less: {
'one.less': mock.file({mtime: new Date(100)}),
'two.less': mock.file({mtime: new Date(200)})
}
},
dest: {
js: {
'abc.min.js': mock.file({
mtime: new Date(200)
})
},
css: {
'one.css': mock.file({mtime: new Date(100)}),
'two.css': mock.file({mtime: new Date(150)})
}
}
});
});
afterEach(mock.restore);
it('compares to previous time if src & dest are same (a)', function(done) {
var files = [{
src: ['src/js/a.js'],
dest: 'src/js/a.js'
}];
util.filterFilesByTime(files, new Date(50), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 1);
var result = results[0];
assert.equal(result.dest, 'src/js/a.js');
assert.deepEqual(result.src, files[0].src);
done();
});
});
it('compares to previous time if src & dest are same (b)', function(done) {
var files = [{
src: ['src/js/a.js'],
dest: 'src/js/a.js'
}];
util.filterFilesByTime(files, new Date(150), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 0);
done();
});
});
it('compares to previous time if src & dest are same (c)', function(done) {
var files = [{
src: ['src/js/a.js'],
dest: 'src/js/a.js'
}, {
src: ['src/js/b.js'],
dest: 'src/js/b.js'
}];
util.filterFilesByTime(files, new Date(50), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 2);
var first = results[0];
assert.equal(first.dest, 'src/js/a.js');
assert.deepEqual(first.src, files[0].src);
var second = results[1];
assert.equal(second.dest, 'src/js/b.js');
assert.deepEqual(second.src, files[1].src);
done();
});
});
it('provides all files if any is newer than dest', function(done) {
var files = [{
src: ['src/js/a.js', 'src/js/b.js', 'src/js/c.js'],
dest: 'dest/js/abc.min.js'
}];
util.filterFilesByTime(files, new Date(1000), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 1);
var result = results[0];
assert.equal(result.dest, 'dest/js/abc.min.js');
assert.equal(result.src.length, 3);
assert.deepEqual(result.src.sort(), files[0].src);
done();
});
});
it('provides all files if dest does not exist', function(done) {
var files = [{
src: ['src/js/a.js', 'src/js/b.js', 'src/js/c.js'],
dest: 'dest/js/foo.min.js'
}];
util.filterFilesByTime(files, new Date(1000), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 1);
var result = results[0];
assert.equal(result.dest, 'dest/js/foo.min.js');
assert.equal(result.src.length, 3);
assert.deepEqual(result.src.sort(), files[0].src);
done();
});
});
it('provides newer src files if same as dest', function(done) {
var files = [{
src: ['src/js/a.js'],
dest: 'src/js/a.js'
}, {
src: ['src/js/b.js'],
dest: 'src/js/b.js'
}, {
src: ['src/js/c.js'],
dest: 'src/js/c.js'
}];
util.filterFilesByTime(files, new Date(150), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 2);
var first = results[0];
assert.equal(first.dest, 'src/js/b.js');
assert.equal(first.src.length, 1);
assert.deepEqual(first.src, files[1].src);
var second = results[1];
assert.equal(second.dest, 'src/js/c.js');
assert.equal(second.src.length, 1);
assert.deepEqual(second.src, files[2].src);
done();
});
});
it('provides files newer than previous if no dest', function(done) {
var files = [{
src: ['src/js/a.js', 'src/js/b.js', 'src/js/c.js']
}];
util.filterFilesByTime(files, new Date(200), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 1);
var result = results[0];
assert.isUndefined(result.dest);
assert.deepEqual(result.src, ['src/js/c.js']);
done();
});
});
it('provides only newer files for multiple file sets', function(done) {
var files = [{
src: ['src/less/one.less'],
dest: 'dest/css/one.css'
}, {
src: ['src/less/two.less'],
dest: 'dest/css/two.css'
}];
util.filterFilesByTime(files, new Date(1000), nullOverride,
function(err, results) {
assert.isNull(err);
assert.equal(results.length, 1);
var result = results[0];
assert.equal(result.dest, 'dest/css/two.css');
assert.deepEqual(result.src, ['src/less/two.less']);
done();
});
});
it('provides an error for a bogus src path', function(done) {
var files = [{
src: ['src/less/bogus.less'],
dest: 'dest/css/one.css'
}];
util.filterFilesByTime(files, new Date(1000), nullOverride,
function(err, results) {
assert.instanceOf(err, Error);
assert.isUndefined(results);
done();
});
});
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=pagination-option.js.map |
import actions from './index'
import {
UPDATE_FOCUSED_GRANULE
} from '../constants/actionTypes'
import { createEcho10MetadataUrls } from '../util/granules'
import { getEarthdataEnvironment } from '../selectors/earthdataEnvironment'
import { getFocusedGranuleId } from '../selectors/focusedGranule'
import { getFocusedGranuleMetadata } from '../selectors/granuleMetadata'
import { portalPathFromState } from '../../../../sharedUtils/portalPath'
import GraphQlRequest from '../util/request/graphQlRequest'
/**
* Sets the focused granule value in redux
* @param {String} payload Concept ID of the granule to set as focused
*/
export const updateFocusedGranule = payload => ({
type: UPDATE_FOCUSED_GRANULE,
payload
})
/**
* Perform a granule concept request based on the focusedGranule from the store.
*/
export const getFocusedGranule = () => (dispatch, getState) => {
const state = getState()
const {
authToken,
router
} = state
// Retrieve data from Redux using selectors
const earthdataEnvironment = getEarthdataEnvironment(state)
const focusedGranuleId = getFocusedGranuleId(state)
const focusedGranuleMetadata = getFocusedGranuleMetadata(state)
// Use the `hasAllMetadata` flag to determine if we've requested previously
// requested the focused collections metadata from graphql
const {
hasAllMetadata = false,
isCwic = false
} = focusedGranuleMetadata
// If this is a cwic granule, we've already retrieved everything we can from the search
if (isCwic) return null
// If we already have the metadata for the focusedGranule, don't fetch it again
if (hasAllMetadata) return null
const graphRequestObject = new GraphQlRequest(authToken, earthdataEnvironment)
const graphQuery = `
query GetGranule(
$id: String!
) {
granule(
conceptId: $id
) {
granuleUr
granuleSize
title
onlineAccessFlag
dayNightFlag
timeStart
timeEnd
dataCenter
originalFormat
conceptId
collectionConceptId
spatialExtent
temporalExtent
relatedUrls
dataGranule
measuredParameters
providerDates
}
}`
const response = graphRequestObject.search(graphQuery, {
id: focusedGranuleId
})
.then((response) => {
const payload = []
const {
data: responseData,
headers
} = response
const { data } = responseData
const { granule } = data
if (granule) {
const {
collectionConceptId,
conceptId,
dataCenter,
dataGranule,
dayNightFlag,
granuleSize,
granuleUr,
measuredParameters,
onlineAccessFlag,
originalFormat,
providerDates,
relatedUrls,
spatialExtent,
temporalExtent,
timeEnd,
timeStart,
title
} = granule
payload.push({
collectionConceptId,
conceptId,
dataCenter,
dataGranule,
dayNightFlag,
granuleSize,
granuleUr,
hasAllMetadata: true,
id: conceptId,
measuredParameters,
metadataUrls: createEcho10MetadataUrls(focusedGranuleId, earthdataEnvironment),
onlineAccessFlag,
originalFormat,
providerDates,
relatedUrls,
spatialExtent,
temporalExtent,
timeEnd,
timeStart,
title
})
// A users authToken will come back with an authenticated request if a valid token was used
dispatch(actions.updateAuthTokenFromHeaders(headers))
// Update metadata in the store
dispatch(actions.updateGranuleMetadata(payload))
} else {
// If no data was returned, clear the focused granule and redirect the user back to the search page
dispatch(actions.updateFocusedGranule(''))
const { location } = router
const { search } = location
dispatch(actions.changeUrl({
pathname: `${portalPathFromState(getState())}/search`,
search
}))
}
})
.catch((error) => {
dispatch(actions.updateFocusedGranule(''))
dispatch(actions.handleError({
error,
action: 'getFocusedGranule',
resource: 'granule',
requestObject: graphRequestObject
}))
})
return response
}
/**
* Change the focusedGranule, and download that granule metadata
* @param {String} granuleId
*/
export const changeFocusedGranule = granuleId => (dispatch) => {
dispatch(updateFocusedGranule(granuleId))
if (granuleId !== '') {
dispatch(actions.getFocusedGranule())
}
}
|
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from collections import defaultdict
from dataclasses import dataclass
from typing import DefaultDict, Iterator, List, Optional
from pants.option.ranked_value import RankedValue
# TODO: Get rid of this? The parser should be able to lazily track.
class OptionTracker:
"""Records a history of what options are set and where they came from."""
@dataclass(frozen=True)
class OptionHistoryRecord:
value: str
rank: int
deprecation_version: Optional[str]
details: Optional[str]
class OptionHistory:
"""Tracks the history of an individual option."""
def __init__(self) -> None:
self.values: List["OptionTracker.OptionHistoryRecord"] = []
def record_value(
self,
value: str,
rank: int,
deprecation_version: Optional[str],
details: Optional[str] = None,
) -> None:
"""Record that the option was set to the given value at the given rank.
:param value: the value the option was set to.
:param rank: the rank of the option when it was set to this value.
:param deprecation_version: Deprecation version for this option.
:param details: optional elaboration of where the option came from (eg, a particular
config file).
"""
deprecation_version_to_write = deprecation_version
if self.latest is not None:
if self.latest.rank > rank:
return
if self.latest.value == value:
return # No change.
if self.latest.deprecation_version:
# Higher RankedValue may not contain deprecation version, so this make sure
# deprecation_version propagate to later and higher ranked value since it is immutable
deprecation_version_to_write = (
self.latest.deprecation_version or deprecation_version
)
self.values.append(
OptionTracker.OptionHistoryRecord(
value, rank, deprecation_version_to_write, details
)
)
@property
def was_overridden(self) -> bool:
"""A value was overridden if it has rank greater than 'HARDCODED'."""
if self.latest is None or len(self.values) < 2:
return False
return (
self.latest.rank > RankedValue.HARDCODED and self.values[-2].rank > RankedValue.NONE
)
@property
def latest(self) -> Optional["OptionTracker.OptionHistoryRecord"]:
"""The most recent value this option was set to, or None if it was never set."""
return self.values[-1] if self.values else None
def __iter__(self) -> Iterator["OptionTracker.OptionHistoryRecord"]:
for record in self.values:
yield record
def __len__(self) -> int:
return len(self.values)
def __init__(self) -> None:
self.option_history_by_scope: DefaultDict = defaultdict(dict)
def record_option(
self,
scope: str,
option: str,
value: str,
rank: int,
deprecation_version: Optional[str] = None,
details: Optional[str] = None,
) -> None:
"""Records that the given option was set to the given value.
:param scope: scope of the option.
:param option: name of the option.
:param value: value the option was set to.
:param rank: the rank of the option (Eg, RankedValue.HARDCODED), to keep track of where the
option came from.
:param deprecation_version: Deprecation version for this option.
:param details: optional additional details about how the option was set (eg, the name
of a particular config file, if the rank is RankedValue.CONFIG).
"""
scoped_options = self.option_history_by_scope[scope]
if option not in scoped_options:
scoped_options[option] = self.OptionHistory()
scoped_options[option].record_value(value, rank, deprecation_version, details)
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+recoil
* @flow strict-local
* @format
*/
'use strict';
import type {RecoilValueReadOnly} from '../core/Recoil_RecoilValue';
import type {RecoilState, RecoilValue} from '../core/Recoil_RecoilValue';
import type {Store} from '../core/Recoil_State';
const ReactDOM = require('ReactDOM');
const {act} = require('ReactTestUtils');
const {graph} = require('../core/Recoil_Graph');
const {
RecoilRoot,
sendEndOfBatchNotifications_FOR_TESTING,
} = require('../core/Recoil_RecoilRoot.react');
const {
invalidateDownstreams_FOR_TESTING,
} = require('../core/Recoil_RecoilValueInterface');
const {makeEmptyStoreState} = require('../core/Recoil_State');
const {
useRecoilValue,
useResetRecoilState,
useSetRecoilState,
} = require('../hooks/Recoil_Hooks');
const selector = require('../recoil_values/Recoil_selector');
const invariant = require('../util/Recoil_invariant');
const nullthrows = require('../util/Recoil_nullthrows');
const stableStringify = require('../util/Recoil_stableStringify');
const React = require('react');
const {useEffect} = require('react');
// TODO Use Snapshot for testing instead of this thunk?
function makeStore(): Store {
const storeState = makeEmptyStoreState();
const store = {
getState: () => storeState,
replaceState: replacer => {
const storeState = store.getState();
// FIXME: does not increment state version number
storeState.currentTree = replacer(storeState.currentTree); // no batching so nextTree is never active
invalidateDownstreams_FOR_TESTING(store, storeState.currentTree);
sendEndOfBatchNotifications_FOR_TESTING(store);
},
getGraph: version => {
const graphs = storeState.graphsByVersion;
if (graphs.has(version)) {
return nullthrows(graphs.get(version));
}
const newGraph = graph();
graphs.set(version, newGraph);
return newGraph;
},
subscribeToTransactions: () => {
throw new Error(
'This functionality, should not tested at this level. Use a component to test this functionality: e.g. componentThatReadsAndWritesAtom',
);
},
addTransactionMetadata: () => {
throw new Error('not implemented');
},
};
return store;
}
class ErrorBoundary extends React.Component<
{children: React.Node | null, ...},
{hasError: boolean, ...},
> {
state = {hasError: false};
static getDerivedStateFromError(_error) {
return {hasError: true};
}
render() {
return this.state.hasError ? 'error' : this.props.children;
}
}
function createReactRoot(container, contents) {
// To test in Concurrent Mode replace with:
// ReactDOM.createRoot(container).render(contents);
ReactDOM.render(contents, container);
}
function renderElements(elements: ?React.Node): HTMLDivElement {
const container = document.createElement('div');
act(() => {
createReactRoot(
container,
<RecoilRoot>
<ErrorBoundary>
<React.Suspense fallback="loading">{elements}</React.Suspense>
</ErrorBoundary>
</RecoilRoot>,
);
});
return container;
}
function renderElementsWithSuspenseCount(
elements: ?React.Node,
): [HTMLDivElement, JestMockFn<[], void>] {
const container = document.createElement('div');
const suspenseCommit = jest.fn(() => {});
function Fallback() {
useEffect(suspenseCommit);
return 'loading';
}
act(() => {
createReactRoot(
container,
<RecoilRoot>
<ErrorBoundary>
<React.Suspense fallback={<Fallback />}>{elements}</React.Suspense>
</ErrorBoundary>
</RecoilRoot>,
);
});
return [container, suspenseCommit];
}
////////////////////////////////////////
// Useful RecoilValue nodes for testing
////////////////////////////////////////
let id = 0;
const errorThrowingAsyncSelector: <T, S>(
string,
?RecoilValue<S>,
) => RecoilValue<T> = <T, S>(
msg,
dep: ?RecoilValue<S>,
): RecoilValueReadOnly<T> =>
selector<T>({
key: `AsyncErrorThrowingSelector${id++}`,
get: ({get}) => {
if (dep != null) {
get(dep);
}
return Promise.reject(new Error(msg));
},
});
const resolvingAsyncSelector: <T>(T) => RecoilValue<T> = <T>(
value: T,
): RecoilValueReadOnly<T> | RecoilValueReadOnly<mixed> =>
selector({
key: `ResolvingSelector${id++}`,
get: () => Promise.resolve(value),
});
const loadingAsyncSelector: () => RecoilValue<void> = () =>
selector({
key: `LoadingSelector${id++}`,
get: () => new Promise(() => {}),
});
function asyncSelector<T, S>(
dep?: RecoilValue<S>,
): [RecoilValue<T>, (T) => void, (Error) => void] {
let resolve = () => invariant(false, 'bug in test code'); // make flow happy with initialization
let reject = () => invariant(false, 'bug in test code');
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const sel = selector({
key: `AsyncSelector${id++}`,
get: ({get}) => {
if (dep != null) {
get(dep);
}
return promise;
},
});
return [sel, resolve, reject];
}
//////////////////////////////////
// Useful Components for testing
//////////////////////////////////
function ReadsAtom<T>({atom}: {atom: RecoilValue<T>}): React.Node {
return stableStringify(useRecoilValue(atom));
}
// Returns a tuple: [
// Component,
// setValue(T),
// resetValue()
// ]
function componentThatReadsAndWritesAtom<T>(
atom: RecoilState<T>,
): [() => React.Node, (T) => void, () => void] {
let setValue;
let resetValue;
const ReadsAndWritesAtom = (): React.Node => {
setValue = useSetRecoilState(atom);
resetValue = useResetRecoilState(atom);
return stableStringify(useRecoilValue(atom));
};
return [
ReadsAndWritesAtom,
(value: T) => setValue(value),
() => resetValue(),
];
}
function flushPromisesAndTimers(): Promise<void> {
// Wrap flush with act() to avoid warning that only shows up in OSS environment
return act(
() =>
new Promise(resolve => {
// eslint-disable-next-line no-restricted-globals
setTimeout(resolve, 100);
jest.runAllTimers();
}),
);
}
type ReloadImports = () => void | (() => void);
type AssertionsFn = (gks: Array<string>) => ?Promise<mixed>;
type TestOptions = {
gks?: Array<Array<string>>,
};
type TestFn = (string, AssertionsFn, TestOptions | void) => void;
const testGKs = (
reloadImports: ReloadImports,
gks: Array<Array<string>>,
): TestFn => (
testDescription: string,
assertionsFn: AssertionsFn,
{gks: additionalGKs = []}: TestOptions = {},
) => {
test.each([
...[...gks, ...additionalGKs].map(gks => [
!gks.length ? testDescription : `${testDescription} [${gks.join(', ')}]`,
gks,
]),
])('%s', async (_title, gks) => {
jest.resetModules();
const gkx = require('../util/Recoil_gkx');
gks.forEach(gkx.setPass);
const after = reloadImports();
await assertionsFn(gks);
gks.forEach(gkx.setFail);
after?.();
});
};
const WWW_GKS_TO_TEST = [
['recoil_suppress_rerender_in_callback'],
['recoil_hamt_2020'],
['recoil_memory_managament_2020'],
];
/**
* GK combinations to exclude in OSS, presumably because these combinations pass
* in FB internally but not in OSS. Ideally this array would be empty.
*/
const OSS_GK_COMBINATION_EXCLUSIONS = [];
// eslint-disable-next-line no-unused-vars
const OSS_GKS_TO_TEST = WWW_GKS_TO_TEST.filter(
gkCombination =>
!OSS_GK_COMBINATION_EXCLUSIONS.some(exclusion =>
exclusion.every(gk => gkCombination.includes(gk)),
),
);
const getRecoilTestFn = (reloadImports: ReloadImports): TestFn =>
testGKs(
reloadImports,
// @fb-only: WWW_GKS_TO_TEST,
OSS_GKS_TO_TEST, // @oss-only
);
module.exports = {
makeStore,
renderElements,
renderElementsWithSuspenseCount,
ReadsAtom,
componentThatReadsAndWritesAtom,
errorThrowingAsyncSelector,
resolvingAsyncSelector,
loadingAsyncSelector,
asyncSelector,
flushPromisesAndTimers,
getRecoilTestFn,
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./Popup"), exports);
tslib_1.__exportStar(require("./Popup.types"), exports);
//# sourceMappingURL=index.js.map |
/**
* Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
*
* @format
* @noflow
* @fbt {"project": "fbt-demo-project"}
* @emails oncall+i18n_fbt_js
*/
/* eslint-disable fb-flow/use-exact-by-default-object-type */
import './css/Example.css';
import classNames from 'classnames';
import fbt, {GenderConst, IntlVariations, init} from 'fbt';
import * as React from 'react';
// eslint-disable-next-line fb-www/no-module-aliasing
const ExampleEnum = require('./Example$FbtEnum');
const viewerContext = {
GENDER: IntlVariations.GENDER_UNKNOWN,
locale: 'en_US',
};
init({
translations: require('../translatedFbts.json'),
hooks: {
getViewerContext: () => viewerContext,
},
});
const LOCALES = Object.freeze({
en_US: Object.freeze({
bcp47: 'en-US',
displayName: 'English (US)\u200e',
englishName: 'English (US)',
rtl: false,
}),
fb_HX: Object.freeze({
bcp47: 'fb-HX',
displayName: 'l33t 5p34k',
englishName: 'FB H4x0r',
rtl: false,
}),
es_LA: Object.freeze({
bcp47: 'es-419',
displayName: 'Espa\u00F1ol',
englishName: 'Spanish',
rtl: false,
}),
ar_AR: Object.freeze({
bcp47: 'ar',
displayName: '\u0627\u0644\u0639\u0631\u0628\u064A\u0629',
englishName: 'Arabic',
rtl: true,
}),
he_IL: Object.freeze({
/* eslint-disable-next-line fb-www/gender-neutral-language */
bcp47: 'he',
displayName: '\u05E2\u05D1\u05E8\u05D9\u05EA',
englishName: 'Hebrew',
rtl: true,
}),
ja_JP: Object.freeze({
bcp47: 'ja',
displayName: '\u65E5\u672C\u8A9E',
englishName: 'Japanese',
rtl: false,
}),
ru_RU: Object.freeze({
bcp47: 'ru',
displayName: 'Русский',
englishName: 'Russian',
rtl: false,
}),
});
type Locale = $Keys<typeof LOCALES>;
type Variation = $Values<typeof IntlVariations>;
type SharedObj = $Keys<typeof ExampleEnum>;
type PronounGender = $Keys<typeof GenderConst>;
type Props = $ReadOnly<{||}>;
type State = {|
locale: Locale,
vcGender: Variation,
ex1Name: string,
ex1Gender: Variation,
ex1Count: int,
ex2Name: string,
ex2Object: SharedObj,
ex2Pronoun: PronounGender,
|};
export default class Example extends React.Component<Props, State> {
state = {
locale: 'en_US',
ex1Name: 'Someone',
ex1Gender: IntlVariations.GENDER_UNKNOWN,
ex1Count: 1,
ex2Name: 'Someone',
ex2Object: 'LINK',
ex2Pronoun: GenderConst.UNKNOWN_SINGULAR,
};
setLocale(locale: Locale) {
viewerContext.locale = locale;
this.setState({locale});
const html = document.getElementsByTagName('html')[0];
if (html != null) {
html.lang = LOCALES[locale].bcp47;
}
document.body.className = LOCALES[locale].rtl ? 'rtl' : 'ltr';
}
onSubmit(event: SyntheticInputEvent<>) {
event.stopPropagation();
event.preventDefault();
}
render() {
const {locale} = this.state;
return (
<div>
<div className="example">
<div className="warning">
<fbt desc="title">Your FBT Demo</fbt>
</div>
<h1>
<fbt desc="header">Construct sentences</fbt>
</h1>
<h2>
{/* For fbt common strings, the description will be sourced from an external manifest.
See `--fbt-common-path` option from `fbt-collect` and common_strings.json */}
<fbt common={true}>Use the form below to see FBT in action.</fbt>
</h2>
<form action="" method="get" onSubmit={this.onSubmit}>
<fieldset>
<span className="example_row">
<span className="example_input--30">
<select
className="neatoSelect"
onChange={(event: SyntheticUIEvent<>) => {
const vcGender = parseInt(event.target.value, 10);
viewerContext.GENDER = vcGender;
this.forceUpdate();
}}>
<option value={IntlVariations.GENDER_UNKNOWN}>
<fbt desc="Gender Select label">Your Gender:</fbt>
</option>
<option value={IntlVariations.GENDER_UNKNOWN}>
<fbt desc="Unknown gender">Unknown</fbt>
</option>
<option value={IntlVariations.GENDER_MALE}>
<fbt desc="Male gender">Male</fbt>
</option>
<option value={IntlVariations.GENDER_FEMALE}>
<fbt desc="Female gender">Female</fbt>
</option>
</select>
</span>
</span>
</fieldset>
<fieldset>
<span className={classNames('example_row', 'example_row--multi')}>
<span
className={classNames('example_input', 'example_input--40')}>
<input
name="name"
onChange={(event: SyntheticUIEvent<>) => {
this.setState({ex1Name: event.target.value});
}}
placeholder={fbt('name', 'name field')}
type="text"
/>
</span>
<span
className={classNames('example_input', 'example_input--30')}>
<input
name="count"
onChange={(event: SyntheticUIEvent<>) => {
const val = parseInt(event.target.value, 10);
this.setState({ex1Count: isNaN(val) ? 1 : val});
}}
placeholder={fbt('count', 'count field')}
type="number"
/>
</span>
<span className="example_row">
<select
className="neatoSelect"
onChange={(event: SyntheticUIEvent<>) => {
this.setState({
ex1Gender: parseInt(event.target.value, 10),
});
}}>
<option value={IntlVariations.GENDER_UNKNOWN}>
<fbt desc="Gender Select label">Gender:</fbt>
</option>
<option value={IntlVariations.GENDER_UNKNOWN}>
<fbt desc="Unknown gender">Unknown</fbt>
</option>
<option value={IntlVariations.GENDER_MALE}>
<fbt desc="Male gender">Male</fbt>
</option>
<option value={IntlVariations.GENDER_FEMALE}>
<fbt desc="Female gender">Female</fbt>
</option>
</select>
</span>
</span>
</fieldset>
<fieldset>
<span className="sentence example_row">
<fbt desc="example 1">
<fbt:param gender={this.state.ex1Gender} name="name">
<b className="padRight">{this.state.ex1Name}</b>
</fbt:param>
has shared
<a className="neatoLink" href="#">
<fbt:plural
count={this.state.ex1Count}
many="photos"
showCount="ifMany">
a photo
</fbt:plural>
</a>
with you
</fbt>
</span>
</fieldset>
<fieldset>
<span className={classNames('example_row', 'example_row--multi')}>
<span
className={classNames('example_input', 'example_input--40')}>
<input
name="ex2Name"
onChange={(event: SyntheticUIEvent<>) => {
this.setState({ex2Name: event.target.value});
}}
placeholder={fbt('name', 'name field')}
type="text"
/>
</span>
<span
className={classNames('example_input', 'example_input--20')}>
<select
className="neatoSelect"
onChange={(event: SyntheticUIEvent<>) => {
this.setState({ex2Object: event.target.value});
}}>
{Object.keys(ExampleEnum).map(k => (
<option key={k} value={k}>
{ExampleEnum[k]}
</option>
))}
</select>
</span>
<span
className={classNames('example_row', 'example_input--20')}>
<select
className="neatoSelect"
onChange={(event: SyntheticUIEvent<>) => {
this.setState({
ex2Pronoun: parseInt(event.target.value, 10),
});
}}>
<option value={GenderConst.UNKNOWN_PLURAL}>
<fbt desc="Gender Select label">Gender:</fbt>
</option>
<option value={GenderConst.NOT_A_PERSON}>
<fbt desc="Gender Select label">Not a person</fbt>
</option>
<option value={GenderConst.UNKNOWN_PLURAL}>
<fbt desc="Gender Select label">Unknown (Plural)</fbt>
</option>
<option value={GenderConst.UNKNOWN_SINGULAR}>
<fbt desc="Gender Select label">Unknown (singular)</fbt>
</option>
<option value={GenderConst.MALE_SINGULAR}>
<fbt desc="Gender Select label">Male (singular)</fbt>
</option>
<option value={GenderConst.FEMALE_SINGULAR}>
<fbt desc="Gender Select label">Female (singular)</fbt>
</option>
</select>
</span>
</span>
</fieldset>
<fieldset>
<span className="sentence example_row">
<fbt desc="Example enum & pronoun">
<fbt:param name="name">
<b className="padRight">
<a href="#">{this.state.ex2Name}</a>
</b>
</fbt:param>
has a
<fbt:enum
enum-range={ExampleEnum}
value={this.state.ex2Object}
/>
to share!{' '}
<b className="pad">
<a href="#">View</a>
</b>{' '}
<fbt:pronoun
gender={this.state.ex2Pronoun}
human={false}
type="possessive"
/>{' '}
<fbt:enum
enum-range={ExampleEnum}
value={this.state.ex2Object}
/>.
</fbt>
</span>
</fieldset>
<fieldset>
<span className="example_row">
<button
className="bottom"
onClick={e => {
window.open('https://github.com/facebook/fbt', '_blank');
}}
type="submit">
{fbt('Try it out!', 'Sign up button')}
</button>
</span>
</fieldset>
</form>
</div>
<ul className="languages">
{Object.keys(LOCALES).map(loc => (
<li key={loc} value={loc}>
{locale === loc ? (
LOCALES[loc].displayName
) : (
<a
href={`#${loc}`}
onClick={(event: SyntheticUIEvent<>) => {
event.preventDefault();
this.setLocale(loc);
}}>
{LOCALES[loc].displayName}
</a>
)}
</li>
))}
</ul>
<p className="copyright">{`Facebook \u00A9 2021`}</p>
</div>
);
}
}
|
from collections import defaultdict
from metrics.sc2metric import Sc2MetricAnalyzer
from metrics.util import convert_to_realtime_r
class APMTracker(object):
"""
Provides ``player.metrics.avg_apm`` which is defined as the sum of
any Selection, ControlGroup, or Command event issued by the player
divided by the number of seconds played by the player (not
necessarily the whole game) multiplied by 60.
APM is 0 for games under 1 minute in length.
*Note: APM is generally calculated starting after an initial time.
For example, APM in Brood War was calculated after the initial
150 seconds of game time. Therefore, actions before 150 seconds
were not counted towards actual APM.
**Note: These APM calculations include the actions taken before 150
seconds, but they do not include that 150 seconds of time, which is
standard among most APM calculators.
"""
name = 'APMTracker'
def __init__(self):
#self._aps = {}
self._actions = defaultdict(int)
self._seconds_played = defaultdict(int)
self.initial_apm_seconds_skipped = 210 #150
def handleInitGame(self, event, replay):
for player in replay.players:
player.metrics = Sc2MetricAnalyzer()
self._actions[player.pid] = 0
self._seconds_played[player.pid] = 0
def handleControlGroupEvent(self, event, replay):
#if event.second > self.initial_apm_seconds_skipped:
self._actions[event.player.pid] += 1
def handleSelectionEvent(self, event, replay):
#if event.second > self.initial_apm_seconds_skipped:
self._actions[event.player.pid] += 1
def handleCommandEvent(self, event, replay):
#if event.second > self.initial_apm_seconds_skipped:
self._actions[event.player.pid] += 1
def handlePlayerLeaveEvent(self, event, replay):
self._seconds_played[event.player.pid] = convert_to_realtime_r(replay, event.second) - self.initial_apm_seconds_skipped #convert_to_realtime_r(replay, self.initial_apm_seconds_skipped)
def handleEndGame(self, event, replay):
for player in replay.players:
if self._actions[player.pid] > 0 and self._seconds_played[player.pid] > 0:
player.metrics.avg_apm = self._actions[player.pid] / self._seconds_played[player.pid] * 60
else:
player.metrics.avg_apm = 0
|
const mongoose = require('mongoose');
const PostSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
text: {
type: String,
required: true
},
name: {
type: String,
},
/*likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'user',
},
},
],
comments: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
text: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
},
],
Date: {
type: Date,
default: Date.now,
},*/
});
module.exports = Post = mongoose.model('post', PostSchema);
|
var header = doc.head || getByTagName('head')[0] || doc.documentElement,
scripts = getByTagName('script'),
currentJs = scripts[scripts.length - 1],
currentPath = currentJs.src || attr(currentJs, 'src'),
BASEPATH = attr(currentJs, 'data-path') || currentPath,
CONFIG = attr(currentJs, 'data-config'),
CHARSET = attr(currentJs, 'charset') || 'utf8',
DEBUG = attr(currentJs, 'data-debug') === 'true',
DYNAMICCONFIG = attr(currentJs,'data-config-dynamic') === 'true',
GLOBALTIMESTAMP = getTimeStamp(currentJs.src),
CONFIGSTMAP = null,
mainjs = attr(currentJs, 'data-main'),
fetching = {},
callbacks = {},
fetched = {},
publicDeps = [], // 改动,增加public依赖数组;
jsExt = ".js"; // 改动,js后缀
BASEPATH = (BASEPATH === currentPath) ? dirname(currentPath) : resolve(BASEPATH, dirname(currentPath));
var fetch = function(url, cb) {
LEVENTS.trigger('fetch', [url, cb]);
};
LEVENTS.on('fetch', function(url, cb) {
if (! (/\.css$/).test(url)) {
if (fetched[url]) {
cb();
return;
}
if (fetching[url]) {
callbacks[url].push(cb);
return;
}
fetching[url] = true;
callbacks[url] = [cb];
getscript(url, function() {
fetched[url] = true;
delete fetching[url];
var fns = callbacks[url];
if (fns) {
delete callbacks[url];
forEach(fns, function(fn) {
fn();
});
}
},
CHARSET);
}
});
var loadeds = {};
var getscript = function(urls, cb, charset) {
var url = isArray(urls) ? urls.shift() : urls;
function success() {
if (isArray(urls) && urls.length) {
getscript(urls, cb, charset);
} else {
if (isFunction(cb)) {
cb();
}
}
}
if (loadeds[url]) {
success();
return;
}
if (url) {
var node = createNode('script', charset);
node.onload = node.onerror = node.onreadystatechange = function() {
if (/loaded|complete|undefined/.test(node.readyState)) {
node.onload = node.onerror = node.onreadystatechange = null;
if (node.parentNode && ! DEBUG) {
node.parentNode.removeChild(node);
}
node = undef;
loadeds[url] = true;
success();
}
};
node.async = 'async';
var timestamp;
if(DYNAMICCONFIG){
timestamp = CONFIGSTMAP ? CONFIGSTMAP : new Date().valueOf();
}else{
timestamp = CONFIGSTMAP ? CONFIGSTMAP : GLOBALTIMESTAMP;
}
url = timestamp ? url + '?timestamp=' + timestamp: url;
node.src = url;
insertscript(node);
} else {
throw new Error('getscript url is ' + url);
}
};
var createNode = function(tag, charset) {
var node = doc.createElement(tag);
node.charset = charset ? charset: CHARSET;
return node;
};
var insertscript = function(node) {
var baseElement = getByTagName('base', header)[0];
if (baseElement) {
header.insertBefore(node, baseElement);
} else {
header.appendChild(node);
}
};
|
const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const UglifyJSPlugin = require("uglifyjs-webpack-plugin")
const CompressionPlugin = require("compression-webpack-plugin")
const BrotliPlugin = require("brotli-webpack-plugin")
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const baseConfig = require('./webpack.baseConfig.js');
const devServer = require('./webpack.devserver.js');
const production = merge(baseConfig, {
mode: 'production',
plugins: [
new ExtractTextPlugin("[name].css"),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require("cssnano"),
cssProcessorOptions: { discardComments: { removeAll: true } }
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
comments: false,
compress: {
screw_ie8: true,
warnings: false
},
mangle: {
keep_fnames: true,
screw_i8: true
}
}),
new CompressionPlugin({
algorithm: "gzip"
}),
new BrotliPlugin(),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
}),
new BundleAnalyzerPlugin({
analyzerMode: 'static'
})
],
});
module.exports = production; |
define(function(require) {
var Mn = require('marionette');
return Mn.ItemView.extend({
template: '#dialog_template',
className: 'dialog',
initialize: function() {},
ui: {
form: 'form',
submitBtn: '#submitDialog'
},
events: {
'click @ui.submitBtn': 'onSubmitBtnClick'
},
onSubmitBtnClick: function(evt) {
evt.preventDefault();
}
});
});
|