code
stringlengths
2
1.05M
/*global define*/ define(function(require){ 'use strict'; var filters = require('filters/filters'); return filters.filter( '<%= name %>', function(){ return function(text) { text = String(text).replace(/\%<%= name.toUpperCase() %>\%/mg, '<%= name %>'.split('').reverse().join('')); return text; }; }); });
(function() { 'use strict' app.factory('httpGET', ["$http", "$q", function($http, $q) { return function(route) { var deferred = $q.defer() console.log("FIRED QUERY"); $http.get(route) .success(function(data) { console.log(`Successful GET request from ${route}:`, data); deferred.resolve(data) }) .error(function(error, status) { console.log("status:", status) console.log(`!ERROR ERROR! from ${route}`, error) deferred.reject(error) }) return deferred.promise } } ]) })()
"use strict"; $("#draw-form").submit(function draw() { $("svg").remove(); $(".last-updated").hide(); $("#update-button").hide(); $("#expand-children-button").hide(); $("#collapse-children-button").hide(); $("#layout-opts").hide(); $("#node-info").html(""); $("#search-group").show(); $("#show-filter-modal-button").show(); var cluster = $("#cluster").val(); var edgeType = $("#edge-type").val(); var levels = $("#levels").val(); var layout = $("#layout").val(); var aggregation = $("#aggregation") .change(function() { aggregation = $(this).prop("checked"); update(); }) .prop("checked"); var w = $("#canvas").innerWidth(), h = $("#canvas").innerHeight(); var zoom = d3.behavior.zoom() .scaleExtent([0.1, 10]) .on("zoom", function() { svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); }); var svg = d3.select("#canvas").append("svg:svg") .attr("width", w) .attr("height", h) svg.append("svg:rect") .attr("width", w) .attr("height", h) .style("fill", "none") .style("stroke", "#000") .style("pointer-events", "all"); svg = svg.call(zoom) .on("dblclick.zoom", null) .append("g"); var svgPaths = svg.append("g"); var svgLines = svg.append("g"); var svgLabels = svg.append("g"); var svgNodes = svg.append("g"); var color = d3.scale.category20(); var size = d3.scale.log(); var radius = parseInt($("#radius").val()); var graph = new dagre.graphlib.Graph() .setGraph({}) .setDefaultEdgeLabel(function() { return {}; }); var visibleGraph = graph; var filterFunction = undefined; var searchMode = false; switch(layout) { case "force-tree": case "force": var force = d3.layout.force() .gravity($("#gravity").val()) .distance(40) .charge($("#charge").val()) .size([w, h]); var paused = false; $("#pause-force-layout").click(function(e) { force.stop(); paused = true; }); var drag = force.drag() .on("dragstart", function(d) { d3.event.sourceEvent.stopPropagation(); }) .on("dragend", function(d) { if (d3.event.sourceEvent.shiftKey) { d.fixed = !d.fixed; } }); $("#layout-opts").show(); $("#gravity") .change(function() { force.gravity(this.value); update(); }); $("#charge") .change(function() { force.charge(this.value); update(); }); $("#radius") .change(function() { radius = parseInt(this.value); update(); }); break; case "dagre": break; } d3.json("/neo?levels=" + levels + "&type=" + edgeType + "&cluster=" + cluster, load); function update() { var visibleGraph = filterFunction? smartFilter(graph, filterFunction): graph; if (aggregation) { visibleGraph = aggregate(visibleGraph); } var nodes = visibleGraph.getNodes(), links = visibleGraph.getLinks(), labeledLinks = links.filter(function(d) { return d.target.number && d.target.number > 1; }); var link = svgLines.selectAll("line.link") .data(links, function(d) { return d.source.id + "-" + d.target.id; }); link.enter().insert("line") .attr("class", "link"); link.exit().remove(); var label = svgLabels.selectAll("text.label") .data(labeledLinks, function(d) { return d.source.id + "-" + d.target.id + "-n" + d.target.number; }); label.enter().insert("text") .attr("class", "label") .text(function(d) { return d.target.number; }); label.exit().remove(); var node = svgNodes.selectAll("g.node") .data(nodes, function(d) { return d.id;}); var nodeEnter = node.enter().append("g") .attr("class", "node") .on("click", handleClick) .on("dblclick", dblclick); nodeEnter.append("circle") .style("fill", function(d) { return color(d.type); }) .style("stroke", function(d) { return d.size? "green": "red"; }) var circle = svg.selectAll("circle") .attr("r", function(d) { return 3 * Math.log(d.size + 1) + radius; }) .style("opacity", function(d) { return (d.highlighted || !searchMode)? 1.0: 0.2; });; nodeEnter.append("text") .attr("dy", ".35em") .attr("text-anchor", "middle") .text(function(d) { return d.type; }); node.exit().remove(); var tick = function tick(e) { if (layout === "force-tree") { var k = 10 * e.alpha; // groups.forEach(function(group) { // var nodes = group.values; // for (var i = 1; i < nodes.length; ++i) { // var dx = nodes[i].x - nodes[0].x; // var dy = nodes[i].y - nodes[0].y; // nodes[i].x -= k * dx / Math.abs(dx); // nodes[i].y -= k * dy / Math.abs(dy); // } // }); links.forEach(function(link) { link.source.y -= k; link.target.y += k; }); var group = svgPaths.selectAll("path") .data(groups) .attr("d", groupPath); group.enter() .insert("path", "circle") .style("fill", groupFill) .style("stroke", groupFill) .style("stroke-width", radius * 6) .style("stroke-linejoin", "round") .style("opacity", .2) .attr("d", groupPath); group.exit().remove(); } node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); label.attr("transform", function(d) { return "translate(" + (d.source.x + d.target.x) / 2 + "," + (d.source.y + d.target.y) / 2 + ")"; }); link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); }; switch(layout) { case "force-tree": topologicalSort(graph); var groups = d3.nest() .key(function(d) { return d.level; }) .entries(nodes) .filter(function(group) { return group.values.length > 2; }); var groupPath = function(d) { return "M" + d3.geom.hull(d.values.map(function(i) { return [i.x, i.y]; })) .join("L") + "Z"; }; var groupFill = function(d, i) { return color(i); }; /* NO BREAK ON PURPOSE*/ case "force": nodeEnter.call(drag); force.on("tick", tick) .nodes(nodes) .links(links) .start(); break; case "dagre": dagre.layout(graph); nodes.forEach(function(node){ node.x += w / 2 - graph.graph().width / 2; node.y += h / 2 ; }); tick(); break; } } function load(json) { json.nodes.forEach(function(node) { graph.setNode(node.id, node); }); json.links.forEach(function(link) { graph.setEdge(link.source, link.target); }); update(); $("#loading-modal").modal("hide"); } function handleClick(node) { $("#node-info").empty(); if (node.aggregated) { node.aggregated.forEach(function(id){ showInfo(id); }); } else { showInfo(node.id); $("#expand-children-button").unbind("click").click(function() { graph.successors(node.id).forEach(function(child) { expand(child); }); }); $("#collapse-children-button").unbind("click").click(function() { graph.successors(node.id).forEach(function(child) { collapse(graph, child); }); update(); }); $("#expand-children-button").show(); $("#collapse-children-button").show(); } } function showInfo(id) { var nodeInfo = graph.node(id).attrs var table = $("<table>") .addClass("table table-bordered") .appendTo("#node-info"); table.append("<thead><tr><th>Key</th><th>Value</th></tr></thead>"); console.log("id = " + id); for (var key in nodeInfo) { table.append("<tr><td>" + key + "</td><td>" + toCell(nodeInfo[key]) +"</td></tr>"); } $(".last-updated#" + cluster).show(); $("#update-button").show(); } function toCell(x) { if ($.isPlainObject(x)) { var cell = "" for (var key in x) { cell += "<b>" + key + ":</b>&nbsp;" + toCell(x[key]) + "<br>"; } return cell; } else { return x; } } function dblclick(node) { if (node.aggregated) { if (node.size == graph.successors(node.id).length) { node.aggregated.forEach(function(id){ collapse(graph, id); }); update(); } else { node.aggregated.forEach(expand); } } else { if (node.size == graph.successors(node.id).length) { collapse(graph, node.id); update(); } else { expand(node.id); } } } function expand(id) { d3.json("/node-out-relations/" + id + "?type=" + edgeType + "&cluster=" + cluster, load); } $("#update-button").click(function () { $.ajax({ type: "GET", url: "/update", data: "cluster=" + cluster }); }); var types, filteredTypes = d3.set(); var linksThroughSuccessor = undefined; function smartFilter(graph, func) { var result = graph.filterNodes(func); if (!linksThroughSuccessor) { $.ajax({ url: "/links-through-successor", data: {type: edgeType, cluster: cluster}, async: false, dataType: "json", success: function(data) { linksThroughSuccessor = data } }); } linksThroughSuccessor.forEach(function(link) { var v = link.source; var w = link.target if (result.hasNode(v) && result.hasNode(w) && !result.hasEdge(v, w)) { result.setEdge(v, w); } }); return result; } $("#show-filter-modal-button").click(function() { types = d3.set( graph.getNodes().map(function(node) { return node.type; }) ).values(); $("#list-of-node-types").empty(); types.forEach(function(type) { var label = $("<label>") .addClass("btn btn-default") .html(type) .appendTo("#list-of-node-types"); var input = $("<input>") .attr({name: type, type: "checkbox"}) .appendTo(label); if (!filteredTypes.has(type)) { label.addClass("active"); input.prop('checked', true); } }); }); $("#filter-button").click(function() { filteredTypes = d3.set($("#filter-form input:checkbox:not(:checked)").map(function() { return $(this).attr("name"); })); filterFunction = function(node) { return !filteredTypes.has(node.type); }; update(); $("#filter-modal").modal("hide"); }); $("#search-button").click(function() { $("#search-error-msg").hide(); var hasSucceeded = false; var lastError; var query = $("#search-query").val(); query = query.replace(/==/g, "===") graph.getNodes().forEach(function(node) { node.highlighted = false; try { node.highlighted = !!evalWith(query, $.extend({}, node.attrs)); hasSucceeded = true; } catch(e) { lastError = e; } }); if (hasSucceeded) { searchMode = true; $("#reset-search-button").show(); update(); } else { $("#search-error-msg").html("<strong>" + lastError.name + "</strong>: " + lastError.message); $("#search-error-msg").show(); } }); $("#reset-search-button").click(function() { searchMode = false; $("#reset-search-button").hide(); update(); }); }); $("#add-button").click(function () { $("#add-error-msg").hide(); $.ajax({ type: "GET", url: "/add-cluster", data: $("#add-form").serialize(), success: function(){ $("#add-modal").modal("hide"); location.reload(); }, error: function() { $("#add-progress").hide(); $("#add-error-msg").show(); $("#add-button").prop("disabled", false); } }); $("#add-button").prop("disabled", true); $("#add-progress").show(); });
'use strict'; var bucketNameComposer = require('../private/bucket_name_composer'); /** * Save the model instance for the given data * @param {String} modelName The model name * @param {Object} data The model data * @param {Function} [apiCallback] The callback function */ module.exports = function(modelName, data, apiCallback){ var id = data.id; if (!id) return apiCallback('save called for a document with no id'); this.db.storeValue({ bucket: bucketNameComposer(this, modelName), key: id, value: data, returnBody: true }, apiCallback); };
'use strict'; const fixture = require('../../fixtures/post_render'); describe('Render post', () => { const Hexo = require('../../../lib/hexo'); const hexo = new Hexo(); const Post = hexo.model('Post'); const Page = hexo.model('Page'); const renderPost = require('../../../lib/plugins/filter/before_generate/render_post').bind(hexo); before(() => hexo.init().then(() => hexo.loadPlugin(require.resolve('hexo-renderer-marked')))); it('post', () => { let id; return Post.insert({ source: 'foo.md', slug: 'foo', _content: fixture.content }).then(post => { id = post._id; return renderPost(); }).then(() => { const post = Post.findById(id); post.content.trim().should.eql(fixture.expected); return post.remove(); }); }); it('page', () => { let id; return Page.insert({ source: 'foo.md', path: 'foo.html', _content: fixture.content }).then(page => { id = page._id; return renderPost(); }).then(() => { const page = Page.findById(id); page.content.trim().should.eql(fixture.expected); return page.remove(); }); }); it('use data variables', () => { let id; return Page.insert({ source: 'foo.md', path: 'foo.html', _content: '<p>Hello {{site.data.foo.name}}</p>' }).then(page => { id = page._id; return renderPost({foo: {name: 'Hexo'}}); }).then(() => { const page = Page.findById(id); page.content.trim().should.eql('<p>Hello Hexo</p>'); return page.remove(); }); }); });
import Microcosm from 'microcosm' describe('History::toArray', function() { it('does not walk past the head', function() { const repo = new Microcosm() let one = repo.append('one') repo.append('two') repo.append('three') repo.checkout(one) repo.history.archive() expect(`${repo.history.toArray()}`).toEqual('one') }) it('only walks through the main timeline', function() { const repo = new Microcosm() const first = repo.append('first') repo.append('second') repo.checkout(first) repo.append('third') repo.history.archive() expect(`${repo.history.toArray()}`).toEqual('first,third') }) })
(function() { 'use strict'; angular .module('users') .controller('SettingsController', SettingsController); SettingsController.$inject = ['$scope', '$http', '$location', 'Users', 'Authentication']; function SettingsController($scope, $http, $location, Users, Authentication) { $scope.user = Authentication.user; // If user is not signed in then redirect back home if(!$scope.user) $location.path('/'); } })();
// import "vue" // import "jquery" // import "underscore" // import { $, jQuery } from "jquery" // export for others scripts to use // window.$ = $ // window.jQuery = jQuery
var projectModule = angular.module('projectModule', ['app.services', 'highcharts-ng']); projectModule.controller('ProjectListController', ['$scope', '$http', '$location', function(scope, http, location) { scope.projects = []; http.get('/project/all').success(function(data) { scope.projects = data.object; }).error(function(data, status, headers, config) { scope.errorMessage = "Can't retrieve project list!"; }); scope.searchProjects = function(query) { return http.get('/project/search?query=' + query).then(function(result) { return result.data.object; }); }; scope.selectProject = function(item, model, label) { location.path('/project/' + model.id); }; } ]); projectModule.controller('ProjectUserAssignController', ['$scope', '$modalInstance', '$http', 'notificationsService', '$location', 'projectId', function(scope, modalInstance, http, notificationsService, location, projectId) { scope.selected = { user: null, role: null }; scope.users = []; http.get('/user/notAssignedToProject/' + projectId).success(function(data) { scope.users = data.object; scope.selected.user = scope.users[0]; }).error(function(data, status, headers, config) { notificationsService.error('Error', "Can't retrieve user list!"); location.path('/project/' + projectId); }); scope.roles = []; http.get('/role/projects').success(function(data) { scope.roles = data.object; scope.selected.role = scope.roles[0]; }).error(function(data, status, headers, config) { notificationsService.error('Error', "Can't retrieve project role list!"); location.path('/project/' + projectId); }); scope.ok = function () { userProjectRoleDto = { userId: scope.selected.user.id, role: scope.selected.role.roleName, projectId: projectId }; modalInstance.close(userProjectRoleDto); }; scope.cancel = function () { modalInstance.dismiss('cancel'); }; } ]); function getProjectDetails(scope, http, notificationsService, location, projectId) { http.get('/project/' + projectId). success(function(data) { scope.project = data.object; scope.bugStat.closed = getClosedBugsByDate(scope.project.bugs); scope.bugStat.opened = getOpenedBugsByDate(scope.project.bugs); scope.chartConfig.series[0].data = scope.bugStat.opened; scope.chartConfig.series[1].data = scope.bugStat.closed; //insert first and last point at chart. //probably highchart have some magic option to do that. setFirstAndLastPointIfNeeded(scope.chartConfig.series[0].data); setFirstAndLastPointIfNeeded(scope.chartConfig.series[1].data); }).error(function(data, status, headers, config) { if(data.error) { notificationsService.error('Error', data.error); } else { notificationsService.error('Error', "Can't retrieve project details!"); } location.path('/project'); }); } function setFirstAndLastPointIfNeeded(data) { todayDate = roundDate(new Date()); if (_.first(data)[1] != 0) { data.unshift([_.first(data)[0] - 24*60*60*1000, 0]); } if (_.last(data)[0] != todayDate) { data.push([todayDate, _.last(data)[1]]); } } function getClosedBugsByDate(bugs) { result = _.filter(bugs, function(bug) { return _.indexOf(["STOPPED", "CLOSED"], bug.state) != -1 ;}); return aggregateBugsByDate(result, "dateModified"); } function getOpenedBugsByDate(bugs) { result = _.filter(bugs, function(bug) { return _.indexOf(["IN_PROGRESS", "READY_TO_TEST", "REOPENED" ], bug.state) != -1 ;}); return aggregateBugsByDate(result, "dateCreated"); } function aggregateBugsByDate(bugs, dateField) { result = _.each(bugs, function(bug) { bug[dateField] = roundDate(new Date(bug[dateField])); }); result = _.countBy(result, dateField); result = _.pairs(result); result = _.sortBy(result, 0); for(i = 1; i < result.length; i++) { result[i][1] += result[i-1][1]; } _.each(result, function(obj) { obj[0] = parseInt(obj[0]); }); return result; } function roundDate(date) { return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); } function getChartConfig(scope) { config = { options: { chart: { type: 'areaspline', zoomType: 'x' } }, title: { text: 'bugs history' }, xAxis: { type: 'datetime', dateTimeLabelFormats: { week: '%b %e', month: '%e. %b', year: '%b' }, title: { text: 'Date' } }, yAxis: { title: { text: 'Number of bugs' }, min: 0 }, series: [{ name: 'Opened bugs', data: scope.stats.openedBugs, color: '#FF6A48' }, { name: 'Closed bugs', data: scope.stats.closedBugs, color: '#A7FF4C' } ] }; return config; } projectModule.controller('ProjectDetailsController', ['$scope', '$http', '$routeParams', 'notificationsService', '$location', '$modal', function(scope, http, routeParams, notificationsService, location, modal) { scope.id = null; scope.projectRevisionDiffs = []; scope.project = null; scope.bugStat = { closed: null, opened: null }; getProjectDetails(scope, http, notificationsService, location, routeParams.id); http.get('/projectRevision/all/' + routeParams.id).success(function(data) { scope.projectRevisionDiffs = data.object; }).error(function(data, status, headers, config) { scope.errorMessage = "Error getting project history"; }); scope.stats = { closedBugs: null, openedBugs: null }; scope.chartConfig = getChartConfig(scope); scope.removeAssignment = function(userId) { http.delete('/project/' + scope.project.id + '/revokeRole/user/' + userId). success(function (data, status, headers, config) { notificationsService.success("User role have been revoked."); getProjectDetails(scope, http, notificationsService, location, routeParams.id); }).error(function(data, status, headers, config) { notificationsService.error('Error', "Can't revoke user role."); location.path('/project/' + projectId); }); }; scope.openAssignPopup = function () { var modalInstance = modal.open({ templateUrl: 'projectUserAssignment.html', controller: 'ProjectUserAssignController', resolve: { projectId: function () { return routeParams.id; } } }); modalInstance.result.then(function (userProjectRole) { http.post('/project/' + userProjectRole.projectId + '/grantRole/' + userProjectRole.role + '/user/' + userProjectRole.userId). success(function (data, status, headers, config) { notificationsService.success('User has been assigned successfully.'); getProjectDetails(scope, http, notificationsService, location, routeParams.id); }).error(function (data, status, headers, config) { notificationsService.error('Error', 'Assigning user failed! ' + data.error); }); }); }; } ]); projectModule.controller('ProjectCreateController', ['$scope', '$http', '$location', 'notificationsService', function(scope, http, location, notificationsService) { scope.createProject = function() { var project = scope.project; var params = JSON.stringify(project); http.post('/project/create', params, { headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).success(function (data, status, headers, config) { notificationsService.success('Success', 'Project ' + data.object.name + ' created successfully'); location.path('/project'); }).error(function (data, status, headers, config) { notificationsService.error('Error', 'Creating project failed! ' + data.error); location.path('/project'); }); } } ]);
exports.blackCards = ["__________. High five, bro.", "TSA guidelines now prohibit __________ on airplanes.", "It's a pity that kids these days are all getting involved with __________.", "In 1,000 years, when paper money is but a distant memory, __________ will be our currency.", "Major League Baseball has banned __________ for giving players an unfair advantage.", "What is Batman's guilty pleasure?", "Next from J.K. Rowling: Harry Potter and the Chamber of __________.", "I'm sorry, Professor, but I couldn't complete my homework because of __________.", "What did I bring back from Mexico?", "__________? There's an app for that.", "Betcha can't have just one!", "What's my anti-drug?", "While the United States raced the Soviet Union to the moon, the Mexican government funneled millions of pesos into research on __________.", "In the new Disney Channel Original Movie, Hannah Montana struggles with __________ for the first time.", "What's my secret power?", "What's the new fad diet?", "What did Vin Diesel eat for dinner?", "When Pharaoh remained unmoved, Moses called down a Plague of __________.", "How am I maintaining my relationship status?", "What's the crustiest?", "When I'm in prison, I'll have __________ smuggled in.", "After Hurricane Katrina, Sean Penn brought __________ to the people of New Orleans.", "Instead of coal, Santa now gives the bad children __________.", "Life was difficult for cavemen before __________.", "What's Teach for America using to inspire inner city students to succeed?", "Who stole the cookies from the cookie jar?", "In Michael Jackson's final moments, he thought about __________.", "White people like __________.", "Why do I hurt all over?", "A romantic candlelit dinner would be incomplete without __________.", "What will I bring back in time to convince people that I am a powerful wizard?", "BILLY MAYS HERE FOR __________.", "The class field trip was completely ruined by __________.", "What's a girl's best friend?", "I wish I hadn't lost the instruction manual for __________.", "When I am President of the United States, I will create the Department of __________.", "What are my parents hiding from me?", "What never fails to liven up the party?", "What gets better with age?", "__________: good to the last drop.", "I got 99 problems but __________ ain't one.", "It's a trap!", "MTV's new reality show features eight washed-up celebrities living with __________.", "What would grandma find disturbing, yet oddly charming?", "What's the most emo?", "During sex, I like to think about __________.", "What ended my last relationship?", "What's that sound?", "__________. That's how I want to die.", "Why am I sticky?", "What's the next Happy Meal® toy?", "What's there a ton of in heaven?", "I do not know with what weapons World War III will be fought, but World War IV will be fought with __________.", "What will always get you laid?", "__________: kid tested, mother approved.", "Why can't I sleep at night?", "What's that smell?", "What helps Obama unwind?", "This is the way the world ends \n This is the way the world ends \n Not with a bang but with __________.", "Coming to Broadway this season, __________: The Musical.", "Anthropologists have recently discovered a primitive tribe that worships __________.", "But before I kill you, Mr. Bond, I must show you __________.", "Studies show that lab rats navigate mazes 50% faster after being exposed to __________.", "Due to a PR fiasco, Walmart no longer offers __________.", "When I am a billionaire, I shall erect a 50-foot statue to commemorate __________.", "In an attempt to reach a wider audience, the Smithsonian Museum of Natural History has opened an interactive exhibit on __________.", "War! What is it good for?", "What gives me uncontrollable gas?", "What do old people smell like?", "Sorry everyone, I just __________.", "Alternative medicine is now embracing the curative powers of __________.", "The U.S. has begun airdropping __________ to the children of Afghanistan.", "What does Dick Cheney prefer?", "During Picasso's often-overlooked Brown Period, he produced hundreds of paintings of __________.", "What don't you want to find in your Chinese food?", "I drink to forget __________."]
// Returns a random integer between min (included) and max (excluded) // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } function fillArray(value, len) { var arr = []; for (var i = 0; i < len; i++) { arr.push(value); } return arr; } function uniform(a, b) { return ( (Math.random() * (b - a)) + a ); } function sampleMarblePosition(center, r) { var sampledR = uniform(0, r); var sampledTheta = uniform(0, Math.PI); //in radians var point = {radius: sampledR, theta: sampledTheta}; return rect(point, center); } //convert to rectangular coordinates function rect(point, center) { var x = center.x + point.radius * Math.cos(point.theta); var y = center.y + point.radius * Math.sin(point.theta); return {x: x, y: y}; } function get100Points(n_total, n_target, tcolor, ocolor, w, h, radius) { var points = []; var targetcolor = tcolor; var othercolor = ocolor; var pointcolors = _.shuffle(fillArray(targetcolor, n_target).concat(fillArray(othercolor, n_total - n_target))); var pcnt = 0; var y = 24.5; for (var i = 0; i < 4; i++) { for (var x = 23; x < 600; x += 46) { points.push({x: x + uniform(-13, 13), y: y + uniform(-13, 13), color: pointcolors[pcnt]}); pcnt++; } y = y + 49; for (var x = 24.5; x < 600; x += 49) { points.push({x: x + uniform(-13, 13), y: y + uniform(-13, 13), color: pointcolors[pcnt]}); pcnt++; } y = y + 49; } return points; } function get5Points(n_total, n_target, tcolor, ocolor, w, h, radius) { var points = []; var targetcolor = tcolor; var othercolor = ocolor; var pointcolors = _.shuffle(fillArray(targetcolor, n_target).concat(fillArray(othercolor, n_total - n_target))); var pcnt = 0; points.push({x: 100 + uniform(-70, 70), y: 100 + uniform(-60, 60), color: pointcolors[pcnt]}); pcnt++; points.push({x: 300 + uniform(-70, 70), y: 100 + uniform(-60, 60), color: pointcolors[pcnt]}); pcnt++; points.push({x: 500 + uniform(-70, 70), y: 100 + uniform(-60, 60), color: pointcolors[pcnt]}); pcnt++; points.push({x: 150 + uniform(-90, 90), y: 300 + uniform(-60, 60), color: pointcolors[pcnt]}); pcnt++; points.push({x: 350 + uniform(-90, 90), y: 300 + uniform(-60, 60), color: pointcolors[pcnt]}); return points; } function get10Points(n_total, n_target, tcolor, ocolor, w, h, radius) { var points = []; var targetcolor = tcolor; var othercolor = ocolor; var pointcolors = _.shuffle(fillArray(targetcolor, n_target).concat(fillArray(othercolor, n_total - n_target))); var pcnt = 0; var cnt = 0 for (var y = 67; y < 400; y += 133) { if (cnt % 2 == 0) { for (var x = 100; x < 600; x += 200) { points.push({x: x + uniform(-80, 80), y: y + uniform(-40, 40), color: pointcolors[pcnt]}); pcnt++; } } else { for (var x = 75; x < 600; x += 150) { points.push({x: x + uniform(-60, 60), y: y + uniform(-40, 40), color: pointcolors[pcnt]}); pcnt++; } } cnt++; } return points; } function get25Points(n_total, n_target, tcolor, ocolor, w, h, radius) { var points = []; var targetcolor = tcolor; var othercolor = ocolor; var pointcolors = _.shuffle(fillArray(targetcolor, n_target).concat(fillArray(othercolor, n_total - n_target))); var pcnt = 0; for (var y = 40; y < 400; y += 80) { for (var x = 60; x < 600; x += 120) { points.push({x: x + uniform(-30, 30), y: y + uniform(-25, 25), color: pointcolors[pcnt]}); pcnt++; } } return points; } function getPoints(n_total, n_target, tcolor, ocolor, w, h, radius) { console.log("width: " + w); console.log("height: " + h); //var initpointlocations = getPointLocations(n_total),w,h; var targetcolor = tcolor;//acolors[cnt].color; var othercolor = ocolor;//bcolors[cnt].color; var pointcolors = _.shuffle(fillArray(targetcolor, n_target).concat(fillArray(othercolor, n_total - n_target))); //console.log(n_total,n_target) //console.log(pointcolors); var points = []; var x = uniform(radius * 2, w - radius * 2); var y = uniform(radius * 2, h - radius * 2); points.push({x: x, y: y, color: pointcolors[0]}); for (var i = 1; i < n_total; i++) { console.log(i); var goodpointfound = false; while (!goodpointfound) { console.log(points); //samp = sampleMarblePosition(initpointlocations[i],6); var x = uniform(radius * 2, w - radius * 2); var y = uniform(radius * 2, h - radius * 2); console.log("x: " + x); console.log("y: " + y); var cnt = 0; for (var p = 0; p < points.length; p++) { console.log(Math.abs(points[p].x - x)); console.log(Math.abs(points[p].y - y)); // console.log(radius*4); if (Math.abs(points[p].x - x) < radius * 1.5 || Math.abs(points[p].y - y) < radius * 1.5) { break; //console.log("increased cnt: "+cnt+" out of a total of "+points.length); } else { cnt++; } } if (cnt == points.length) { console.log("found a good point"); goodpointfound = true; points.push({x: x, y: y, color: pointcolors[i]}); } else { console.log("start over"); } } } console.log(points); console.log(n_total); return points; } function draw(id, n_total, n_target, tcolor, ocolor) { var canvas = document.getElementById(id); canvas.style.background = "lightgrey"; // Useful in the case of black/white colors. if (canvas.getContext) { var ctx = canvas.getContext("2d"); canvas.width = 600; canvas.height = 400; var radius = 0; if (n_total < 25) { radius = 150 / n_total; } else { if (n_total == 25) { radius = 10; } else { radius = 6; } } //paint the rectangle // var x = canvas.width / 2; // var y = canvas.height / 4 var counterClockwise = true; ctx.rect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = 'black'; ctx.stroke(); //paint the marbles if (n_total == 5) { points = get5Points(n_total, n_target, tcolor, ocolor, canvas.width, canvas.height, radius); } else { if (n_total == 10) { points = get10Points(n_total, n_target, tcolor, ocolor, canvas.width, canvas.height, radius); } else { if (n_total == 25) { points = get25Points(n_total, n_target, tcolor, ocolor, canvas.width, canvas.height, radius); } else { points = get100Points(n_total, n_target, tcolor, ocolor, canvas.width, canvas.height, radius); } } } for (var i = 0; i < points.length; i++) { ctx.beginPath(); ctx.arc(points[i].x, points[i].y, radius, 0, 2 * Math.PI, true); ctx.fillStyle = points[i].color; ctx.closePath(); ctx.fill(); } } } function make_slides(f) { var slides = {}; // preload( // ["images/bathrobe.png","images/belt.jpg"], // {after: function() { console.log("everything's loaded now") }} // ) slides.i0 = slide({ name: "i0", start: function () { exp.startT = Date.now(); } }); // We're actually not using this slide at all for now. slides.instructions = slide({ name: "instructions", button: function () { exp.go(); //use exp.go() if and only if there is no "present" data. } }); slides.prolificID = slide({ name: "prolificID", start: function() { $(".errProlificID").hide(); }, button: function() { var prolificID = $(".prolificIDInput").val(); if (prolificID.length > 0) { $(".errProlificID").hide(); exp.prolificID = prolificID; exp.go(); //use exp.go() if and only if there is no "present" data. } else { $(".errProlificID").show(); } } }); slides.objecttrial = slide({ name: "objecttrial", present: exp.all_stims, start: function () { $(".err").hide(); }, present_handle: function (stim) { this.trial_start = Date.now(); this.stim = stim; console.log(this.stim); var blanksentence = "How would you describe the <strong>number of <span style='color:" + this.stim.color_target.color + "; background:lightgrey'>" + this.stim.color_target.colorword + "</span> dots</strong> to someone who has not seen the picture?"; //$("#contextsentence").html(contextsentence); $(".blanksentence").html(blanksentence); $(".color-word").attr("style", "color:" + this.stim.color_target.color + "; background:lightgrey"); $(".color-word").text(this.stim.color_target.colorwordTargetLan); draw("situation", this.stim.n_total, this.stim.n_target, this.stim.color_target.color, this.stim.color_other.color); }, // This is the "Continue" button. button: function () { var word1 = $(".word1").val(); var word2 = $(".word2").val(); var word3 = $(".word3").val(); console.log(word1); // Should we keep the empty responses as empty columns, or only add the responses that actually have contents? // Should actually just produce three variables to record, in retrospect. this.stim.response1 = word1; this.stim.response2 = word2; this.stim.response3 = word3; // This means the answers were entered correctly. At least one would need to be filled if (word1.length > 0 || word2.length > 0 || word3.length > 0) { $(".err").hide(); this.log_responses(); // Clear them to prepare for the next round of question. $(".word1").val(""); $(".word2").val(""); $(".word3").val(""); _stream.apply(this); //use exp.go() if and only if there is no "present" data. } else { // Some of the blanks are left empty. $(".err").show(); } }, log_responses: function () { exp.data_trials.push({ "slide_number_in_experiment": exp.phase, "rt": Date.now() - _s.trial_start, "response1": this.stim.response1, "response2": this.stim.response2, "response3": this.stim.response3, "color_target": this.stim.color_target.colorword, "color_other": this.stim.color_other.colorword, "n_total": this.stim.n_total, "n_target": this.stim.n_target }); } }); slides.language_info = slide({ name: "language_info", button: function () { // Let me just rewrite this... BitBallon is getting me crazy results by inserting <pre> elements on its own! exp.language_data = { country_of_birth: $(".country-of-birth-response").val(), country_of_residence: $(".country-of-residence-response").val(), father_country_of_birth: $(".father-cob-response").val(), mother_country_of_birth: $(".mother-cob-response").val(), childhood_language: $(".childhood-language-response").val(), preferred_language: $(".preferred-language-response").val() }; for (var response in exp.language_data) { if (!exp.language_data.hasOwnProperty(response)) { continue; } if (exp.language_data[response].length <= 0) { $(".language-info-error").show(); return; } } exp.go(); } }); slides.subj_info = slide({ name: "subj_info", submit: function (e) { //if (e.preventDefault) e.preventDefault(); // I don't know what this means. // Tell the participant to wait instead of clicking the submit button multiple times, since it can take several seconds. $(".submissionPrompt").show(); exp.subj_data = { // This is not useful for now since we are targeting a specific native language. // language: $("#language").val(), // This is already asked above. // count: $("#count").val(), languages: $("#languages").val(), enjoyment: $("#enjoyment").val(), // To avoid putting null there. assess: $('input[name="assess"]:checked').length > 0 ? $('input[name="assess"]:checked').val() : "", age: $("#age").val(), gender: $("#gender").val(), education: $("#education").val(), colorblind: $("#colorblind").val(), comments: $("#comments").val(), }; exp.data = { "prolificID": exp.prolificID, "trials": exp.data_trials, "catch_trials": exp.catch_trials, "system": exp.system, "condition": exp.condition, "language_information": exp.language_data, "subject_information": exp.subj_data, "time_in_minutes": (Date.now() - exp.startT) / 60000, // Entries needed for the custom backend. "experiment_id": "italian-free-production-pilot", "author": "JI Xiang", "description": "Pilot experiment on Prolific collecting the most common Chinese quantifiers" }; // I guess in this case I should actually move the submission logic a bit, so that if a submission fails, the participant can actually resubmit it. Let me see how it goes. // Set a timeout of 1 second. Presumably to let the participant read the information first before posting the JSON. I don't think we need such a high timeout in our case though. setTimeout(function () { // turk.submit(exp.data); $.ajax({ type: 'POST', url: 'https://procomprag.herokuapp.com/api/submit_experiment', // url: 'http://localhost:4000/api/submit_experiment', crossDomain: true, data: exp.data, success: function(responseData, textStatus, jqXHR) { console.log(textStatus) // Only proceed to the next slide if the submission actually succeeded. exp.go(); //use exp.go() if and only if there is no "present" data. }, error: function(responseData,textStatus, errorThrown) { // It seems that this timeout (waiting for the server) is implemented as a default value in many browsers, e.g. Chrome. However it is really long (1 min) so timing out shouldn't be such a concern. if (textStatus == "timeout") { alert("Oops, the submission timed out. Please try again. If the problem persists, please contact xiang.ji@student.uni-tuebingen.de and mchfranke@gmail.com, including your Prolific ID"); } else { alert("Oops, the submission failed. Please try again. If the problem persists, please contact xiang.ji@student.uni-tuebingen.de and mchfranke@gmail.com, including your Prolific ID"); } } }) }, 1000); } }); slides.thanks = slide({ name: "thanks", start: function () { var completionPrompt = "Please click on <a href=" + exp.completionURL + ">" + exp.completionURL + "</a> or copy the code to finish the study."; $(".completionPrompt").html(completionPrompt); } }); return slides; } /// init /// function init() { // Let me just put the completion url here anyways. exp.completionURL = "https://www.prolific.ac/submissions/complete?cc=CL4ZZB15"; document.onkeydown = function (e) { e = e || window.event; // If it's "Enter", then continue if (e.keyCode == 13) { _s.button(); } } // This function is called when the sequence of experiments is generated, further down in the init() function. function makeStim(i, n) { // Make it only black and white var colors = ([{color: "#000000", colorword: "black", colorwordTargetLan: "neri"}, {color: "#FFFFFF", colorword: "white", colorwordTargetLan: "bianchi"}]); var shuffled = _.shuffle(colors); color_target = shuffled[0]; color_other = shuffled[1]; // console.log("makeStim is called. The target color is " + color_target.colorword + ". The other color is " + color_other.colorword); return { "n_total": n, "n_target": i, "color_target": color_target, "color_other": color_other } } function getIntervals(n) { var random_ints = []; switch (n) { case 5: random_ints = [0, 1, 2, 3, 4, 5]; break; case 10: random_ints = [getRandomInt(0, 3), getRandomInt(3, 5), getRandomInt(5, 7), getRandomInt(7, 9), getRandomInt(9, 11)]; break; case 25: random_ints = [getRandomInt(0, 6), getRandomInt(6, 11), getRandomInt(11, 16), getRandomInt(16, 21), getRandomInt(21, 26)]; break; case 100: random_ints = [getRandomInt(0, 11), getRandomInt(11, 21), getRandomInt(21, 31), getRandomInt(31, 41), getRandomInt(41, 51), getRandomInt(51, 61), getRandomInt(61, 71), getRandomInt(71, 81), getRandomInt(81, 91), getRandomInt(91, 101)]; break; } return random_ints; } exp.all_stims = []; // Make stims for all four numbers of total dots. var n_totals = [5, 10, 25, 100]; for (var n = 0; n < n_totals.length; n++) { console.log(n_totals[n]); var intervals = getIntervals(n_totals[n]); console.log(intervals); for (var i = 0; i < intervals.length; i++) { exp.all_stims.push(makeStim(intervals[i], n_totals[n])); } } exp.all_stims = _.shuffle(exp.all_stims); console.log(exp.all_stims); exp.trials = []; exp.catch_trials = []; exp.condition = {}; //can randomize between subject conditions here exp.system = { Browser: BrowserDetect.browser, OS: BrowserDetect.OS, screenH: screen.height, screenUH: exp.height, screenW: screen.width, screenUW: exp.width }; //blocks of the experiment: exp.structure = ["i0", "prolificID", "objecttrial", 'language_info', 'subj_info', 'thanks']; exp.data_trials = []; //make corresponding slides: exp.slides = make_slides(exp); exp.nQs = utils.get_exp_length(); //this does not work if there are stacks of stims (but does work for an experiment with this structure) //relies on structure and slides being defined $(".nQs").html(exp.nQs); $('.slide').hide(); //hide everything //make sure turkers have accepted HIT (or you're not in mturk) $("#start_button").click(function () { if (turk.previewMode) { $("#mustaccept").show(); } else { $("#start_button").click(function () { $("#mustaccept").show(); }); exp.go(); } }); exp.go(); //show first slide }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const webpackMerge = require('webpack-merge'); const config_1 = require("./config"); const webpack_configs_1 = require("./webpack-configs"); const path = require('path'); class NgCliWebpackConfig { constructor(buildOptions, appConfig) { this.validateBuildOptions(buildOptions); const configPath = config_1.CliConfig.configFilePath(); const projectRoot = path.dirname(configPath); appConfig = this.addAppConfigDefaults(appConfig); buildOptions = this.addTargetDefaults(buildOptions); buildOptions = this.mergeConfigs(buildOptions, appConfig); this.wco = { projectRoot, buildOptions, appConfig }; } buildConfig() { let webpackConfigs = [ webpack_configs_1.getCommonConfig(this.wco), webpack_configs_1.getBrowserConfig(this.wco), webpack_configs_1.getStylesConfig(this.wco), this.getTargetConfig(this.wco) ]; if (this.wco.appConfig.main || this.wco.appConfig.polyfills) { const typescriptConfigPartial = this.wco.buildOptions.aot ? webpack_configs_1.getAotConfig(this.wco) : webpack_configs_1.getNonAotConfig(this.wco); webpackConfigs.push(typescriptConfigPartial); } this.config = webpackMerge(webpackConfigs); return this.config; } getTargetConfig(webpackConfigOptions) { switch (webpackConfigOptions.buildOptions.target) { case 'development': return webpack_configs_1.getDevConfig(webpackConfigOptions); case 'production': return webpack_configs_1.getProdConfig(webpackConfigOptions); } } // Validate build options validateBuildOptions(buildOptions) { buildOptions.target = buildOptions.target || 'development'; if (buildOptions.target !== 'development' && buildOptions.target !== 'production') { throw new Error("Invalid build target. Only 'development' and 'production' are available."); } } // Fill in defaults for build targets addTargetDefaults(buildOptions) { const targetDefaults = { development: { environment: 'dev', outputHashing: 'media', sourcemaps: true, extractCss: false }, production: { environment: 'prod', outputHashing: 'all', sourcemaps: false, extractCss: true, aot: true } }; return Object.assign({}, targetDefaults[buildOptions.target], buildOptions); } // Fill in defaults from .angular-cli.json mergeConfigs(buildOptions, appConfig) { const mergeableOptions = { outputPath: appConfig.outDir, deployUrl: appConfig.deployUrl }; return Object.assign({}, mergeableOptions, buildOptions); } addAppConfigDefaults(appConfig) { const appConfigDefaults = { testTsconfig: appConfig.tsconfig, scripts: [], styles: [] }; // can't use Object.assign here because appConfig has a lot of getters/setters for (let key of Object.keys(appConfigDefaults)) { appConfig[key] = appConfig[key] || appConfigDefaults[key]; } return appConfig; } } exports.NgCliWebpackConfig = NgCliWebpackConfig; //# sourceMappingURL=/users/johnny/myfiles/angular-cli/models/webpack-config.js.map
_.mixin({ /** * empty event handler function, which simply prevents default handling * * @function module:undermore.eFn * @example * $('#thing').on('click',this.conf.onClick||_.eFn) */ eFn: function(e) { e.preventDefault(); } });
var re1 = /([\W_\-]+\S?)/g; var re2 = /[\W_]/g; module.exports = function toCamelCase(string, capitalizeFirst) { var replaced = string.replace(re1, function (match) { return match.replace(re2, '').toUpperCase(); }); var first = replaced.slice(0, 1)[capitalizeFirst ? 'toUpperCase' : 'toLowerCase'](); return first + replaced.slice(1); };
beforeEach(() => { cy.visitStory('components-dropdowns-dropdown--dropdown-default') }) describe('Dropdown', () => { it('Should open a Dropdown', () => { cy.get('[data-cy="DropdownTrigger"]').click() cy.get('.DropdownMenuContainerPlacementRoot').should('exist') }) })
import React, { Component } from 'react' import Game from './Game' class GameList extends Component { renderGames () { return this.props.games.map(game => { return (<Game key={game.id} game={game} goToGame={this.props.goToGame} />) }) } render () { return ( <div className='dark-container'> <h3>GameList</h3> <div> {this.renderGames()} </div> </div> ) } } export default GameList
module.exports = _.extend({}, Backbone.Events);
/*****************************************************************************/ /* Server Methods */ /*****************************************************************************/ Meteor.methods({ 'server/submitenquiry': function (doc) { check(doc, { name: String, email: String, phone: Match.Optional(String), reason: String, message: String, "g-recaptcha-response": String }); var verifyCaptchaResponse = Recaptcha.verifyCaptcha(this.connection.clientAddress, doc['g-recaptcha-response']); console.dir(verifyCaptchaResponse.data); if (verifyCaptchaResponse.data.success === false) throw new Meteor.Error("Oh no! A robot!"); delete doc["g-recaptcha-response"]; Enquiry.insert(doc, function () { }); } });
import { shallowMount } from '@vue/test-utils'; import waitForPromises from 'helpers/wait_for_promises'; import { GlAlert, GlModal } from '@gitlab/ui'; import PagerDutySettingsForm from '~/incidents_settings/components/pagerduty_form.vue'; describe('Alert integration settings form', () => { let wrapper; const resetWebhookUrl = jest.fn(); const service = { updateSettings: jest.fn().mockResolvedValue(), resetWebhookUrl }; const findForm = () => wrapper.find({ ref: 'settingsForm' }); const findWebhookInput = () => wrapper.find('[data-testid="webhook-url"]'); const findModal = () => wrapper.find(GlModal); const findAlert = () => wrapper.find(GlAlert); beforeEach(() => { wrapper = shallowMount(PagerDutySettingsForm, { provide: { service, pagerDutySettings: { active: true, webhookUrl: 'pagerduty.webhook.com', webhookUpdateEndpoint: 'webhook/update', }, }, }); }); afterEach(() => { if (wrapper) { wrapper.destroy(); wrapper = null; } }); it('should match the default snapshot', () => { expect(wrapper.element).toMatchSnapshot(); }); it('should call service `updateSettings` on form submit', () => { findForm().trigger('submit'); expect(service.updateSettings).toHaveBeenCalledWith( expect.objectContaining({ pagerduty_active: wrapper.vm.active }), ); }); describe('Webhook reset', () => { it('should make a call for webhook reset and reset form values', async () => { const newWebhookUrl = 'new.webhook.url?token=token'; resetWebhookUrl.mockResolvedValueOnce({ data: { pagerduty_webhook_url: newWebhookUrl }, }); findModal().vm.$emit('ok'); await waitForPromises(); expect(resetWebhookUrl).toHaveBeenCalled(); expect(findWebhookInput().attributes('value')).toBe(newWebhookUrl); expect(findAlert().attributes('variant')).toBe('success'); }); it('should show error message and NOT reset webhook url', async () => { resetWebhookUrl.mockRejectedValueOnce(); findModal().vm.$emit('ok'); await waitForPromises(); expect(findAlert().attributes('variant')).toBe('danger'); }); }); });
var style = { contentHeadline: { fontWeight: 100, color: '#676767', fontSize: '32px' }, contentHr: { border: 'none', height: '1px', backgroundColor: 'rgba(0, 0, 0, 0.15)', marginLeft: '-10px', width: 'calc(100% + 20px)' }, center: { textAlign: 'center' }, button: { paddingTop: 9, paddingBottom: 9, paddingLeft: 16, paddingRight: 16, minWidth: '116px', fontSize: '14px', borderRadius: 5, // '38px' border: 'none', outline: 'none', transition: 'ease-in-out 0.1s', cursor: 'pointer', marginTop: 10, marginRight: 10, marginBottom: 10, ':hover': { // opacity: 0.6, transform: 'scaleX(1.1) scaleY(1.1)' } }, green: { backgroundColor: 'rgba(32, 199, 83, 1)', color: '#ffffff' }, red: { backgroundColor: 'rgb(255, 59, 0)', color: '#ffffff' }, gray: { backgroundColor: 'rgb(234, 234, 234)', color: '#000000' }, hoverRed: { ':hover': { backgroundColor: 'rgb(255, 59, 0)', color: '#ffffff' } }, validationError: { color: '#ff0000', fontWeight: 700, fontSize: 14 }, errorBox: { fontSize: 14, fontWeight: 500, cursor: 'pointer', borderRadius: 5, backgroundColor: 'rgb(255, 59, 0)', padding: 8, paddingLeft: 16, paddingRight: 16, border: '1px solid rgb(255, 59, 0)', position: 'relative', marginBottom: 10, color: '#ffffff' } } export default style
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createScript; var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _slash = require('slash'); var _slash2 = _interopRequireDefault(_slash); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _metadata = require('./metadata'); var _metadata2 = _interopRequireDefault(_metadata); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const indents = {}; /* eslint quotes:0 */ for (let i = 0; i <= 16; i += 1) { let str = ''; let j = i; while (j > 0) { str += ' '; j -= 1; } indents[i] = str; } function wrapWord(word) { if (/^[a-z]/i.test(word) && /^[a-z_0-9]+$/i.test(word)) { return word; } return `'${word}'`; } function createScript(id, serviceDir, configFile, modulesDirs) { let metadata = (0, _metadata2.default)(id, serviceDir, configFile, modulesDirs); const moduleFilePath = _path2.default.join(serviceDir, 'modules.js'); function relative(file) { let modulesDir = _path2.default.join(process.cwd(), 'node_modules'); let res = _path2.default.relative(modulesDir, file); if (res && res[0] !== '.') { return (0, _slash2.default)(res); } res = _path2.default.relative(_path2.default.dirname(moduleFilePath), file); if (res[0] !== '.') { res = './' + res; } return (0, _slash2.default)(res); } let script = '// This file is auto-created by alaska, please DO NOT modify the file manually!\n\n'; // fields script += 'exports.fields = {\n'; _lodash2.default.forEach(metadata.fields, (dir, name) => { console.log('field :', name); script += ` '${name}': require('${relative(dir)}').default,\n`; }); script += '};\n\n'; // drivers script += 'exports.drivers = {\n'; _lodash2.default.forEach(metadata.drivers, (dir, name) => { console.log('driver :', name); script += ` '${name}': require('${relative(dir)}').default,\n`; }); script += '};\n\n'; // renderers script += 'exports.renderers = {\n'; _lodash2.default.forEach(metadata.renderers, (dir, name) => { console.log('renderer :', name); script += ` '${name}': require('${relative(dir)}').default,\n`; }); script += '};\n\n'; // middlewares script += 'exports.middlewares = {\n'; _lodash2.default.forEach(metadata.middlewares, (dir, name) => { console.log('middleware :', name); script += ` '${name}': require('${relative(dir)}'),\n`; }); script += '};\n\n'; // services script += 'exports.services = {\n'; function renderList(indent, object, name, withDefault) { let defaultStr = withDefault ? '.default' : ''; if (_lodash2.default.size(object)) { script += `${indents[indent]}${name}: {\n`; _lodash2.default.forEach(object, (file, key) => { script += `${indents[indent]} ${wrapWord(key)}: require('${relative(file)}')${defaultStr},\n`; }); script += `${indents[indent]}},\n`; } } _lodash2.default.forEach(metadata.services, (service, serviceId) => { console.log('service :', serviceId); script += ` ${wrapWord(serviceId)}: {\n`; script += ` id: '${serviceId}',\n`; script += ` service: require('${relative(service.dir)}').default,\n`; script += ` config: require('${relative(service.config)}').default,\n`; renderList(4, service.api, 'api'); renderList(4, service.controllers, 'controllers'); renderList(4, service.routes, 'routes', true); renderList(4, service.locales, 'locales', true); renderList(4, service.models, 'models', true); renderList(4, service.sleds, 'sleds', true); renderList(4, service.updates, 'updates', true); // plugins if (_lodash2.default.size(service.plugins)) { script += ` plugins: {\n`; _lodash2.default.forEach(service.plugins, (plugin, key) => { console.log(' plugin :', (0, _slash2.default)(_path2.default.relative(process.cwd(), plugin.dir))); script += ` ${wrapWord(key)}: {\n`; if (plugin.pluginClass) { script += ` pluginClass: require('${relative(plugin.pluginClass)}').default,\n`; } if (plugin.config) { script += ` config: require('${relative(plugin.config)}').default,\n`; } renderList(8, plugin.api, 'api'); renderList(8, plugin.controllers, 'controllers'); renderList(8, plugin.routes, 'routes', true); renderList(8, plugin.locales, 'locales', true); renderList(8, plugin.models, 'models'); renderList(8, plugin.sleds, 'sleds'); script += ` },\n`; }); script += ` },\n`; } // templatesDirs if (_lodash2.default.size(service.templatesDirs)) { script += ` templatesDirs: [\n`; _lodash2.default.forEach(service.templatesDirs, d => { script += ` '${(0, _slash2.default)(_path2.default.relative(serviceDir, d))}',\n`; }); script += ` ],\n`; } // react views script += ` reactViews: {\n`; _lodash2.default.forEach(service.reactViews, (file, name) => { script += ` '${(0, _slash2.default)(name)}': require('./${(0, _slash2.default)(_path2.default.relative(serviceDir, file))}').default,\n`; }); script += ` },\n`; // end script += ` },\n`; }); script += '};\n\n'; _fs2.default.writeFileSync(moduleFilePath, script); }
// JavaScript Variables and Objects // I paired [by myself, with:] on this challenge. // __________________________________________ // Write your code below. var secretNumber = 7 var password = "just open the door" var allowedIn = false var members = ["John", , ,"Mary"] // __________________________________________ // Test Code: Do not alter code below this line. function assert(test, message, test_number) { if (!test) { console.log(test_number + "false"); throw "ERROR: " + message; } console.log(test_number + "true"); return true; } assert( (typeof secretNumber === 'number'), "The value of secretNumber should be a number.", "1. " ) assert( secretNumber === 7, "The value of secretNumber should be 7.", "2. " ) assert( typeof password === 'string', "The value of password should be a string.", "3. " ) assert( password === "just open the door", "The value of password should be 'just open the door'.", "4. " ) assert( typeof allowedIn === 'boolean', "The value of allowedIn should be a boolean.", "5. " ) assert( allowedIn === false, "The value of allowedIn should be false.", "6. " ) assert( members instanceof Array, "The value of members should be an array", "7. " ) assert( members[0] === "John", "The first element in the value of members should be 'John'.", "8. " ) assert( members[3] === "Mary", "The fourth element in the value of members should be 'Mary'.", "9. " )
export const ic_format_underlined_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"},"children":[]}]};
module.exports = function(that) { var val = that.value; if (!val) return true; var otherField = that.getField(that.Rules.smallerThan); if (!otherField || !otherField.value) return true; var otherFieldValue = otherField.value; var value1 = !!isNaN(val) || typeof val=='object'?val:parseFloat(val); var value2 = !!isNaN(otherFieldValue) || typeof otherFieldValue=='object'?otherFieldValue:parseFloat(otherFieldValue); return value1 < value2; }
'use strict'; var greet = function(name) { if (name === undefined) { name = 'world'; } return 'Hello ' + name + '!'; }; module.exports = greet;
//==================FLUX========================= var Reactor = require("client/js/reactor.js"); //=============================================== var IndexPage = React.createClass({ displayName: "IndexPage", propTypes: { device: React.PropTypes.string, children: React.PropTypes.node, route: React.PropTypes.object, history: React.PropTypes.object }, mixins: [Reactor.ReactMixin], getDataBindings() { //The order matter - the list need to be uptop , before the meta state return {} }, buildIndexPage(props, state) { var className= cx({ "p-index": true }); return ( <div className={className} > <div> {`Hello i'm index page`} </div> {this.props.children && React.cloneElement(this.props.children, { device: this.state.device })} </div> ) }, render() { return this.buildIndexPage(this.props, this.state) } }); module.exports = IndexPage;
"use strict"; var esprima = require("esprima"); var estraverse = require("estraverse"); var escodegen = require("escodegen"); var jsstana = require("jsstana"); function stripAsserts(code) { function notAssertStatement(node) { if (node.type == "FunctionDeclaration" && node.id.name.match(/^assert/)) { return false; } var m1 = jsstana.match("(expr (call (ident ?fn) ??))", node); if (m1 && m1.fn.match(/^assert/)) { return false; } var m2 = jsstana.match("(expr (assign = (ident ?fn) ?))", node); if (m2 && m2.fn.match(/^assert/)) { return false; } return true; } var ast = esprima.parse(code, { sourceType: 'module' }); estraverse.replace(ast, { enter: function (node) { if (node !== null && node.type === "BlockStatement") { node.body = node.body.filter(notAssertStatement); return node; } } }) return escodegen.generate(ast); } module.exports = stripAsserts
//Dates: 'june' or 'may' const ambig = require('../_ambig') const dates = `(${ambig.personDate.join('|')})` let list = [ // ==== Holiday ==== { match: '#Holiday (day|eve)', tag: 'Holiday', reason: 'holiday-day' }, // the captain who // ==== WeekDay ==== // sun the 5th { match: '[sun] the #Ordinal', tag: 'WeekDay', reason: 'sun-the-5th' }, //sun feb 2 { match: '[sun] #Date', group: 0, tag: 'WeekDay', reason: 'sun-feb' }, //1pm next sun { match: '#Date (on|this|next|last|during)? [sun]', group: 0, tag: 'WeekDay', reason: '1pm-sun' }, //this sat { match: `(in|by|before|during|on|until|after|of|within|all) [sat]`, group: 0, tag: 'WeekDay', reason: 'sat' }, { match: `(in|by|before|during|on|until|after|of|within|all) [wed]`, group: 0, tag: 'WeekDay', reason: 'wed' }, { match: `(in|by|before|during|on|until|after|of|within|all) [march]`, group: 0, tag: 'Month', reason: 'march' }, //sat november { match: '[sat] #Date', group: 0, tag: 'WeekDay', reason: 'sat-feb' }, // ==== Month ==== //all march { match: `#Preposition [(march|may)]`, group: 0, tag: 'Month', reason: 'in-month' }, //this march { match: `this [(march|may)]`, group: 0, tag: 'Month', reason: 'this-month' }, { match: `next [(march|may)]`, group: 0, tag: 'Month', reason: 'this-month' }, { match: `last [(march|may)]`, group: 0, tag: 'Month', reason: 'this-month' }, // march 5th { match: `[(march|may)] the? #Value`, group: 0, tag: 'Month', reason: 'march-5th' }, // 5th of march { match: `#Value of? [(march|may)]`, group: 0, tag: 'Month', reason: '5th-of-march' }, // march and feb { match: `[(march|may)] .? #Date`, group: 0, tag: 'Month', reason: 'march-and-feb' }, // feb to march { match: `#Date .? [(march|may)]`, group: 0, tag: 'Month', reason: 'feb-and-march' }, //quickly march { match: `#Adverb [(march|may)]`, group: 0, tag: 'Verb', reason: 'quickly-march' }, //march quickly { match: `[(march|may)] #Adverb`, group: 0, tag: 'Verb', reason: 'march-quickly' }, //5th of March { match: '#Value of #Month', tag: 'Date', reason: 'value-of-month' }, //5 March { match: '#Cardinal #Month', tag: 'Date', reason: 'cardinal-month' }, //march 5 to 7 { match: '#Month #Value to #Value', tag: 'Date', reason: 'value-to-value' }, //march the 12th { match: '#Month the #Value', tag: 'Date', reason: 'month-the-value' }, //june 7 { match: '(#WeekDay|#Month) #Value', tag: 'Date', reason: 'date-value' }, //7 june { match: '#Value (#WeekDay|#Month)', tag: 'Date', reason: 'value-date' }, //may twenty five { match: '(#TextValue && #Date) #TextValue', tag: 'Date', reason: 'textvalue-date' }, // in june { match: `in [${dates}]`, group: 0, tag: 'Date', reason: 'in-june' }, { match: `during [${dates}]`, group: 0, tag: 'Date', reason: 'in-june' }, { match: `on [${dates}]`, group: 0, tag: 'Date', reason: 'in-june' }, { match: `by [${dates}]`, group: 0, tag: 'Date', reason: 'by-june' }, { match: `after [${dates}]`, group: 0, tag: 'Date', reason: 'after-june' }, { match: `#Date [${dates}]`, group: 0, tag: 'Date', reason: 'in-june' }, // june 1992 { match: `${dates} #Value`, tag: 'Date', reason: 'june-5th' }, { match: `${dates} #Date`, tag: 'Date', reason: 'june-5th' }, // June Smith { match: `${dates} #ProperNoun`, tag: 'Person', reason: 'june-smith', safe: true }, // june m. Cooper { match: `${dates} #Acronym? (#ProperNoun && !#Month)`, tag: 'Person', reason: 'june-smith-jr' }, // 'second' { match: `#Cardinal [second]`, tag: 'Unit', reason: 'one-second' }, // second quarter // { match: `#Ordinal quarter`, tag: 'Date', reason: 'second-quarter' }, // 'aug 20-21' { match: `#Month #NumberRange`, tag: 'Date', reason: 'aug 20-21' }, // timezones // china standard time { match: `(#Place|#Demonmym|#Time) (standard|daylight|central|mountain)? time`, tag: 'Timezone', reason: 'std-time' }, // eastern time { match: `(eastern|mountain|pacific|central|atlantic) (standard|daylight|summer)? time`, tag: 'Timezone', reason: 'eastern-time', }, // 5pm central { match: `#Time [(eastern|mountain|pacific|central|est|pst|gmt)]`, group: 0, tag: 'Timezone', reason: '5pm-central' }, // central european time { match: `(central|western|eastern) european time`, tag: 'Timezone', reason: 'cet' }, ] module.exports = list
const data = [ { resource: 'Node.js', link:'https://nodejs.org/en/', description: 'Node.js® is a JavaScript runtime built on Chrome\'s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js\' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.' }, { resource: 'Express', link:'https://github.com/expressjs/express', description: 'Fast, unopinionated, minimalist web framework for Node.js' }, { resource: 'React', link:'https://github.com/facebook/react', description: 'A declarative, efficient, and flexible JavaScript library for building user interfaces.' }, { resource: 'Redux', link:'https://github.com/reactjs/redux', description: 'Predictable state container for JavaScript apps' }, { resource: 'React Router 2.0', link:'https://github.com/reactjs/react-router', description: 'A complete routing solution for React.js' }, { resource: 'Aphrodite for CSS', link:'https://github.com/Khan/aphrodite', description: 'Support for colocating your styles with your JavaScript component. It\'s inline styles, but they work!' }, { resource: 'React Helmet', link:'https://github.com/nfl/react-helmet', description: 'A document head manager for React' }, { resource: 'Redial for data fetching', link:'https://github.com/markdalgleish/redial', description: 'Universal data fetching and route lifecycle management for React' }, { resource: 'Babel 6', link:'https://github.com/babel/babel', description: 'Babel is a compiler for writing next generation JavaScript.' }, { resource: 'Webpack', link:'https://github.com/webpack/webpack', description: 'Webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.' }, { resource: 'React Hot Loader', link:'https://github.com/gaearon/react-hot-loader', description: 'Tweak React components in real time.' }, ]; export default data;
var cluster = require('cluster'), fetch = require("fetch"), EventEmitter = require('events').EventEmitter, utillib = require("util"), fs = require("fs"); module.exports = StatBot; function StatBot(options){ EventEmitter.call("this"); options = options || {}; options.childProcesses = options.childProcesses || 5; options.timeout = options.timeout || 10; this.options = options; this.serverList = []; this.workers = {}; this.toBeProcessed = 0; this.workerCount = 0; this.processedCount = 0; this.startTimer = Date.now(); if(cluster.isMaster){ process.nextTick(this.runMaster.bind(this)); }else{ process.nextTick(this.runChild.bind(this)); } } utillib.inherits(StatBot, EventEmitter); StatBot.prototype.handleChildEnd = function(worker){ if(this.workers[worker.pid].url){ this.emitURLData({url:this.workers[worker.pid].url, error:"Child crashed"}); } if(this.options.debug){ console.log("WORKER DIED "+worker.pid); } this.workers[worker.pid] = null; this.workerCount--; if(!this.done && this.workerCount < this.options.childProcesses){ this.addChild(); } } StatBot.prototype.addChild = function(){ var worker; if(!this.serverList.length){ return; } var worker = cluster.fork(); this.workers[worker.pid] = {worker: worker}; this.workerCount++; if(this.options.debug){ console.log("ADDED WORKER "+worker.pid); } worker.on("message", (function(msg) { switch(msg && msg.command){ case "getUrl": this.sendURL(worker); break; case "response": this.handleResponse(worker, msg.data); break; } }).bind(this)); } //+ Jonas Raoni Soares Silva //@ http://jsfromhell.com/array/shuffle [v1.0] StatBot.prototype.arrayShuffle = function(o){ for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; } StatBot.prototype.handleResponse = function(worker, data){ var keys = 0; this.workers[worker.pid].url = null; this.emitURLData(data); this.processedCount++; if(this.processedCount >= this.toBeProcessed){ this.done = true; keys = Object.keys(this.workers); for(var i=0, len=keys.length; i<len; i++){ if(this.workers[keys[i]] && this.workers[keys[i]].worker){ this.workers[keys[i]].worker.kill(); } } this.endTimer = Date.now(); process.nextTick(this.emit.bind(this,"end", this.endTimer - this.startTimer)); } } StatBot.prototype.runMaster = function(){ cluster.on('death', (function(worker) { if(this.workers[worker.pid]){ this.handleChildEnd(worker); } }).bind(this)); this.emit("links", (function(links){ this.startTimer = Date.now(); this.serverList = this.arrayShuffle(links); this.toBeProcessed += links.length; this.handleLinks(); }).bind(this)); } StatBot.prototype.handleLinks = function(){ for(var i=0, len=this.options.childProcesses; i<len; i++){ this.addChild(); } } StatBot.prototype.emitURLData = function(data){ if(data && data.url){ this.emit("url", data); } } StatBot.prototype.sendURL = function(worker){ if(this.serverList.length){ var url = this.serverList.pop(); this.workers[worker.pid].url = url; process.nextTick(worker.send.bind(worker, {url: url})); if(this.options.debug){ console.log("SENT TO WORKER "+worker.pid+" "+url); } }else{ if(this.options.debug){ console.log("KILLING "+worker.pid); } process.nextTick(worker.kill.bind(worker)); } } StatBot.prototype.runChild = function(){ process.on("message", (function(msg){ if(this.options.debug){ console.log(process.pid + " RECEIVED " + JSON.stringify(msg)); } if(msg && msg.url){ this.processURL(msg.url); } }).bind(this)); if(this.options.debug){ console.log(process.pid + " SENT BACK " + JSON.stringify({command: "getUrl"})); } process.nextTick(process.send.bind(process,{command: "getUrl"})); } StatBot.prototype.processURL = function(url){ handleUrl(url, {timeout: this.options.timeout}, (function(err, meta){ var response = {}; if(err){ response = {command: "response", data: { url: url, error: err.message || err }}; process.send(response); if(this.options.debug){ console.log(process.pid + " SENT BACK " + JSON.stringify(response)); console.log(process.pid + " GOING TO DIE"); } process.exit(); // die on error }else{ response = {command: "response", data: { url: url, meta: meta }} if(this.options.debug){ console.log(process.pid + " SENT BACK " + JSON.stringify(response)); } process.send(response); } if(this.options.debug){ console.log(process.pid + " SENT BACK " + JSON.stringify({command: "getUrl"})); } process.nextTick(process.send.bind(process,{command: "getUrl"})); }).bind(this)); } function handleUrl(url, options, callback){ var done = false, timeout = setTimeout(function(){ if(!done){ done = true; callback(new Error("Timeout")); } }, options.timeout * 1000); fetch.fetchUrl( url, { maxResponseLength: 50*1048, disableDecoding: true, headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2', 'Accept-Language':'et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset':'windows-1257,utf-8;q=0.7,*;q=0.3' } }, function(err, meta, body){ clearTimeout(timeout); if(done){ return }; done = true; if(err){ return callback(err); } body = body.toString().replace(/\r?\n/g,"\u0000"); // document type var dtd = body.match(/<\!DOCTYPE[^>]*>/i), dtdname = (dtd && dtd[0] || "").replace(/[\u0000\s]+/g, " "); if(dtdname){ meta.doctype = { doctype: dtdname, pos: dtd.index } } if(meta.cookieJar){ meta.cookieJar = meta.cookieJar.cookies || {}; } // charset var metaList = body.match(/<meta ([^>]*?)>/gi), charset = ""; if(metaList){ for(var i=0, len=metaList.length; i<len; i++){ if(metaList[i].match(/http-equiv\s*=\s*['"]\s*content-type\s*['"]/i)){ ct = metaList[i].match(/content\s*=\s*['"]([^'"]+)['"]/i) ct = (ct && ct[1] && ct[1].split(";").pop() || "").replace(/[\u0000\s]+/g, " ").trim().toUpperCase(); if(ct && (ct = ct.split("=").pop())){ charset = ct; break; } }else if((ct = metaList[i].match(/<meta charset\s*=\s*['"]?([^'"\/>]+)['"]?/i))){ ct = (ct && ct[1] || "").replace(/[\u0000\s]+/g, " ").trim().toUpperCase(); if(ct){ charset = ct; break; } } } } if(charset){ meta.charset = charset; } callback(null, meta); }); }
#!/usr/bin/env node // ./index.js -f tux 'Hello World!' // ______________ // < Hello World! > // -------------- // \ // \ // .--. // |o_o | // |:_/ | // // \ \ // (| | ) // /'\_ _/`\ // \___)=(___/ // // Help output // ----------- // // ./index.js --help // Usage: cowsay <command> <text> [options] // // Configurable speaking cow (and a bit more) // // Commands: // list List the cow templates. // // Options: // -e, --eye <str> The eye string. // -T, --tongue <str> The tongue string. // -f, --cowfile <cow> The cowfile. // -v, --version Displays version information. // -h, --help Displays this help. // // Examples: // $ cowsay 'Hello there!' // $ cowsay -e '*-' 'Heyyy! // $ cowsay -T '++' 'I have a nice tongue! // // Well, this is just a tiny example how to use Tilda. // Documentation can be found at https://github.com/IonicaBizau/tilda. "use strict"; const Tilda = require("../lib") , cowsay = require("cowsay") ; let p = new Tilda({ name: "cowsay" , version: "1.0.0" , description: "Configurable speaking cow (and a bit more)" , documentation: "https://github.com/IonicaBizau/tilda" , examples: [ "cowsay 'Hello there!'" , "cowsay -e '*-' 'Heyyy!" , "cowsay -T '++' 'I have a nice tongue!" ] , notes: "Well, this is just a tiny example how to use Tilda." , args: [{ name: "text" , type: String , desc: "The text to display." , stdin: true }] }, { stdin: true }).option([ { opts: ["eye", "e"] , desc: "The eye string." , name: "str" } , { opts: ["tongue", "T"] , desc: "The tongue string." , name: "str" } , { opts: ["cowfile", "f"] , desc: "The cowfile." , name: "cow" , default: "default" } ]).action([ { name: "list" , desc: "List the cow templates." , options: [ { opts: ["list", "l"], desc: "Display as list", } ] } ]).on("list", action => { cowsay.list((err, list) => { if (err) { return this.exit(err); } let str = list.join(action.options.list.is_provided ? "\n" : ", ") console.log(str); }); }).main(action => { console.log(cowsay.say({ text: action.stdinData || action.args.text || " " , e: action.options.eye.value , T: action.options.tongue.value , f: action.options.cowfile.value })); });
function onAnimalLoved (player, animal) { // TODO: Add this event call from JAVA if (animal.hasTrait('carriable')) { // TODO: Add this function to animal scripting player.status().adjust('animals_carried', 1) } }
// Unfinished // Shadow Momo var obj_list; var cn; function DCInit_MO(colorname){ DCSetCN_MO(colorname); DCChange_MO(); } function DCSetCN_MO(colorname){ cn = colorname; } function DCChange_MO(){ for (var i=0; i < obj_list["length"]; i++){ if (obj_list[i].getAttribute(cn) == "#000000"){ obj_list[i].setAttribute(cn, "#FFFFFF"); document.body.style.backgroundColor = "#000000"; } else { obj_list[i].setAttribute(cn, "#000000"); document.body.style.backgroundColor = "#FFFFFF"; } } } function DCChangeO_MO(id){ if (document.getElementById(id).getAttribute(cn) == "#000000"){ document.getElementById(id).setAttribute(cn, "#FFFFFF"); } else { document.getElementById(id).setAttribute(cn, "#000000"); } } obj_list = document.getElementsByClassName("DColoured"); for (var i = 0; i < obj_list["length"]; i++){ obj_list[i].setAttribute("onclick", "DCChangeO_MO(this.id);") } DCInit_MO("fill") document.getElementById("DCButton").setAttribute("onclick", "DCChange_MO();");
taskName = "Task2"; function Main(bufferElement) { //#region Input var test1 = [ ], test2 = [ ], test3 = [ ], result1, result2, result3; //#endregion //#region Solution function solve(args) { var result, i, len; function solve(params) { var rows = parseInt(params[0]), cols = parseInt(params[1]), tests = parseInt(params[rows + 2]), i, move; for (i = 0; i < tests; i += 1) { move = params[rows + 3 + i]; // Your solution here console.log('yes'); // or console.log('no'); } } return result; } //#endregion //#region Output WriteLine("Result: " + solve(test1)); WriteLine("TEST1: " + (solve(test1) === result1)); WriteLine("TEST2: " + (solve(test2) === result2)); WriteLine("TEST3: " + (solve(test3) === result3)); //#endregion }
/** * Created by Administrator on 2017-4-11. * 显示静态图片 */ var fs = require('fs'); var http = require('http'); // 获取 images文件目录下的图片名 fs.readdir(process.cwd() + '/images', function (err, files) { var _imgHtml = ''; files.forEach(function (val) { _imgHtml += '<img src="/images/'+ val +'">'; }); createWebServer(files,_imgHtml); }); function createWebServer(imgName,imgHtml) { http.createServer(function (req,res) { if(req.url == '/'){ //第一次进入首页时 渲染html 再根据image中的link 来获取图片数据 res.writeHead(200,{'Content-type':'text/html'}); res.end(imgHtml);// 写入image html }else{ imgName.forEach(function (val) { if(req.url == '/images/' + val){ res.writeHead(200,{'Content-type':'image/png'}); var stream = fs.createReadStream(process.cwd() + '/images/' + val); stream.on('data',function (data) { res.write(data); }); stream.on('end',function () { res.end(); }) } }) } }).listen(3000) }
/** * Created by 殿麒 on 2015/9/18. */ logIn.directive('dialoger',function(){ function link($scope,ele){ var window_width = document.documentElement.clientWidth, dialog_left = (window_width - 235) / 2, window_height = document.documentElement.clientHeight, dialog_header = parseFloat($('.dialog-header').css('height'))||0, dialog_center = parseFloat($('.dialog-center').css('height')) || 0, dialog_bottom = parseFloat($('.dialog-bottom').css('height')) || 0, dialog_height = dialog_header + dialog_center + dialog_bottom, dialog_top = (window_height - dialog_height) / 2; $(ele).css({'left':dialog_left + 'px','top':dialog_top + 'px'}); } return { restrict:'E', template:'<div class="dialog-main" ng-transclude></div>', transclude:true, link:link } });
var elements = new Array( "lname", "pass" , "vpass", "fname", "sname" , "address", "city", "pincode" , "email" , "occupation", "ccno" , "ccdate" ); function doBadThing(name , val){ if( val ) document.getElementById( name ).src = "images/sn.gif"; else document.getElementById( name ).src = "images/sy.gif"; return ! val ; } function checkAll(){ ret = true; for (i = 0 ; i < elements.length ; i++ ){ elem = document.getElementById (elements[i]); ret = doBadThing( elements[i] + "_image" , elem.value == "" ); } if( document.all.pass == "" || document.all.pass.value != document.all.vpass.value ) ret = doBadThing( "vpass_image" , 1 ); return ret; }
import Immutable from 'immutable'; import Actions from '../actions/Actions'; const { REQUEST } = Actions; const initialState = Immutable.fromJS({}); export const REQUEST_STATE_KEY = ['API-Request']; export function mutateState(previousState, props, STATE_KEY = []) { let nextState = previousState; for (let key in props){ // eslint-disable-line nextState = nextState.setIn([...STATE_KEY, key], props[key]); } return nextState; } export default function (previousState = initialState, action) { switch (action.type) { case REQUEST.PENDING: case REQUEST.RESOLVED: case REQUEST.REJECTED: return mutateState(previousState, { [action.props.meta.hashCode]: action.props }, REQUEST_STATE_KEY); default: return previousState; } }
/*! * TimeShift.js version 20130811 * * Copyright 2013 Mobile Wellness Solutions MWS Ltd, Sampo Niskanen * Released under the MIT license */ (function() { var root = this; var OriginalDate = root.Date; var TimeShift; if (typeof exports !== 'undefined') { TimeShift = exports; } else { TimeShift = root.TimeShift = {}; } var currentTime = undefined; var timezoneOffset = new OriginalDate().getTimezoneOffset(); function currentDate() { if (currentTime) { return new OriginalDate(currentTime); } else { return new OriginalDate(); } } function realLocalToUtc(realLocal) { return new OriginalDate(realLocal.getTime() - realLocal.getTimezoneOffset()*60*1000 + timezoneOffset*60*1000); } function utcToLocal(utc) { return new OriginalDate(utc.getTime() - timezoneOffset*60*1000); } function localToUtc(local) { return new OriginalDate(local.getTime() + timezoneOffset*60*1000); } function twoDigit(n) { if (n < 10) { return "0" + n; } else { return "" + n; } } function timezoneName() { var zone = "GMT"; var offset = Math.abs(timezoneOffset); if (timezoneOffset < 0) { zone = zone + "+"; } else if (timezoneOffset > 0) { zone = zone + "-"; } else { return zone; } return zone + twoDigit(Math.floor(offset/60)) + twoDigit(offset%60); } /** * Return the current time zone offset in minutes. A value of -60 corresponds to GMT+1, * +60 to GTM-1. Default value is from new Date().getTimezoneOffset(). */ TimeShift.getTimezoneOffset = function() { return timezoneOffset; } /** * Set the time zone offset in minutes. -60 corresponds to GMT+1, +60 to GTM-1. * Changing this will affect the results also for previously created Date instances. */ TimeShift.setTimezoneOffset = function(offset) { timezoneOffset = offset; } /** * Return the currently overridden time value as milliseconds after Jan 1 1970 in UTC time. * The default value is undefined, which indicates using the real current time. */ TimeShift.getTime = function() { return currentTime; } /** * Set the current time in milliseconds after Jan 1 1970 in UTC time. Setting this * to undefined will reset to the real current time. */ TimeShift.setTime = function(time) { currentTime = time; } /** * Access to the original Date constructor. */ TimeShift.OriginalDate = OriginalDate; /** * Mock implementation of Date. */ TimeShift.Date = function() { // Detect whether we're being called with 'new' // From http://stackoverflow.com/questions/367768/how-to-detect-if-a-function-is-called-as-constructor var isConstructor = false; if (this instanceof TimeShift.Date && !this.__previouslyConstructedByTimeShift) { isConstructor = true; this.__previouslyConstructedByTimeShift = true; } if (!isConstructor) { return (new TimeShift.Date()).toString(); } switch (arguments.length) { case 0: this.utc = currentDate(); break; case 1: this.utc = new OriginalDate(arguments[0]); break; case 2: this.utc = realLocalToUtc(new OriginalDate(arguments[0], arguments[1])); break; case 3: this.utc = realLocalToUtc(new OriginalDate(arguments[0], arguments[1], arguments[2])); break; case 4: this.utc = realLocalToUtc(new OriginalDate(arguments[0], arguments[1], arguments[2], arguments[3])); break; case 5: this.utc = realLocalToUtc(new OriginalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4])); break; case 6: this.utc = realLocalToUtc(new OriginalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5])); break; default: this.utc = realLocalToUtc(new OriginalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6])); break; } } TimeShift.Date.prototype.getDate = function() { return utcToLocal(this.utc).getUTCDate(); } TimeShift.Date.prototype.getDay = function() { return utcToLocal(this.utc).getUTCDay(); } TimeShift.Date.prototype.getFullYear = function() { return utcToLocal(this.utc).getUTCFullYear(); } TimeShift.Date.prototype.getHours = function() { return utcToLocal(this.utc).getUTCHours(); } TimeShift.Date.prototype.getMilliseconds = function() { return utcToLocal(this.utc).getUTCMilliseconds(); } TimeShift.Date.prototype.getMinutes = function() { return utcToLocal(this.utc).getUTCMinutes(); } TimeShift.Date.prototype.getMonth = function() { return utcToLocal(this.utc).getUTCMonth(); } TimeShift.Date.prototype.getSeconds = function() { return utcToLocal(this.utc).getUTCSeconds(); } TimeShift.Date.prototype.getUTCDate = function() { return this.utc.getUTCDate(); } TimeShift.Date.prototype.getUTCDay = function() { return this.utc.getUTCDay(); } TimeShift.Date.prototype.getUTCFullYear = function() { return this.utc.getUTCFullYear(); } TimeShift.Date.prototype.getUTCHours = function() { return this.utc.getUTCHours(); } TimeShift.Date.prototype.getUTCMilliseconds = function() { return this.utc.getUTCMilliseconds(); } TimeShift.Date.prototype.getUTCMinutes = function() { return this.utc.getUTCMinutes(); } TimeShift.Date.prototype.getUTCMonth = function() { return this.utc.getUTCMonth(); } TimeShift.Date.prototype.getUTCSeconds = function() { return this.utc.getUTCSeconds(); } TimeShift.Date.prototype.setDate = function() { var d = utcToLocal(this.utc); d.setUTCDate.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setFullYear = function() { var d = utcToLocal(this.utc); d.setUTCFullYear.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setHours = function() { var d = utcToLocal(this.utc); d.setUTCHours.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setMilliseconds = function() { var d = utcToLocal(this.utc); d.setUTCMilliseconds.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setMinutes = function() { var d = utcToLocal(this.utc); d.setUTCMinutes.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setMonth = function() { var d = utcToLocal(this.utc); d.setUTCMonth.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setSeconds = function() { var d = utcToLocal(this.utc); d.setUTCSeconds.apply(d, Array.prototype.slice.call(arguments, 0)); this.utc = localToUtc(d); } TimeShift.Date.prototype.setUTCDate = function() { this.utc.setUTCDate.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.setUTCFullYear = function() { this.utc.setUTCFullYear.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.setUTCHours = function() { this.utc.setUTCHours.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.setUTCMilliseconds = function() { this.utc.setUTCMilliseconds.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.setUTCMinutes = function() { this.utc.setUTCMinutes.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.setUTCMonth = function() { this.utc.setUTCMonth.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.setUTCSeconds = function() { this.utc.setUTCSeconds.apply(this.utc, Array.prototype.slice.call(arguments, 0)); } TimeShift.Date.prototype.getYear = function() { return this.getFullYear() - 1900; } TimeShift.Date.prototype.setYear = function(v) { this.setFullYear(v + 1900); } TimeShift.Date.prototype.getTime = function() { return this.utc.getTime(); } TimeShift.Date.prototype.setTime = function(v) { this.utc.setTime(v); } TimeShift.Date.prototype.getTimezoneOffset = function() { return timezoneOffset; } TimeShift.Date.prototype.toDateString = function() { return utcToLocal(this.utc).toDateString(); } // Wrong TimeShift.Date.prototype.toLocaleDateString = function() { return utcToLocal(this.utc).toLocaleDateString(); } // Wrong TimeShift.Date.prototype.toISOString = function() { return this.utc.toISOString(); } TimeShift.Date.prototype.toGMTString = function() { return this.utc.toGMTString(); } TimeShift.Date.prototype.toUTCString = function() { return this.utc.toUTCString(); } TimeShift.Date.prototype.toString = function() { var wkdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var d = utcToLocal(this.utc); // Mon Mar 05 2012 06:07:08 GMT+0500 return wkdays[d.getUTCDay()] + " " + months[d.getUTCMonth()] + " " + twoDigit(d.getUTCDate()) + " " + d.getUTCFullYear() + " " + twoDigit(d.getUTCHours()) + ":" + twoDigit(d.getUTCMinutes()) + ":" + twoDigit(d.getUTCSeconds()) + " " + timezoneName(); } TimeShift.Date.prototype.toLocaleString = function() { return this.toString(); } // Wrong TimeShift.Date.prototype.toLocaleTimeString = function() { return this.toString(); } // Wrong TimeShift.Date.prototype.toTimeString = function() { return this.toString(); } // Wrong TimeShift.Date.prototype.toJSON = function() { return this.utc.toJSON(); } TimeShift.Date.prototype.valueOf = function() { return this.utc.getTime(); } TimeShift.Date.now = function() { return currentDate().getTime(); } TimeShift.Date.parse = OriginalDate.parse; // Wrong TimeShift.Date.UTC = OriginalDate.UTC; /** * Helper method that describes a Date object contents. */ TimeShift.Date.prototype.desc = function() { return "utc=" + this.utc.toUTCString() + " local=" + utcToLocal(this.utc).toUTCString() + " offset=" + timezoneOffset; } }).call(this); var time = prompt("Pick a time in MS since epoc"); Date = TimeShift.Date; TimeShift.setTime(time);
/******************************** ** Module dependencies ********************************/ var utils = require('./utils'), debug = require('debug')('gaia.injector'); var Injector = { dependencies: {}, getInjectMethod: function(target) { if ('$inject' === utils.getFnName(target)) { return 'function'; } if (undefined !== target.$inject) { return "property"; } return null; }, /** * Inject dependencies or return without do nothing */ processInject: function(target) { if (!target) return target; var injectMethod = this.getInjectMethod(target); if (null === injectMethod) { return target; } debug('processInject for %s', utils.getFnName(target)); var args = []; switch (injectMethod) { case 'function': var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var text = target.toString(); var matches = text.match(FN_ARGS); args = matches[1] ? matches[1].split(',') : []; return target.apply(target, this.getDependencies(args)); case 'property': args = [target].concat(this.getDependencies(target.$inject)); return new(Function.prototype.bind.apply(target, args)); } }, /** * Inject and register */ processInjectAndRegister: function(name, target) { if (!target) return target; target = this.processInject(target); this.register(name, target); return target; }, /** * Get object in the injector */ get: function(dep) { return this.dependencies[dep]; }, /** * Get all dependencies */ getDependencies: function(arr) { return arr.map(function(value) { var toInject = value.trim(); if (!this.dependencies[toInject]) { debug("Unknown dependency " + toInject); return null; } return this.dependencies[toInject]; }, this); }, /** * Register an object in injector */ register: function(name, dependency) { debug('register %s', name); return this.dependencies[name] = dependency; }, /** * Unregister object */ unregister: function(name) { debug('unregister %s', name); if (this.dependencies[name]) delete this.dependencies[name]; } }; //tiny reference Injector.p = Injector.processInject; Injector.register('$injector', Injector); module.exports = Injector;
var UserModel = require('./models').UserModel , error = require('./error') , _ = require('underscore') , async = require('async'); /** * Create new dummy user for debugging. THIS IS NOT PRODUCTION CODE. * * @param {Object} The parsed and validated json from the client. * @param {Function} Callback to execute after inserting. The argument is an error object. * @api private */ exports.initDebugUser = function() { var username = 'test'; UserModel.findOne({username: username}, function(err, user){ if (err || !user) { console.log('Attempting to create new debug user...'); var master_user = new UserModel({username: username}); master_user.save(function(err) { if (err) { console.log('Failed to create new debug user...') } console.log('Successfully created new debug user...') }); } else { console.log('DEBUG USER: ', user); } }); } /** * Updates the used_by field of a list of packages with a dependent package id in parallel. Doesn't create duplicates. * * @param {Object} The pkg * @param {Array} The list of maintainers * @param {Function} Callback to execute after inserting. The argument is an error object if any of the package updates failed. * @api public */ exports.update_user_list_maintains = function(pkg_id, mantainer_id_list, callback) { var funcs = []; // build up list of work to do _.each(mantainer_id_list, function(maintainer_id) { funcs.push(function(inner_callback) { exports.update_user_maintains(pkg_id, maintainer_id, inner_callback); }); }); async.parallel(funcs, function(err, users) { if (err) { callback(error.fail('Failed to update the maintains field of a user. ')) } callback(null, users); }); }; /** * Updates a users maintains field with a package. Doesn't create duplicates. * * @param {Object} The pkg id * @param {Object} The user id * @param {Function} Callback to execute after inserting. The argument is an error object. * @api public */ exports.update_user_maintains = function(pkg_id, maintainer_id, callback) { UserModel.findById(maintainer_id, function(err, user) { if (err) { callback('The user does not exist'); return; }; if (user.maintains.indexOf(pkg_id) === -1) { user.maintains.push( pkg_id ); user.maintains = user.maintains.filter(function(elem, pos) { return user.maintains.indexOf(elem) == pos; }); user.markModified('maintains'); user.save(); } callback(null, user); }); }; /** * Save a new user into the database, assuming data has been validated. * * @param {Object} The parsed and validated json from the client. * @param {Function} Callback to execute after inserting. The argument is an error object. * @api public */ exports.save_new_user = function(pkg_data, callback) { _validate_new_user(data, function(err) { if (err) { if (callback) callback(err); return; } _save_new_user( pkg_data, callback ); }); }; /** * Get user by the username * * @param {Object} The parsed and validated json from the client. * @param {Function} Callback to execute after inserting. The argument is an error object and the id, if found. * @api public */ exports.get_user_by_name = function(username, callback) { UserModel.findOne({username:username}, function(err,user){ if (err || !user){ callback(error.fail('Could not find the user in the database.') ); return; } callback(null, user); }); }; /** * Lookup a collection users in the databse * * @param {Array} A collection of users to look up * @param {Function} Callback to execute after inserting. The argument is an error object * (if necessary) and all the users in an array. The function terminates prematurely if * any of the users couldn't be found. * @api public */ exports.find_users_by_name = function(un_arr, callback) { // all of the lookups we are about to do var pkg_lookups = []; _.each( un_arr, function(un) { pkg_lookups.push( function(inner_callback) { UserModel.findOne( {username: un }, function(err, user) { if (err) { inner_callback(error.fail('The user called \'' + un + '\' does not exist')); return; } inner_callback(null, user); }); // find one }); // push func }); // each // run all of these lookups in parallel, callback is executed if any of them fails async.parallel( pkg_lookups, function(err, users) { if (err) { callback(err); return; } callback(null, users); }); }; /** * Validate new user data. * * @param {Object} The parsed and validated json from the client. * @param {Function} Callback to execute after inserting. The argument is an error object. * @api private */ function _validate_new_user(pkg_data, callback) { if (callback) callback(); // callback with nothing, indicating success }; /** * Save a new user into the database, assuming data has been validated. * * @param {Object} The parsed and validated json from the client. * @param {Function} Callback to execute after inserting. The argument is an error object. * @api private */ function _save_new_user (pkg_data, callback) { var user = new UserModel({ name: pkg_data.name }); user.save( function(err){ if (err) { if (callback) callback( error.fail('DB error creating the new user.') ); return; } if (callback) callback( error.success('Successfully inserted user into the database.') ); }); };
var defaults = require('./defaults'); var Album = module.exports = function (lastfm) { this.lastfm = lastfm; }; Album.prototype.addTags = function (artist, album, tags, callback) { if (!Array.isArray(tags)) { tags = [ tags ]; } var options = defaults.defaultOptions({ 'artist' : artist, 'album' : album, 'tags' : tags.join(','), 'sk' : this.lastfm.sessionCredentials.key }, callback); this.lastfm.api.request('album.addTags', options); }; Album.prototype.getInfo = function (params, callback) { var options = defaults.defaultOptions(params, callback, 'album'); this.lastfm.api.request('album.getInfo', options); }; Album.prototype.getTags = function (params, callback) { if (!params.user) { params.user = this.lastfm.sessionCredentials.username; } var options = defaults.defaultOptions(params, callback, 'tags'); this.lastfm.api.request('album.getTags', options); }; Album.prototype.getTopTags = function (params, callback) { var options = defaults.defaultOptions(params, callback, 'toptags'); this.lastfm.api.request('album.getTopTags', options); }; Album.prototype.removeTag = function (artist, album, tag, callback) { var options = defaults.defaultOptions({ 'artist' : artist, 'album' : album, 'tag' : tag, 'sk' : this.lastfm.sessionCredentials.key }, callback); this.lastfm.api.request('album.removeTag', options); }; Album.prototype.search = function (params, callback) { var options = defaults.defaultOptions(params, callback, 'results'); this.lastfm.api.request('album.search', options); };
/* Copyright 2013-2016 ASIAL CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import internal from '../../ons/internal'; /** * @class AnimatorCSS - implementation of Animator class using css transitions */ class AnimatorCSS { /** * @method animate * @desc main animation function * @param {Element} element * @param {Object} finalCSS * @param {number} [duration=200] - duration in milliseconds * @return {Object} result * @return {Function} result.then(callback) - sets a callback to be executed after the animation has stopped * @return {Function} result.stop(options) - stops the animation; if options.stopNext is true then it doesn't call the callback * @return {Function} result.finish(ms) - finishes the animation in the specified time in milliseconds * @return {Function} result.speed(ms) - sets the animation speed so that it finishes as if the original duration was the one specified here * @example * ```` * var result = animator.animate(el, {opacity: 0.5}, 1000); * * el.addEventListener('click', function(e){ * result.speed(200).then(function(){ * console.log('done'); * }); * }, 300); * ```` */ animate(el, final, duration = 200) { var start = (new Date()).getTime(), initial = {}, stopped = false, next = false, timeout = false, properties = Object.keys(final); var updateStyles = () => { let s = window.getComputedStyle(el); properties.forEach(s.getPropertyValue.bind(s)); s = el.offsetHeight; }; var result = { stop: (options = {}) => { timeout && clearTimeout(timeout); var k = Math.min(1, ((new Date()).getTime() - start) / duration); properties.forEach(i => { el.style[i] = (1 - k) * initial[i] + k * final[i] + (i == 'opacity' ? '' : 'px'); }); el.style.transitionDuration = '0s'; if (options.stopNext) { next = false; } else if (!stopped) { stopped = true; next && next(); } return result; }, then: (cb) => { next = cb; if (stopped) { next && next(); } return result; }, speed: (newDuration) => { if (internal.config.animationsDisabled) { newDuration = 0; } if (!stopped) { timeout && clearTimeout(timeout); const passed = (new Date()).getTime() - start; const k = passed / duration; const remaining = newDuration * (1 - k); properties.forEach(i => { el.style[i] = (1 - k) * initial[i] + k * final[i] + (i == 'opacity' ? '' : 'px'); }); updateStyles(); start = el.speedUpTime; duration = remaining; el.style.transitionDuration = duration / 1000 + 's'; properties.forEach(i => { el.style[i] = final[i] + (i == 'opacity' ? '' : 'px'); }); timeout = setTimeout(result.stop, remaining); } return result; }, finish: (milliseconds = 50) => { var k = ((new Date()).getTime() - start) / duration; result.speed(milliseconds / (1 - k)); return result; } }; if (el.hasAttribute('disabled') || stopped || internal.config.animationsDisabled) { return result; } var style = window.getComputedStyle(el); properties.forEach(e => { const v = parseFloat(style.getPropertyValue(e)); initial[e] = isNaN(v) ? 0 : v; }); if (!stopped) { el.style.transitionProperty = properties.join(','); el.style.transitionDuration = duration / 1000 + 's'; properties.forEach(e => { el.style[e] = final[e] + (e == 'opacity' ? '' : 'px'); }); } timeout = setTimeout(result.stop, duration); this._onStopAnimations(el, result.stop); return result; } constructor() { this._queue = []; this._index = 0; } _onStopAnimations(el, listener) { var queue = this._queue; var i = this._index++; queue[el] = queue[el] || []; queue[el][i] = (options) => { delete queue[el][i]; if (queue[el] && queue[el].length == 0) { delete queue[el]; } return listener(options); }; } /** * @method stopAnimations * @desc stops active animations on a specified element * @param {Element|Array} element - element or array of elements * @param {Object} [options={}] * @param {Boolean} [options.stopNext] - the callbacks after the animations won't be called if this option is true */ stopAnimations(el, options = {}) { if (Array.isArray(el)) { return el.forEach(el => { this.stopAnimations(el, options); }); } (this._queue[el] || []).forEach(e => { e(options || {}); }); } /** * @method stopAll * @desc stops all active animations * @param {Object} [options={}] * @param {Boolean} [options.stopNext] - the callbacks after the animations won't be called if this option is true */ stopAll(options = {}) { this.stopAnimations(Object.keys(this._queue), options); } /** * @method fade * @desc fades the element (short version for animate(el, {opacity: 0})) * @param {Element} element * @param {number} [duration=200] */ fade(el, duration = 200) { return this.animate(el, {opacity: 0}, duration); } } export default AnimatorCSS;
/* Version: 0.2.0 Publish Date: October 22, 2014 */ (function () { /* Title: Minerva Header Description: Defines a generic header for the Minerva body container Parameters: mv-Title: The title of the header */ var mvHeader = function() { return { restrict: 'E', replace: true, transclude: true, scope: { mvTitle: '@' }, template:'<div class="mv-header"> \ <div class="mv-title">{{mvTitle}}<ng-transclude></ng-transclude></div> \ </div>' }; }; /* Title: Minerva Body Description: Defines the body of the grid container Parameters: mv-Rows: The number of rows needed in the body grid */ var mvBody = function() { return { restrict: 'E', transclude: true, replace: true, scope: { mvRows: '@' }, template:'<div class="mv-body"> \ <div class="mv-widget-container g{{mvRows}}r"> \ <ng-transclude></ng-transclude> \ </div> \ </div>' }; }; /* Title: Minerva Footer Description: Defines a container for a footer to the body Parameters: N/A */ var mvFooter = function() { return { restrict: 'E', transclude: true, replace: true, template:'<div class="mv-footer"><ng-transclude></ng-transclude></div>' }; }; /* Title: Minerva Row Description: Defines a container for a row of content Parameters: N/A */ var mvRow = function() { return { restrict: 'E', transclude: true, replace: true, template:'<div><ng-transclude></ng-transclude></div>' }; }; /* Title: Minerva Group Description: Defines a container for grouping grid element. This is mostly used to group elements on the same row. It can also be used to define empty sections of the grid as place holders. Parameters: mv-Size: The size of the group with height and width dimensions as a string. */ var mvGroup = function() { return { restrict: 'E', transclude: true, replace: true, scope: { mvSize: '@' }, template:'<div class="g-{{mvSize}} break"><ng-transclude></ng-transclude></div>' }; }; /* Title: Minerva Any Num Description: Define a dynamic table displaying a series of numbers Parameters: mv-Data: Date needed for the table mv-Id: The ID of the inner container mv-ID-Head: The ID of the container header mv-Title: The title of the container mv-Size: The size of the container passed as a string representing the height x width. Ex. "1x3" */ var mvAnyNum = function() { return { restrict: 'E', replace: true, scope: { mvData: '=', mvId: '@', mvIdHead: '@', mvTitle: '@', mvSize: '@' }, template:'<div class="widget g-{{mvSize}}" id="{{mvId}}"> \ <div class="w-head lightbox-head">{{mvTitle}}</div> \ <div class="w-body lightbox-body w-mediumtext"> \ <div class="w-any-num"> \ <table> \ <tr> \ <th ng-repeat="stat in mvData.data"> \ {{stat.title}} \ </th> \ </tr> \ <tr> \ <td ng-repeat="stat in mvData.data"> \ {{stat.number}} \ </td> \ </tr> \ </table> \ </div> \ </div> \ <div class="w-any-num-title">{{mvData.title}}</div> \ </div>' }; }; /* Title: Minerva ID Box Description: Defines an empty grid container of a specified size Parameters: mv-ID: The ID of the inner container mv-Title: The title of the container mv-Size: The size of the container passed as a string representing the height x width. Ex. "3x3" */ var mvIdBox = function() { return { restrict: 'E', transclude: true, replace: true, scope: { mvId: '@', mvTitle: '@', mvSize: '@' }, template:'<div class="widget g-{{mvSize}}" id="{{mvId}}"> \ <div class="w-head lightbox-head">{{mvTitle}}</div> \ <div class="w-body lightbox-body"> \ <ng-transclude></ng-transclude> \ </div> \ </div>' }; }; /* Title: Minerva Table Description: Defines a generic table Parameters: mv-Data: Date needed for the table mv-Id: A unique is given for the table widget mv-Title: The title of the table container mv-Size: The size of the container passed as a string representing the height x width. Ex. "3x3" mv-Style: Any custom style for the table */ var mvTable = function() { return { restrict: 'E', replace: true, scope: { mvData: '=', mvId: '@', mvTitle: '@', mvSize: '@', mvStyle: '@' }, template:'<div class="widget g-{{mvSize}}" id="{{mvId}}"> \ <div class="w-head lightbox-head">{{mvTitle}}</div> \ <div class="w-body lightbox-body"> \ <div class="w-table" ng-style="{{mvStyle}}"> \ <table> \ <tr> \ <th ng-repeat="header in mvData.headers">{{header}}</th> \ </tr> \ <tr ng-repeat="row in mvData.rows"> \ <td ng-repeat="col in row" class="{{col.color}}">{{col.value}}</td> \ </tr> \ </table> \ </div> \ </div> \ </div>' }; }; /* Title: Minerva Table List Description: Defines container which contain a series of small tables Parameters: mv-Data: Date needed for the table(s) mv-Id: A unique is given for the table widget mv-Title: The title of the table container mv-Size: The size of the container passed as a string representing the height x width. Ex. "3x3" mv-Style: Any custom style for the table */ var mvTableList = function() { return { restrict: 'E', replace: true, scope: { mvData: '=', mvId: '@', mvTitle: '@', mvSize: '@', mvStyle: '@' }, template:'<div class="widget g-{{mvSize}}" id="{{mvId}}"> \ <div class="w-head lightbox-head">{{mvTitle}}</div> \ <div class="w-body lightbox-body"> \ <div class="w-table-list" ng-style="{{mvStyle}}"> \ <table ng-repeat="stats in mvData"> \ <tr><th class="mv-table-list-title" colspan="2">{{stats.title}}</th></tr> \ <tr ng-repeat="stat in stats.data"> \ <th>&emsp;<span class="w-c{{$index}}">&emsp;</span> {{stat.title}}</th> \ <td>{{stat.number}}</td> \ </tr> \ <tr><td>&nbsp;</td></tr> \ </table> \ </div> \ </div> \ </div>' }; }; /* Title: mvChart Description: create a variety of charts using D3.js Parameters: mvData - dataset for the chart to read mvOptions - chart options to pass in, you only need to pass in values to override defaults */ var mvChart = function() { return { restrict: 'E', scope: { mvData: '=', mvOptions: '=' }, link: function(scope, element, attrs, ctrl, transclude) { //set defaults var defaultOptions = { chart: { height: 450, width: 640, margin: { top: 40, right: 20, bottom: 20, left: 50 }, colors: ["#427A82", "#51BF96", "#FBD163", "#F29A3F", "#DB5957"], backgroundColor: '#F3F3F3', sort: '', inverse: false, type: 'bar' }, legend: { enabled: false, color: '#A6A6A6' }, tooltip: { color: '#888888', format: '' }, xAxis: { title: { color: '#A6A6A6', size: '0.7em', text: '' }, labels: { format: '', color: '#A6A6A6' }, orient: 'bottom' }, yAxis: { title: { color: '#A6A6A6', size: '0.7em', text: 'Y Axis' }, labels: { format: '0', color: '#A6A6A6' }, orient: 'left', min: 0 }, types: { bar: { stacked: false, grouped: false, stacking: 'normal' //'normal' or 'percent' }, pie: { labels: { enabled: false, color: '#FFFFFF' }, burst: false, scale: 100, innerRadius: 0 }, bubble: { scale: 60 }, map: { mapfile: 'us-states', quantizeScale: [0, 100], globe: false, grid: false, zoom: false, rotate: false } } }; //merge the default options with the passed in options var o = extendDeep(defaultOptions, scope.mvOptions); //set the attributes of the chart //margin and height/width var margin = o.chart.margin, height = o.chart.height - margin.top - margin.bottom, width = o.chart.width - margin.left - margin.right; //chart orientation var xOrient = o.xAxis.orient; var yOrient = o.yAxis.orient; if (o.chart.inverse == true) { //flip chart orientation } //scale var xPadding = 1; //padding between x values switch (o.chart.type) { case 'bar': xPadding = .1; //axis label centered on bar break; case 'line': xPadding = 1; //axis label aligned with value break; } var x = d3.scale.ordinal() .rangeRoundBands([0, width], xPadding, 1); var y = d3.scale.linear() .range([height, 0]); //colors var color = d3.scale.ordinal() .range(o.chart.colors); //x axis formatting var xAxis = d3.svg.axis() .scale(x) .orient(xOrient); if (o.xAxis.labels.format != '') { xAxis.tickFormat(d3.format(o.xAxis.labels.format)); } //y axis formatting var yAxis = d3.svg.axis() .scale(y) .orient(yOrient); if (o.yAxis.labels.format != '') { yAxis.tickFormat(d3.format(o.yAxis.labels.format)); } //create svg element var svg = d3.select(element[0]).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .attr('fill', o.chart.backgroundColor) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); data = scope.mvData; //create map of keys color.domain(d3.keys(data[0]).filter(function(key) { return key !== 'x'; })); data.forEach(function(d) { d.y = +d.y; }); //tooltip var tip = d3.tip() .attr('class', 'mvTip') .offset([-10, 0]) .html(function(d) { var title = d.x; var data = tipformat(d.y); switch (o.chart.type) { case 'bar': if (o.types.bar.stacked == true) { var data = tipformat(d.y1 - d.y0); //calculate difference between two y values } break; case 'bubble': title = d.id + '<br/>' + d.label; data = tipformat(d.value); break; case 'pie': title = d.data.x; data = tipformat(d.data.y); break; case 'scatter': title = d.z; data = d.x + ', ' + d.y; break; case 'map': //TODO: fix title = d.id; data = ''; } return '<strong>' + title + ':</strong> <span style="color:' + o.tooltip.color + '">' + data + '</span>'; }); svg.call(tip); switch (o.chart.type) { case 'pie': var radius = Math.min(width, height) / 2; //define pie var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.y; }); //define arc if (o.types.pie.burst == false) { var arc = d3.svg.arc() .outerRadius(radius - 10) .innerRadius(o.types.pie.innerRadius); //increase inner radius to create donut chart } else //burst chart arc { var arc = d3.svg.arc() .outerRadius(function (d) { return (radius - o.types.pie.innerRadius) * (d.data.y / o.types.pie.scale) + o.types.pie.innerRadius; }) .innerRadius(o.types.pie.innerRadius); } //redo color domain for pie data color.domain(d3.keys(data[0].data).filter(function(key) { return key !== 'x'; })); var g = svg.selectAll(".arc") .data(pie(data)) .enter().append("g") .attr("class", "arc") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data.x); }) //colors of pie slices .on('mouseover', tip.show) .on('mouseout', tip.hide); if (o.types.pie.labels.enabled == true) { g.append("text") .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; }) .attr("dy", ".35em") .style("text-anchor", "middle") .text(function(d) { return d.data.x; }) .style('fill', o.types.pie.labels.color); } break; case 'map': var map = d3.map(); var g = svg.append("g"); var quantize = d3.scale.quantize() .domain(o.types.map.quantizeScale) .range(d3.range(9).map(function(i) { return 'q' + i; })); var projection = null; data.forEach(function(d) { map.set(d.x, +d.y); }); //define the map file var mapFile = ''; switch (o.types.map.mapfile) { case 'world': mapFile = '../SiteAssets/Minerva/stable/maps/world-50m.txt'; if (o.types.map.globe == true) { projection = d3.geo.orthographic() .scale(width * 0.5) //size of map .translate([width / 2, height / 2]) //move map to center .clipAngle(90); } else //map projection { //d3.geo.equirectangular() projection = d3.geo.mercator() .scale(width / 2 / Math.PI) //size of map .translate([width / 2, height / 2]); //move map to center } break; default: mapFile = '../SiteAssets/Minerva/stable/maps/us.txt'; projection = d3.geo.albersUsa() .scale(width * 1.5) //size of map .translate([width / 2, height / 2]); //move map to center break; } if (o.types.map.zoom == true) { var zoom = d3.behavior.zoom() .scaleExtent([1, 8]) .on("zoom", zoomed); svg.call(zoom) .call(zoom.event); function zoomed() { g.attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')'); } } var path = d3.geo.path() .projection(projection); d3.json(mapFile, function(error, json) { var topoFeature = null; var outlineFeature = null; switch (o.types.map.mapfile) { case 'us-counties': topoFeature = json.objects.counties; outlineFeature = json.objects.states; break; case 'us-states': topoFeature = json.objects.states; outlineFeature = json.objects.states; break; case 'world': topoFeature = json.objects.countries; outlineFeature = json.objects.countries; break; default: topoFeature = json.objects.states; outlineFeature = json.objects.states; break; } if (o.types.map.globe == false) { g.append("g") .attr("class", o.types.map.mapfile) .selectAll("path") .data(topojson.feature(json, topoFeature).features) .enter().append("path") .attr("class", function(d) { return quantize(map.get(d.id)); }) .attr("d", path) .on('mouseover', tip.show) .on('mouseout', tip.hide); g.append("path") .datum(topojson.mesh(json, outlineFeature, function(a, b) { return a !== b; })) .style('fill', 'none') .style('stroke', '#FFFFFF') .style('stroke-linejoin', 'round') .attr("d", path); } else //globe specific code { var time = Date.now(); d3.select(element[0]) .on("mousemove", mousemove) .on("mouseup", mouseup); svg.on("mousedown", mousedown); var globe_shading = svg.append("defs").append("radialGradient") .attr("id", "globe_shading") .attr("cx", "55%") .attr("cy", "45%"); globe_shading.append("stop") .attr("offset","60%").attr("stop-color", "#fff") .attr("stop-opacity","0") globe_shading.append("stop") .attr("offset","100%").attr("stop-color", "#7B8996") .attr("stop-opacity","0.2") //display globe g.append("circle") .attr("cx", width / 2).attr("cy", height / 2) .attr("r", projection.scale()); //display grid if (o.types.map.grid == true) { var graticule = d3.geo.graticule(); g.append("path") .datum(graticule) .attr("class", "graticule") .attr("d", path); } //display the countries g.append("g") .selectAll("path") .data(topojson.feature(json, topoFeature).features) .enter().append("path") .attr("class", function(d) { return 'world ' + quantize(map.get(d.id)); }) .attr("d", path) .on('mouseover', tip.show) .on('mouseout', tip.hide); //display map shading g.append("circle") .attr("cx", width / 2).attr("cy", height / 2) .attr("r", projection.scale()) .style("fill", "url(#globe_shading)"); /* svg.append("g").attr("class","points") .selectAll("text").data(places.features) .enter().append("path") .attr("class", "point") .attr("d", path);*/ function refresh() { svg.selectAll("path").attr("d", path); } var m0, o0; function mousedown() { m0 = [d3.event.pageX, d3.event.pageY]; o0 = projection.rotate(); d3.event.preventDefault(); } function mousemove() { if (m0) { var m1 = [d3.event.pageX, d3.event.pageY] , o1 = [o0[0] + (m1[0] - m0[0]) / 6, o0[1] + (m0[1] - m1[1]) / 6]; o1[1] = o1[1] > 30 ? 30 : o1[1] < -30 ? -30 : o1[1]; projection.rotate(o1); refresh(); } } function mouseup() { if (m0) { mousemove(); m0 = null; } } if (o.types.map.rotate == true) { d3.timer(function() { var dt = Date.now() - time; projection.rotate([10 + 0.003 * dt, 0]); svg.selectAll("path").attr("d", path); }); } } }); break; case 'bubble': var center = {x: width / 2, y: height / 2}; //get the unique key for each group and deduplicate them var uniqueKeys = []; var dedupulicator = {}; data.forEach(function(d, i) { //if it's a new key, add it, otherwise skip it if (dedupulicator[d.x] == undefined) { dedupulicator[d.x] = ''; uniqueKeys.push(d.x); } }); var groupCenters = []; //center of each group uniqueKeys.forEach(function(d, i) { groupCenters[d] = {x: ((width / uniqueKeys.length + 1) * (i + 0.5)), y: height / 2}; }); var groupsX = []; //label position for each group uniqueKeys.forEach(function(d, i) { groupsX[d] = ((width / uniqueKeys.length + 1) * (i + 0.5)); }); var layoutGravity = -0.01, damper = 0.1, nodes = [], force, bubbleView = 'all'; var maxAmount = d3.max(data, function(d) { return parseInt(d.y, 10); } ); var radiusScale = d3.scale.pow().exponent(0.5).domain([0, maxAmount]).range([2, o.types.bubble.scale]); data.forEach(function(d) { var node = { id: d.x, label: d.label, radius: radiusScale(parseInt(d.y, 10)), value: d.y, x: Math.random() * 900, y: Math.random() * 800 }; nodes.push(node); }); nodes.sort(function(a, b) { return b.id - a.id; }); //redo color for nodes color.domain(d3.keys(nodes[0]).filter(function(key) { return key !== 'x'; })); var circles = svg.selectAll('circle') .data(nodes, function(d) { return d.x; }); circles.enter().append('circle') .attr('r', 0) .attr('fill', function(d) { return color(d.id); }) .attr('stroke-width', 1) .attr('stroke', function(d) { return d3.rgb(color(d.id)).darker(); }) .attr('id', function(d) { return 'bubble_' + d.id; }) .on('click', function() { toogleBubble() }) .on('mouseover', tip.show) .on('mouseout', tip.hide); circles.transition().duration(2000).attr('r', function(d) { return d.radius; }); start(); displayStart(); function charge(d) { return -Math.pow(d.radius, 2.0) / 8; } function start() { force = d3.layout.force() .nodes(nodes) .size([width,height]); } function displayStart() { force.gravity(layoutGravity) //start by moving away .charge(charge) .friction(0.9) .on('tick', function(e) { circles.each(moveTowardsGroup(e.alpha)) .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }); }); setTimeout(function() { //delay and then move back towards center force.gravity(layoutGravity) .charge(charge) .friction(0.9) .on('tick', function(e) { circles.each(moveTowardsCenter(e.alpha)) .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }); }); }, 1000); force.start(); } function displayGroupAll() { force.gravity(layoutGravity) .charge(charge) .friction(0.9) .on('tick', function(e) { circles.each(moveTowardsCenter(e.alpha)) .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }); }); force.start(); hideGroups(); } function moveTowardsCenter(alpha) { return function(d) { d.x = d.x + (center.x - d.x) * (damper + 0.02) * alpha; d.y = d.y + (center.y - d.y) * (damper + 0.02) * alpha; } } function displayByGroup() { force.gravity(layoutGravity) .charge(charge) .friction(0.9) .on('tick', function(e) { circles.each(moveTowardsGroup(e.alpha)) .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }); }); force.start(); displayGroups(); } function moveTowardsGroup(alpha) { return function(d) { var target = groupCenters[d.id]; d.x = d.x + (target.x - d.x) * (damper + 0.02) * alpha; d.y = d.y + (target.y - d.y) * (damper + 0.02) * alpha; } } function displayGroups() { var groupsData = d3.keys(groupsX); var groups = svg.selectAll('.groups') .data(groupsData); groups.enter().append('text') .attr('class', 'groups') .attr('fill', '#A6A6A6') .attr('x', function(d) { return groupsX[d]; }) .attr('y', 10) .attr('text-anchor', 'middle') .text(function(d) { return d;}); } function hideGroups() { var groups = svg.selectAll('.groups').remove(); } //toggle the view function toogleBubble() { console.log('toggle'); if (bubbleView == 'all') { displayByGroup(); bubbleView = 'group' } else { displayGroupAll(); bubbleView = 'all' } } break; default: x.domain(data.map(function(d) { return d.x; })); //x axis range y.domain([0, d3.max(data, function(d) { return d.y; })]); //y axis range switch (o.chart.type) { case 'bar': if (o.types.bar.stacked == true || o.types.bar.grouped == true) //stacked or grouped bar chart { if (o.types.bar.grouped == true) //grouped bar chart { //redo color domain to filter out added information color.domain(d3.keys(data[0]).filter(function(key) { return (key !== 'x' && key !== 'y' && key !== 'total' && key !== 'data'); })); var names = d3.keys(data[0]).filter(function(key) { return (key !== 'x' && key !== 'y' && key !== 'total' && key !== 'data'); });; data.forEach(function(d) { d.data = color.domain().map(function(dn) { return {x: dn, y: +d[dn]}; }); }); //add new x1 and domain var x1 = d3.scale.ordinal(); x1.domain(names).rangeRoundBands([0, x.rangeBand()]); y.domain([0, d3.max(data, function(d) { return d3.max(d.data, function(d) { return d.y; }); })]); } else //stacked bar chart { //redo color domain to filter out added information color.domain(d3.keys(data[0]).filter(function(key) { return (key !== 'x' && key !== 'y' && key !== 'total' && key !== 'data'); })); data.forEach(function(d) { var y0 = 0; d.data = color.domain().map(function(dn) { return {x: dn, y0: y0, y1: y0 += +d[dn]}; }); switch(o.types.bar.stacking) { case 'normal': break; case 'percent': d.data.forEach(function(d) { d.y0 /= y0; d.y1 /= y0; }); //change formatting to percentage yAxis.tickFormat(d3.format('0%')); o.tooltip.format = '0%'; break; } d.total = d.data[d.data.length - 1].y1; }); y.domain([0, d3.max(data, function(d) { return d.total; })]); } //create object for legend var multibar = color.domain().map(function(dn) { return { x: dn, values: data.map(function(d) { return {x: d.x, y: +d[dn]}; }) }; }); //create each grouping for stacked or grouped bars var bars = svg.selectAll('.bars') .data(data) .enter().append('g') .attr("class", "g") .attr("transform", function(d) { return "translate(" + x(d.x) + ",0)"; }); bars.selectAll(".bar") .data(function(d) { return d.data }) .enter().append("rect") .attr("class", "bar") .style("fill", function(d) { return color(d.x); }) .on('mouseover', tip.show) .on('mouseout', tip.hide); if (o.types.bar.grouped == true) //grouped bar chart { bars.selectAll('.bar') .attr("x", function(d) { return x1(d.x); }) .attr("y", function(d) { return y(d.y); }) .attr("height", function(d) { return height - y(d.y); }) .attr("width", x1.rangeBand()); } else //stacked bar chart { bars.selectAll('.bar') .attr("y", function(d) { return y(d.y1); }) .attr("height", function(d) { return y(d.y0) - y(d.y1); }) .attr("width", x.rangeBand()) } } else { svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.x); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.y); }) .attr("height", function(d) { return height - y(d.y); }) .style("fill", function(d) { return color(d.x); }) .on('mouseover', tip.show) .on('mouseout', tip.hide); } break; case 'line': //define lines var lines = color.domain().map(function(dn) { return { x: dn, values: data.map(function(d) { return {x: d.x, y: +d[dn]}; }) }; }); //set minimum for y axis var yDomainMin = 0; if (o.yAxis.min == 'min') { yDomainMin = d3.min(lines, function(c) { return d3.min(c.values, function(v) { return v.y; }); }); } else { yDomainMin = parseInt(o.yAxis.min); } //define y axis again to account for multiple lines y.domain([ yDomainMin, d3.max(lines, function(c) { return d3.max(c.values, function(v) { return v.y; }); }) ]); //define line var line = d3.svg.line() .x(function(d) { return x(d.x); }) .y(function(d) { return y(d.y); }); var zn = svg.selectAll(".zn") .data(lines) .enter().append("g") .attr("class", "zn"); zn.append('path') .attr('class', 'line') .attr('d', function(d) { return line(d.values); }) .style('stroke', function(d) { return color(d.x); }); break; case 'scatter': //scatter plot chart //create order var order = {}; data.forEach(function(d) { order[d.z] = ''; }); //redo color domain for z color.domain(d3.keys(order)); svg.selectAll(".dot") .data(data) .enter().append("circle") .attr("class", "dot") .attr("r", 3.5) .attr("cx", function(d) { return x(d.x); }) .attr("cy", function(d) { return y(d.y); }) .style("fill", function(d) { return color(d.z); }) .on('mouseover', tip.show) .on('mouseout', tip.hide); break; } //add x axis svg.append("g") .attr("class", "x axis") //class for x axis .style("fill", o.xAxis.labels.color) //label color for x axis .attr("transform", "translate(0," + height + ")") //height for x axis .call(xAxis); //add y axis svg.append("g") .attr("class", "y axis") .style("fill", o.yAxis.labels.color) .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", o.yAxis.title.size) .style("text-anchor", "end") .style("fill", o.yAxis.title.color) .text(o.yAxis.title.text); break; } //tooltip format var tipformat = d3.format(o.tooltip.format); //chart legend if (o.legend.enabled == true) { var legendData = data; switch (o.chart.type) { case 'line': legendData = lines; //change so that legend uses the line categories instead break; } var legend = svg.selectAll(".legend") .data(legendData) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); //space between legend items legend.append("rect") .attr("x", width - 25) .attr("y", 0) .attr("width", 18) .attr("height", 18) .style("fill", function(d) { return color(d.x) }); legend.append('text') .attr('x', width) .attr('y', 9) .attr('dy', '.35em') .style('fill', o.legend.color) .style('text-anchor', 'start') .text(function(d) { return d.x; }); } //sort chart if (o.chart.sort != '') { sortChart(); } //sort the chart based on different cases function sortChart() { // Copy-on-write since tweens are evaluated after a delay. var x0 = null; switch (o.chart.sort) { case 'y-descending': x0 = x.domain(data.sort(function(a, b) { return d3.descending(a.y, b.y); }) .map(function(d) { return d.x; })) .copy(); break; case 'y-ascending': x0 = x.domain(data.sort(function(a, b) { return d3.ascending(a.y, b.y); }) .map(function(d) { return d.x; })) .copy(); break; case 'x-descending': x0 = x.domain(data.sort(function(a, b) { return d3.descending(a.x, b.x); }) .map(function(d) { return d.x; })) .copy(); break; case 'x-ascending': x0 = x.domain(data.sort(function(a, b) { return d3.ascending(a.x, b.x); }) .map(function(d) { return d.x; })) .copy(); break; } var transition = svg.transition().duration(750), delay = function(d, i) { return i * 50; }; transition.selectAll(".bar") .delay(delay) .attr("x", function(d) { return x0(d.x); }); transition.select(".x.axis") .call(xAxis) .selectAll("g") .delay(delay); } //perform deep extend which merges objects and any sub objects together function extendDeep(dst) { angular.forEach(arguments, function(obj) { if (obj !== dst) { angular.forEach(obj, function(value, key) { if (dst[key] && dst[key].constructor && dst[key].constructor === Object) { extendDeep(dst[key], value); } else { dst[key] = value; } }); } }); return dst; } } } }; //define the minerva angular module and associate all directives angular.module('mvMinerva', []) .directive('mvHeader', mvHeader) .directive('mvBody', mvBody) .directive('mvFooter', mvFooter) .directive('mvRow', mvRow) .directive('mvGroup', mvGroup) .directive('mvAnyNum', mvAnyNum) .directive('mvIdBox', mvIdBox) .directive('mvTableList', mvTableList) .directive('mvTable', mvTable) .directive('mvChart', mvChart); }());
console.log('loading module ngMenu') angular.module('ngMenu', []).directive('ngMenu',function(){ return{ templateUrl: 'ngapp/menu/template.html', link:function ($scope) { $scope.$on("$stateChangeSuccess", function (v) {console.log(v)}) } } }); console.log('loaded module ngMenu') // $rootScope.$on('$stateChangeStart', // function(event, toState, toParams, fromState, fromParams){ // // logic // })
var Mocha = require('mocha').Mocha, mocha; // @hack to avoid path.resolve errors Mocha.prototype.loadFiles = function (fn) { var self = this, suite = this.suite; this.files.forEach(function (file) { suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); suite.emit('post-require', global, file, self); }); fn && fn(); }; mocha = new Mocha({timeout: 1000 * 60, useColors: true}); __specs.forEach(mocha.addFile.bind(mocha)); // @hack __specs is exposed in the VM context mocha.run(__next); // @hack exposed in the VM context
var fs = require('fs'); var express = require('express'); var cfg = require('./config.json'); var key = fs.readFileSync(cfg.key).toString(); var cert = fs.readFileSync(cfg.cert).toString(); var ca = cfg.ca ? fs.readFileSync(cfg.ca).toString() : null; var app = require('express')(); var http = require('http'); var https = require('https'); var server = https.createServer({ key: key, cert: cert, ca: ca}, app); server.listen(8443); var io = require('socket.io')(server); var Ps = require('ps-node'); var debounce = require('debounce'); var slowSendStatus = debounce(sendStatus, 1000); var runningApps = []; var monitorApps = require('./monitor.json'); function monitor() { for (var key in monitorApps) { var app = monitorApps[key]; (function(app){ Ps.lookup({ command: app.process }, function(error, results) { if (error || typeof results === 'undefined ' || results === null) { slowSendStatus(null); return; } var running = results.length > 0; if (runningApps.indexOf(app.id) === -1 && running) { slowSendStatus(null); runningApps.push(app.id) } else if (runningApps.indexOf(app.id) > -1 && !running) { slowSendStatus(null); var index = runningApps.indexOf(app.id); delete runningApps[index]; } }); })(app); } } setInterval(monitor, 5000); io.on('connection', function (socket) { console.log('connected'); sendStatus(socket); socket.on('notification', function(message, socket) { receive(message, socket); }); socket.on('disconnect', function () { }); }); function sendStatus(socket) { var overview = {}; for (var key in monitorApps) { var app = monitorApps[key]; overview[app.id] = isRunning(app); } if (socket) { socket.emit('overview', overview); } else { io.emit('overview', overview); } } function isRunning(app) { return runningApps.indexOf(app.id) !== -1; } function receive(message, socket) { console.log(message); } function send(message, socket) { io.emit('notification', message); }
var dataManager = require('../../core/DataManager'), domSelector = require('../../utils/domSelector'), scpSignals = require('../../core/scpSignals'), Q = require('../../libs/q'), Signal = require('../../libs/signals'), City = require('./City'), body = document.body, LIST_CITY_CLASS = 'list-city', LIST_MARKUP = '<li class="'+LIST_CITY_CLASS+'*">' + '<div class="'+LIST_CITY_CLASS+'-mask"></div>' + '<div class="'+LIST_CITY_CLASS+'-hoverMask"></div>' + '<a class="'+LIST_CITY_CLASS+'-copy"><span class="'+LIST_CITY_CLASS+'-masked">#</span></a>' + '</li>'; module.exports = function(el) { var cities = [], cityEls = [], cityClicked = new Signal(); this.cityClicked = cityClicked; this.init = function() { var cityList = dataManager.getCityList(), currentCityId = dataManager.getCurrentLocation().cityId, html = '', city; cityList.forEach(function(city) { cities.push(new City(city.id)); html += LIST_MARKUP .replace('#', city.abbr) .replace('*', city.id === currentCityId ? ' is-active' : ''); }); el.innerHTML = html; var taskList = []; cityEls = domSelector.all(el, LIST_CITY_CLASS); cityEls.forEach(function(listCityEl, index){ city = cities[index]; taskList.push(city.init(listCityEl, currentCityId === city.cityId)); city.clicked.add(cityClicked.dispatch); }); scpSignals.windowResized.add(onWindowResize); onWindowResize(); return Q.all(taskList); }; function onWindowResize() { var totalHeight = body.offsetHeight, averageHeight = Math.round(totalHeight/cityEls.length), height; cityEls.forEach(function(cityEl, index) { if(index === cityEls.length-1) { height = totalHeight; } else { totalHeight -= averageHeight; height = averageHeight; } cityEl.style.height = height + 'px'; }); } this.update = function(cityId){ var taskList = [], method; cities.forEach(function(city, index){ if(city.cityId === cityId) { method = 'activate'; } else { method = 'deactivate'; } taskList.push(city[method](index/10, true)); }); composeTaskList('removeListeners'); return Q.all(taskList) .then(function(){composeTaskList('addListeners');}); }; this.cover = function(isRightToLeft) { composeTaskList('removeListeners'); return composeTaskList('cover', isRightToLeft === true) .then(function(){composeTaskList('addListeners');}); }; this.uncover = function(isRightToLeft) { composeTaskList('removeListeners'); return composeTaskList('uncover', isRightToLeft === true) .then(function(){composeTaskList('addListeners');}); }; this.show = function() { return composeTaskList('show', true) .then(function(){composeTaskList('addListeners');}); }; this.hide = function() { composeTaskList('removeListeners'); return composeTaskList('hide', false); }; this.dispose = function(){ cityEls = null; scpSignals.windowResized.remove(onWindowResize); composeTaskList('removeListeners'); return Q.all(composeTaskList('dispose')) .then(function(){ cityClicked.removeAll(); cityClicked = null; cities = null; }); }; function composeTaskList(method, isRightToLeft) { var taskList = []; cities.forEach(function(city, index){ taskList.push(city[method](index/10, isRightToLeft)); }); return Q.all(taskList); } };
/* Constructors for SCXML events, since the browser's built-in DOM Events are not ideally suited for that role. */ // the basic constructor: SCxml.Event=function SCxmlEvent(name, type) { this.name=String(name) this.timestamp=new Date().getTime() this.type=type||"platform" } SCxml.Event.prototype={ constructor: SCxml.Event, toString: function (){ return "SCxmlEvent("+this.name+")" }, origin:undefined, origintype:undefined, sendid:undefined, invokeid:undefined, data:undefined, match: function (t) // matches transitions and events, e.g. "user.*" matches "user.login" // the argument is an actual <transtion> element { var patterns=t.getAttribute("event").split(/\s+/) var event=this.name.split(".") overPatterns: for(var i=0, p; p=patterns[i]; i++) { if((p=p.split(".")).length>event.length) continue for(var j=0; j<p.length; j++) if(p[j]!="*" && p[j]!=event[j]) continue overPatterns return true } return false } } // sub-constructors for internal, error and external events: SCxml.InternalEvent=function (name, src) { SCxml.Event.call(this, name, "internal") this.srcElement=src||null } SCxml.InternalEvent.prototype=new SCxml.Event() SCxml.InternalEvent.prototype.constructor=SCxml.InternalEvent SCxml.Error=function (name, src, err) { SCxml.Event.call(this, name) this.srcElement=src||null this.err=err if(src && src.tagName=="send") this.sendid=src.getAttribute("id") } SCxml.Error.prototype=new SCxml.Event() SCxml.Error.prototype.constructor=SCxml.Error SCxml.ExternalEvent=function (name, origin, origintype, invokeid, data) { SCxml.Event.call(this, name, "external") this.origin=origin this.origintype=origintype this.invokeid=invokeid this.data=data } SCxml.ExternalEvent.prototype=new SCxml.Event() SCxml.ExternalEvent.prototype.constructor=SCxml.ExternalEvent SCxml.ExternalEvent.DOMRefCount=1 SCxml.ExternalEvent.targetOfElement=function (e) { if(e instanceof Element) return "//*[@scxmlref=\""+(e.getAttribute("scxmlref") || (e.setAttribute("scxmlref", SCxml.ExternalEvent.DOMRefCount) , SCxml.ExternalEvent.DOMRefCount++))+"\"]" return e } SCxml.ExternalEvent.fromDOMEvent=function (de) { var e=new SCxml.ExternalEvent(de.type, SCxml.ExternalEvent.targetOfElement(de.srcElement), SCxml.EventProcessors.DOM.name) e.timeStamp=de.timeStamp if(de instanceof CustomEvent) e.data=de.detail else for(var prop in de) if(de.hasOwnProperty(prop)) e.data[prop]=SCxml.ExternalEvent.targetOfElement(de[prop]) return e }
'use strict'; // var binding = require('node-cmake')('tessocr'); var path = require('path'); var binary = require('node-pre-gyp'); var binding_path = binary.find(path.resolve(path.join(__dirname, '../package.json'))); var binding = require(binding_path); var _ = require('lodash'); var os = require('os'); var async = require('async'); var Jimp = require("jimp"); var segline = require('./segline'); var utils = require('./utils'); var TESSDATA = utils.findExists([ '/usr/local/share/tessdata', '/usr/share/tesseract-ocr/tessdata' ]); var DEFAULT_OPTIONS = { language: 'eng', psm: 3, tessdata: TESSDATA }; /** * * @returns {Tess} * @constructor */ function Tess() { if (!(this instanceof Tess)) { return new Tess(); } } utils.merge(Tess, binding); Tess.prototype.segline = function (image, options, cb) { if (typeof options === 'function') { cb = options; options = null; } else if (typeof options === 'number') { options = {threshold: options} } options = utils.merge(options); if (image && image.data && image.width && image.height) { cb(null, segline(image.data, image.width, image.height, options)); } else { Jimp.read(image, function (err, image) { cb(null, segline(image.bitmap.data, image.bitmap.width, image.bitmap.height, options)); }); } }; /** * * @param image * @param {Object|Number|Boolean} [options] * @param {String} [options.language] Language * @param {String} [options.language] Language * @param {String} [options.l] Language * @param {String} [options.tessdata] tessdata path * @param {Number} [options.psm] page segment mode * @param {Array} [options.rects] Multi image rects * @param {Number} [options.level] * 0: RIL_BLOCK, // Block of text/image/separator line. * 1: RIL_PARA, // Paragraph within a block. * 2: RIL_TEXTLINE, // Line within a paragraph. * 3: RIL_WORD, // Word within a textline. * 4: RIL_SYMBOL // Symbol/character within a word. * @param {Boolean} [options.textOnly] * @param cb function (err, result) * * Example for result * { * dimensions: [ 1486, 668 ], // image width and height * boxes: [ * { x: 38, y: 0, w: 1448, h: 114, confidence: 77 }, * { x: 99, y: 108, w: 1387, h: 156, confidence: 77 }, * { x: 34, y: 185, w: 1437, h: 88, confidence: 77 }, * { x: 101, y: 256, w: 1356, h: 81, confidence: 77 }, * { x: 31, y: 336, w: 1395, h: 74, confidence: 77 }, * { x: 99, y: 412, w: 1337, h: 83, confidence: 77 }, * { x: 28, y: 487, w: 1417, h: 82, confidence: 77 }, * { x: 96, y: 563, w: 1306, h: 84, confidence: 77 } * ] * } */ Tess.prototype.tokenize = function (image, options, cb) { if (typeof options === 'function') { cb = options; options = cb; } if (typeof options === 'number') { options = {level: options}; } else if (typeof options === 'boolean') { options = {textOnly: true}; } options = parseOptions(options); cb = cb || utils.noop; return binding.tokenize(image, options, cb); }; /** * * @param {Object|String} image The image data or image filename * @param {Object|Function} [options] Options * @param {String} [options.language] Language * @param {String} [options.tessdata] tessdata path * @param {Number} [options.psm] page segment mode * @param {Array} [options.rects] Multi image rects * @param {Function} [cb] Callback */ Tess.prototype.recognize = function (image, options, cb) { if (typeof options === 'function') { cb = options; options = cb; } options = parseOptions(options); cb = cb || utils.noop; return binding.recognize(image, options, function (err, result) { if (err) return cb(err); cb(null, _.trim(result)); }); }; /** * * @param {Object|String} image The image data or image filename * @param {Object|Function} [options] Options * @param {String} [options.language] Language * @param {String} [options.tessdata] tessdata path * @param {Number} [options.psm] Set page segment mode * @param {Array} [options.rects] The rects of image to ocr * @param {Number} [options.jobs] Jobs to run recognize. It is work only when has rects or with segline. * @param {Boolean|Object} [options.segline] Using segline to segment image in rects * @param {Function} [cb] Callback */ Tess.prototype.ocr = function (image, options, cb) { if (typeof options === 'function') { cb = options; options = cb; } options = parseOptions(options); var that = this; var rects = options.rects; var sopts = options.segline; var bitmap; if (image && typeof image === 'object' && image.toBuffer && image.getPixel) { bitmap = image; image = image.toBuffer(); } if (sopts) { if (typeof sopts !== 'object') { sopts = {}; } rects = sopts.rects || rects; if (bitmap) { seglineAndRecognize(bitmap, bitmap.bytesPerPixel, done); } else if (typeof image === 'string' || Buffer.isBuffer(image)) { Jimp.read(image, function (err, image) { seglineAndRecognize(image.bitmap, done); }); } else { throw new Error('Invalid image'); } } else { recognize(rects, done); } function seglineAndRecognize(bitmap, channels, done) { if (typeof channels === 'function') { done = channels; channels = null; } sopts.channels = channels; if (rects) { rects = _.flatten(_.map(rects, function (rect) { sopts.rect = rect; return segline(bitmap.data, bitmap.width, bitmap.height, sopts); })); } else { rects = segline(bitmap.data, bitmap.width, bitmap.height, sopts); } recognize(rects, done); } function recognize(rects, done) { if (!rects) { return that.recognize(image, options, cb); } var jobs = utils.arrange(rects, options.jobs || os.cpus().length); async.map(jobs, function (rects, cb) { options.rects = normalize(rects); that.recognize(image, options, cb); }, done); } function done(err, result) { if (err) return cb(err); result = Array.isArray(result) ? result.join('\n') : result; cb(null, result); } }; function parseOptions(options) { options = options || {}; options.language = options.language || options.lang; if (options.rect && !options.rects) { options.rects = [options.rect]; } return utils.merge({}, DEFAULT_OPTIONS, options); } function normalize(rects) { return rects.map(function (rect) { if (Array.isArray(rect)) return rect; if (rect && typeof rect === 'object') { return [rect.x, rect.y, rect.w, rect.h]; } }) } exports.Tess = exports.tess = Tess;
'use strict'; const _ = require('lodash'); const { Bots } = require('./../../../lib/bot/bots'); const config = require('../../mock'); describe('/bots', function () { describe('Should instantiate bots correctly', function () { let slackBots; beforeEach(function () { slackBots = new Bots(config.BotsTest.bots).getBots(); }); afterEach(function () { slackBots = null; }); describe('Should instantiate bots correctly', function () { it('Should contain bot token and command for bots', function () { expect(slackBots).toBeTruthy(); _.forEach(slackBots, function (botInfo) { expect(botInfo.config.botCommand).toBeTruthy(); }); }); it('Should contain normalized bots', function () { expect(slackBots).toBeTruthy(); _.forEach(slackBots, function (botInfo) { expect(botInfo.config.botCommand['PING-ME']).toBeTruthy(); expect(botInfo.config.botCommand['STOP']).toBeUndefined(); }); }); }); }); describe('Should instantiate bots correctly for recurive tasks', function () { let slackBots; beforeEach(function () { slackBots = new Bots(config.BotsTestWithRecursiveTasks.bots).getBots(); }); afterEach(function () { slackBots = null; }); describe('Should instantiate bots correctly', function () { it('Should contain bot token and command for bots', function () { expect(slackBots).toBeTruthy(); _.forEach(slackBots, function (botInfo) { expect(botInfo.config.botCommand).toBeTruthy(); }); }); it('Should contain normalized bots', function () { expect(slackBots).toBeTruthy(); _.forEach(slackBots, function (botInfo) { expect(botInfo.config.botCommand['PING-ME']).toBeTruthy(); expect(botInfo.config.botCommand['AUTODATA']).toBeTruthy(); expect(botInfo.config.botCommand['STOP']).toBeTruthy(); expect(botInfo.config.botCommand['STOP'].allowedParam).toEqual([ 'AUTODATA', ]); }); }); }); }); });
var Component = require('./component.js'); var Partial = Component.extend(); module.exports = Partial;
define([ 'intern!object', 'intern/chai!expect', '../helper/fixtures/shadow-input.fixture', '../helper/supports', 'ally/maintain/disabled', ], function(registerSuite, expect, shadowInputFixture, supports, maintainDisabled) { registerSuite(function() { var fixture; var handle; var handle2; return { name: 'maintain/disabled', beforeEach: function() { fixture = shadowInputFixture(); }, afterEach: function() { // make sure a failed test cannot leave listeners behind handle && handle.disengage({ force: true }); handle2 && handle2.disengage(); fixture.remove(); fixture = null; }, lifecycle: function() { expect(fixture.input.outer.disabled).to.equal(false, 'before engaged'); handle = maintainDisabled(); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(true, 'after engaged'); handle.disengage(); expect(fixture.input.outer.disabled).to.equal(false, 'after disengaged'); }, 'non-input elements': function() { var element = fixture.add('<div tabindex="0"></div>').firstElementChild; expect(fixture.input.outer.disabled).to.equal(false, 'input before engaged'); expect(element.hasAttribute('data-ally-disabled')).to.equal(false, 'div before engaged'); handle = maintainDisabled(); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(true, 'after engaged'); expect(element.hasAttribute('data-ally-disabled')).to.equal(true, 'div after engaged'); handle.disengage(); expect(fixture.input.outer.disabled).to.equal(false, 'after disengaged'); expect(element.hasAttribute('data-ally-disabled')).to.equal(false, 'div after disengaged'); }, context: function() { handle = maintainDisabled({ context: '#after-wrapper', }); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(false, 'out of context'); expect(fixture.input.after.disabled).to.equal(true, 'in context'); }, filter: function() { handle = maintainDisabled({ filter: '#after-wrapper', }); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(true, 'out of filter'); expect(fixture.input.after.disabled).to.equal(false, 'in filter'); }, 'context and filter': function() { var input = fixture.add('<input id="dyamic-input">').firstElementChild; handle = maintainDisabled({ context: fixture.root, filter: '#after-wrapper, #outer-input', }); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(false, 'in filter'); expect(fixture.input.after.disabled).to.equal(false, 'in filter'); expect(input.disabled).to.equal(true, 'out of filter'); }, 'dom mutation': function() { if (!window.MutationObserver) { this.skip('MutationObserver not supported'); } var deferred = this.async(10000); handle = maintainDisabled({ context: fixture.root, filter: '#after-wrapper, #outer-input', }); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(false, 'in filter'); var input = fixture.add('<input id="dyamic-input">').firstElementChild; // dom mutation is observed asynchronously setTimeout(deferred.callback(function() { expect(input.disabled).to.equal(true, 'added after the fact'); }), 50); }, 'dom mutation (single node)': function() { if (!window.MutationObserver) { this.skip('MutationObserver not supported'); } var deferred = this.async(10000); var input = document.createElement('input'); input.id = 'dynamic-input'; handle = maintainDisabled({ context: '#intern-dom-fixture', filter: '#after-wrapper, #outer-input', }); expect(handle.disengage).to.be.a('function'); expect(fixture.input.outer.disabled).to.equal(false, 'in filter'); fixture.root.appendChild(input); // dom mutation is observed asynchronously setTimeout(deferred.callback(function() { expect(input.disabled).to.equal(true, 'added after the fact'); }), 50); }, 'Shadow DOM': function() { if (!supports.cssShadowPiercingDeepCombinator) { this.skip('Shadow DOM "shadow-piercing descendant combinator" not supported'); } handle = maintainDisabled({ context: fixture.root, filter: '#after-wrapper', }); expect(handle.disengage).to.be.a('function'); expect(fixture.input.after.disabled).to.equal(false, 'in filter'); expect(fixture.input.first.disabled).to.equal(true, 'out of filter'); }, 'concurrent instances': function() { var container = fixture.add('<input type="text" id="dynamic-input">', 'dynamic-wrapper'); var input = container.firstElementChild; handle = maintainDisabled({ context: '#after-wrapper', }); expect(fixture.input.outer.disabled).to.equal(false); expect(fixture.input.after.disabled).to.equal(true, 'alpha after first handle'); expect(input.disabled).to.equal(false, 'bravo after first handle'); handle2 = maintainDisabled({ context: container, }); expect(fixture.input.outer.disabled).to.equal(false); expect(fixture.input.after.disabled).to.equal(true, 'alpha after second handle'); expect(input.disabled).to.equal(true, 'bravo after second handle'); handle.disengage(); expect(fixture.input.after.disabled).to.equal(false, 'alpha after disengaging first handle'); expect(input.disabled).to.equal(true, 'bravo after disengaging first handle'); }, }; }); });
export const countries = [ {'name': 'Afghanistan', 'code': 'AF'}, {'name': 'land Islands', 'code': 'AX'}, {'name': 'Albania', 'code': 'AL'}, {'name': 'Algeria', 'code': 'DZ'}, {'name': 'American Samoa', 'code': 'AS'}, {'name': 'AndorrA', 'code': 'AD'}, {'name': 'Angola', 'code': 'AO'}, {'name': 'Anguilla', 'code': 'AI'}, {'name': 'Antarctica', 'code': 'AQ'}, {'name': 'Antigua and Barbuda', 'code': 'AG'}, {'name': 'Argentina', 'code': 'AR'}, {'name': 'Armenia', 'code': 'AM'}, {'name': 'Aruba', 'code': 'AW'}, {'name': 'Australia', 'code': 'AU'}, {'name': 'Austria', 'code': 'AT'}, {'name': 'Azerbaijan', 'code': 'AZ'}, {'name': 'Bahamas', 'code': 'BS'}, {'name': 'Bahrain', 'code': 'BH'}, {'name': 'Bangladesh', 'code': 'BD'}, {'name': 'Barbados', 'code': 'BB'}, {'name': 'Belarus', 'code': 'BY'}, {'name': 'Belgium', 'code': 'BE'}, {'name': 'Belize', 'code': 'BZ'}, {'name': 'Benin', 'code': 'BJ'}, {'name': 'Bermuda', 'code': 'BM'}, {'name': 'Bhutan', 'code': 'BT'}, {'name': 'Bolivia', 'code': 'BO'}, {'name': 'Bosnia and Herzegovina', 'code': 'BA'}, {'name': 'Botswana', 'code': 'BW'}, {'name': 'Bouvet Island', 'code': 'BV'}, {'name': 'Brazil', 'code': 'BR'}, {'name': 'British Indian Ocean Territory', 'code': 'IO'}, {'name': 'Brunei Darussalam', 'code': 'BN'}, {'name': 'Bulgaria', 'code': 'BG'}, {'name': 'Burkina Faso', 'code': 'BF'}, {'name': 'Burundi', 'code': 'BI'}, {'name': 'Cambodia', 'code': 'KH'}, {'name': 'Cameroon', 'code': 'CM'}, {'name': 'Canada', 'code': 'CA'}, {'name': 'Cape Verde', 'code': 'CV'}, {'name': 'Cayman Islands', 'code': 'KY'}, {'name': 'Central African Republic', 'code': 'CF'}, {'name': 'Chad', 'code': 'TD'}, {'name': 'Chile', 'code': 'CL'}, {'name': 'China', 'code': 'CN'}, {'name': 'Christmas Island', 'code': 'CX'}, {'name': 'Cocos (Keeling) Islands', 'code': 'CC'}, {'name': 'Colombia', 'code': 'CO'}, {'name': 'Comoros', 'code': 'KM'}, {'name': 'Congo', 'code': 'CG'}, {'name': 'Congo, The Democratic Republic of the', 'code': 'CD'}, {'name': 'Cook Islands', 'code': 'CK'}, {'name': 'Costa Rica', 'code': 'CR'}, {'name': 'Cote D\'Ivoire', 'code': 'CI'}, {'name': 'Croatia', 'code': 'HR'}, {'name': 'Cuba', 'code': 'CU'}, {'name': 'Cyprus', 'code': 'CY'}, {'name': 'Czech Republic', 'code': 'CZ'}, {'name': 'Denmark', 'code': 'DK'}, {'name': 'Djibouti', 'code': 'DJ'}, {'name': 'Dominica', 'code': 'DM'}, {'name': 'Dominican Republic', 'code': 'DO'}, {'name': 'Ecuador', 'code': 'EC'}, {'name': 'Egypt', 'code': 'EG'}, {'name': 'El Salvador', 'code': 'SV'}, {'name': 'Equatorial Guinea', 'code': 'GQ'}, {'name': 'Eritrea', 'code': 'ER'}, {'name': 'Estonia', 'code': 'EE'}, {'name': 'Ethiopia', 'code': 'ET'}, {'name': 'Falkland Islands (Malvinas)', 'code': 'FK'}, {'name': 'Faroe Islands', 'code': 'FO'}, {'name': 'Fiji', 'code': 'FJ'}, {'name': 'Finland', 'code': 'FI'}, {'name': 'France', 'code': 'FR'}, {'name': 'French Guiana', 'code': 'GF'}, {'name': 'French Polynesia', 'code': 'PF'}, {'name': 'French Southern Territories', 'code': 'TF'}, {'name': 'Gabon', 'code': 'GA'}, {'name': 'Gambia', 'code': 'GM'}, {'name': 'Georgia', 'code': 'GE'}, {'name': 'Germany', 'code': 'DE'}, {'name': 'Ghana', 'code': 'GH'}, {'name': 'Gibraltar', 'code': 'GI'}, {'name': 'Greece', 'code': 'GR'}, {'name': 'Greenland', 'code': 'GL'}, {'name': 'Grenada', 'code': 'GD'}, {'name': 'Guadeloupe', 'code': 'GP'}, {'name': 'Guam', 'code': 'GU'}, {'name': 'Guatemala', 'code': 'GT'}, {'name': 'Guernsey', 'code': 'GG'}, {'name': 'Guinea', 'code': 'GN'}, {'name': 'Guinea-Bissau', 'code': 'GW'}, {'name': 'Guyana', 'code': 'GY'}, {'name': 'Haiti', 'code': 'HT'}, {'name': 'Heard Island and Mcdonald Islands', 'code': 'HM'}, {'name': 'Holy See (Vatican City State)', 'code': 'VA'}, {'name': 'Honduras', 'code': 'HN'}, {'name': 'Hong Kong', 'code': 'HK'}, {'name': 'Hungary', 'code': 'HU'}, {'name': 'Iceland', 'code': 'IS'}, {'name': 'India', 'code': 'IN'}, {'name': 'Indonesia', 'code': 'ID'}, {'name': 'Iran, Islamic Republic Of', 'code': 'IR'}, {'name': 'Iraq', 'code': 'IQ'}, {'name': 'Ireland', 'code': 'IE'}, {'name': 'Isle of Man', 'code': 'IM'}, {'name': 'Israel', 'code': 'IL'}, {'name': 'Italy', 'code': 'IT'}, {'name': 'Jamaica', 'code': 'JM'}, {'name': 'Japan', 'code': 'JP'}, {'name': 'Jersey', 'code': 'JE'}, {'name': 'Jordan', 'code': 'JO'}, {'name': 'Kazakhstan', 'code': 'KZ'}, {'name': 'Kenya', 'code': 'KE'}, {'name': 'Kiribati', 'code': 'KI'}, {'name': 'Korea, Democratic People\'S Republic of', 'code': 'KP'}, {'name': 'Korea, Republic of', 'code': 'KR'}, {'name': 'Kuwait', 'code': 'KW'}, {'name': 'Kyrgyzstan', 'code': 'KG'}, {'name': 'Lao People\'S Democratic Republic', 'code': 'LA'}, {'name': 'Latvia', 'code': 'LV'}, {'name': 'Lebanon', 'code': 'LB'}, {'name': 'Lesotho', 'code': 'LS'}, {'name': 'Liberia', 'code': 'LR'}, {'name': 'Libyan Arab Jamahiriya', 'code': 'LY'}, {'name': 'Liechtenstein', 'code': 'LI'}, {'name': 'Lithuania', 'code': 'LT'}, {'name': 'Luxembourg', 'code': 'LU'}, {'name': 'Macao', 'code': 'MO'}, {'name': 'Macedonia, The Former Yugoslav Republic of', 'code': 'MK'}, {'name': 'Madagascar', 'code': 'MG'}, {'name': 'Malawi', 'code': 'MW'}, {'name': 'Malaysia', 'code': 'MY'}, {'name': 'Maldives', 'code': 'MV'}, {'name': 'Mali', 'code': 'ML'}, {'name': 'Malta', 'code': 'MT'}, {'name': 'Marshall Islands', 'code': 'MH'}, {'name': 'Martinique', 'code': 'MQ'}, {'name': 'Mauritania', 'code': 'MR'}, {'name': 'Mauritius', 'code': 'MU'}, {'name': 'Mayotte', 'code': 'YT'}, {'name': 'Mexico', 'code': 'MX'}, {'name': 'Micronesia, Federated States of', 'code': 'FM'}, {'name': 'Moldova, Republic of', 'code': 'MD'}, {'name': 'Monaco', 'code': 'MC'}, {'name': 'Mongolia', 'code': 'MN'}, {'name': 'Montenegro', 'code': 'ME'}, {'name': 'Montserrat', 'code': 'MS'}, {'name': 'Morocco', 'code': 'MA'}, {'name': 'Mozambique', 'code': 'MZ'}, {'name': 'Myanmar', 'code': 'MM'}, {'name': 'Namibia', 'code': 'NA'}, {'name': 'Nauru', 'code': 'NR'}, {'name': 'Nepal', 'code': 'NP'}, {'name': 'Netherlands', 'code': 'NL'}, {'name': 'Netherlands Antilles', 'code': 'AN'}, {'name': 'New Caledonia', 'code': 'NC'}, {'name': 'New Zealand', 'code': 'NZ'}, {'name': 'Nicaragua', 'code': 'NI'}, {'name': 'Niger', 'code': 'NE'}, {'name': 'Nigeria', 'code': 'NG'}, {'name': 'Niue', 'code': 'NU'}, {'name': 'Norfolk Island', 'code': 'NF'}, {'name': 'Northern Mariana Islands', 'code': 'MP'}, {'name': 'Norway', 'code': 'NO'}, {'name': 'Oman', 'code': 'OM'}, {'name': 'Pakistan', 'code': 'PK'}, {'name': 'Palau', 'code': 'PW'}, {'name': 'Palestinian Territory, Occupied', 'code': 'PS'}, {'name': 'Panama', 'code': 'PA'}, {'name': 'Papua New Guinea', 'code': 'PG'}, {'name': 'Paraguay', 'code': 'PY'}, {'name': 'Peru', 'code': 'PE'}, {'name': 'Philippines', 'code': 'PH'}, {'name': 'Pitcairn', 'code': 'PN'}, {'name': 'Poland', 'code': 'PL'}, {'name': 'Portugal', 'code': 'PT'}, {'name': 'Puerto Rico', 'code': 'PR'}, {'name': 'Qatar', 'code': 'QA'}, {'name': 'Reunion', 'code': 'RE'}, {'name': 'Romania', 'code': 'RO'}, {'name': 'Russian Federation', 'code': 'RU'}, {'name': 'RWANDA', 'code': 'RW'}, {'name': 'Saint Helena', 'code': 'SH'}, {'name': 'Saint Kitts and Nevis', 'code': 'KN'}, {'name': 'Saint Lucia', 'code': 'LC'}, {'name': 'Saint Pierre and Miquelon', 'code': 'PM'}, {'name': 'Saint Vincent and the Grenadines', 'code': 'VC'}, {'name': 'Samoa', 'code': 'WS'}, {'name': 'San Marino', 'code': 'SM'}, {'name': 'Sao Tome and Principe', 'code': 'ST'}, {'name': 'Saudi Arabia', 'code': 'SA'}, {'name': 'Senegal', 'code': 'SN'}, {'name': 'Serbia', 'code': 'RS'}, {'name': 'Seychelles', 'code': 'SC'}, {'name': 'Sierra Leone', 'code': 'SL'}, {'name': 'Singapore', 'code': 'SG'}, {'name': 'Slovakia', 'code': 'SK'}, {'name': 'Slovenia', 'code': 'SI'}, {'name': 'Solomon Islands', 'code': 'SB'}, {'name': 'Somalia', 'code': 'SO'}, {'name': 'South Africa', 'code': 'ZA'}, {'name': 'South Georgia and the South Sandwich Islands', 'code': 'GS'}, {'name': 'Spain', 'code': 'ES'}, {'name': 'Sri Lanka', 'code': 'LK'}, {'name': 'Sudan', 'code': 'SD'}, {'name': 'Suriname', 'code': 'SR'}, {'name': 'Svalbard and Jan Mayen', 'code': 'SJ'}, {'name': 'Swaziland', 'code': 'SZ'}, {'name': 'Sweden', 'code': 'SE'}, {'name': 'Switzerland', 'code': 'CH'}, {'name': 'Syrian Arab Republic', 'code': 'SY'}, {'name': 'Taiwan, Province of China', 'code': 'TW'}, {'name': 'Tajikistan', 'code': 'TJ'}, {'name': 'Tanzania, United Republic of', 'code': 'TZ'}, {'name': 'Thailand', 'code': 'TH'}, {'name': 'Timor-Leste', 'code': 'TL'}, {'name': 'Togo', 'code': 'TG'}, {'name': 'Tokelau', 'code': 'TK'}, {'name': 'Tonga', 'code': 'TO'}, {'name': 'Trinidad and Tobago', 'code': 'TT'}, {'name': 'Tunisia', 'code': 'TN'}, {'name': 'Turkey', 'code': 'TR'}, {'name': 'Turkmenistan', 'code': 'TM'}, {'name': 'Turks and Caicos Islands', 'code': 'TC'}, {'name': 'Tuvalu', 'code': 'TV'}, {'name': 'Uganda', 'code': 'UG'}, {'name': 'Ukraine', 'code': 'UA'}, {'name': 'United Arab Emirates', 'code': 'AE'}, {'name': 'United Kingdom', 'code': 'GB'}, {'name': 'United States', 'code': 'US'}, {'name': 'United States Minor Outlying Islands', 'code': 'UM'}, {'name': 'Uruguay', 'code': 'UY'}, {'name': 'Uzbekistan', 'code': 'UZ'}, {'name': 'Vanuatu', 'code': 'VU'}, {'name': 'Venezuela', 'code': 'VE'}, {'name': 'Viet Nam', 'code': 'VN'}, {'name': 'Virgin Islands, British', 'code': 'VG'}, {'name': 'Virgin Islands, U.S.', 'code': 'VI'}, {'name': 'Wallis and Futuna', 'code': 'WF'}, {'name': 'Western Sahara', 'code': 'EH'}, {'name': 'Yemen', 'code': 'YE'}, {'name': 'Zambia', 'code': 'ZM'}, {'name': 'Zimbabwe', 'code': 'ZW'} ];
const Flint = require('../../../index.js') const supertest = require('supertest') const mongoose = require('mongoose') describe('publicRegistration', () => { let server let agent const signupRoute = '/p/signup' const loginRoute = '/p/login' beforeAll(async () => { const flintServer = new Flint({ listen: false, signupRoute, loginRoute }) server = await flintServer.startServer() agent = supertest.agent(server) const Site = mongoose.model('Site') await Site.findOneAndUpdate({}, { $set: { allowPublicRegistration: true } }).exec() }) it('can sign up a new user', async () => { await agent .post(signupRoute) .send({ username: 'exampler', email: 'example@example.com', password: 'password' }) const User = mongoose.model('User') const foundNewUser = await User.findOne({ username: 'exampler' }).exec() expect(typeof foundNewUser).toBe('object') }) it('can log in that new user', async () => { const res = await agent .post(loginRoute) .send({ email: 'example@example.com', password: 'password' }) expect(res.status).toBe(302) expect(res.header).toHaveProperty('location', '/admin') }) afterAll(() => mongoose.disconnect()) })
;(function(){ // Console wrapper if (typeof console === 'undefined') { var f = function () {}; window.console = { log:f, info:f, warn:f, debug:f, error:f }; } // Helper function inspired by Backbone to trigger an event function quickly var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); } } var PostMessage = function PostMessage(options) { this.initialize(options); } // options = { // target: window.parent or iframe.contentWindow // origin: Host of your application // destination: Host where the message are sent (Ex. http://example.com) // } PostMessage.prototype.initialize = function initialize(options) { if (!options.target) return console.error('You have to specify the target options to post a message.'); if (!options.origin) return console.error('You have to specify the origin options for security reasons.'); if (!options.destination) return console.error('You have to specify the destination options for security reasons.'); var self = this; self._events = []; self._callbacks = {}; self._callbackCounter = 0; self.options = options; self._target = options.target; delete options['target']; var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; self._messageEventHandler = function() { self._messageHandler.apply(self, arguments); }; eventer(messageEvent, self._messageEventHandler, false); } PostMessage.prototype._messageHandler = function _messageHandler(message) { // console.log('Raw message ' + this.options.name, message); if (message.origin !== this.options.destination) return console.warn('Message coming from a different origin: ' + message.origin + ' => ' + this.options.destination); var type = message.data.type; var data = message.data.data; var callbackId = message.data.callbackId; if (!type) return console.warn('Unknown message type'); switch (type) { case 'callback': if (!callbackId) return console.warn('No callbackId provided on callback message'); if (!this._callbacks[callbackId]) return console.warn('Cannot find a callback with ID ' + callbackId); var callback = this._callbacks[callbackId]; delete this._callbacks[callbackId]; callback(data); break; default: if (callbackId && data !== undefined) this.trigger(type, data, this._createCallbackFunction(callbackId)); else if (callbackId) this.trigger(type, this._createCallbackFunction(callbackId)); else if (data !== undefined) this.trigger(type, data); else this.trigger(type); } } PostMessage.prototype._createCallbackFunction = function _createCallbackFunction(callbackId) { var self = this; return function (data) { var newMessage = { type: 'callback', data: data, callbackId: callbackId } self._target.postMessage(newMessage, self.options.destination); } } PostMessage.prototype.emit = function emit(type, data, callback) { if (typeof data === 'function') { callback = data; data = undefined; } if (typeof callback === 'function') { var callbackId = ++this._callbackCounter; this._callbacks[callbackId] = callback; } var newMessage = { type: type, data: data, callbackId: callbackId } this._target.postMessage(newMessage, this.options.destination); } PostMessage.prototype.on = function on(name, callback, context) { if (!callback) return this; var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; } PostMessage.prototype.trigger = function trigger(name) { if (!this._events) return this; var args = [].slice.call(arguments, 1); var events = this._events[name]; if (events) triggerEvents(events, args); return this; } PostMessage.prototype.destroy = function destroy() { var eventMethod = window.removeEventListener ? "removeEventListener" : "detachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "detachEvent" ? "onmessage" : "message"; eventer(messageEvent, this._messageEventHandler, false); } if (typeof exports == 'object') { exports = module.exports = PostMessage; } else if (typeof define == 'function' && define.amd) { define(function(){ return PostMessage; }); } else { window['PostMessage'] = PostMessage; } })();
import React, { Component } from 'react'; import {setColor} from '../../actions/image'; import { SketchPicker } from 'react-color'; if (process.env.WEBPACK) require('./css/ColorPicker.scss'); import { connect } from 'react-redux'; import Button from '../components/button'; import ClickOutside from 'react-click-outside'; @connect((state) => { const {image} = state; return {image}; }, {setColor}) export default class ColorPicker extends Component { state = { color: '#fff' }; handleChangeColor = (color) => { this.props.setColor(color.hex); }; hide = () => this.setState({colorPickerOpened: false}); render() { const colorStyle = {background: this.props.image.color}; return (<div className="color-picker"> <span>Color: </span> <div className="text-color" style={colorStyle} onClick={() => {!this.state.colorPickerOpened && this.setState({colorPickerOpened: true})}}> {this.state.colorPickerOpened && <ClickOutside onClickOutside={::this.hide}> <div className="text-color-picker"> <SketchPicker color={ this.state.color } onChangeComplete={ this.handleChangeColor }/> <Button type="square" onClick={this.hide}>done</Button> </div> </ClickOutside>} </div> </div>); } }
module.exports = function(a, b) { return a + b; };
// Regular expression that matches all symbols in the `Devanagari` script as per Unicode v5.2.0: /[\u0900-\u0939\u093C-\u094E\u0950\u0953-\u0955\u0958-\u0963\u0966-\u096F\u0971\u0972\u0979-\u097F\uA8E0-\uA8FB]/;
angular .module('ScheduleModule') .factory('authorityEnum', function() { return { USER: 'USER', ADMIN: 'ADMIN' } });
var mongoose = require('mongoose'), shortid = require('shortid'), helpers = require('./model_helpers'), user = require('./user'), Schema = mongoose.Schema, ObjectId = Schema.Types.ObjectId; var message = new Schema({ // This should be the ID of the sending user // If it isn't the user this message list was retrieved // from then it was sent to them from someone else _id: { type: String, default: shortid.generate }, sender: { type: ObjectId, required: true, ref: 'User' }, text: { type: String, required: true }, unread: { type: Boolean, default: true } }, { collection: 'messages', timestamps: true }); module.exports = mongoose.model('Message', message);
(function() { 'use strict'; function Game() { } Game.prototype.create = function() { this.input.onDown.add(this.onInputDown, this); }; Game.prototype.update = function() { }; Game.prototype.onInputDown = function() { }; window['<%= projectName %>'] = window['<%= projectName %>'] || {}; window['<%= projectName %>'].Game = Game; }());
export Footer from './Footer'; export Section from './Section'; export DropDownSection from './DropDownSection'; export LinkList from './LinkList';
test("url building - music tags", function(){ var starting_text= [ "<https://www.deezer.com/album/7509216>", "<https://www.deezer.com/track/75795831>", "<https://www.deezer.com/playlist/66498465>", "<https://play.spotify.com/track/7EE7jbv7Dv8ZkyWBlKhPXX>", "<https://soundcloud.com/deletefile/der-dub-dream>" ], expected= [ "[music]https://www.deezer.com/album/7509216[/music]", "[music]https://www.deezer.com/track/75795831[/music]", "[music]https://www.deezer.com/playlist/66498465[/music]", "[music]spotify:track:7EE7jbv7Dv8ZkyWBlKhPXX[/music]", "[music]https://soundcloud.com/deletefile/der-dub-dream[/music]", ]; var conv = new Showdown.converter(); for(var i = 0; i<starting_text.length; i++){ deepEqual( expected[i], conv.makeBBCode(starting_text[i]) //starting_text+" => "+expected ); } });
// U3.W9:JQuery // I worked on this challenge [by myself, with: ]. // This challenge took me [#] hours. $(document).ready(function(){ //RELEASE 0: //link the image //RELEASE 1: //Link this script and the jQuery library to the jQuery_example.html file and analyze what this code does. $('body').css({'background-color': 'pink'}) //RELEASE 2: //Add code here to select elements of the DOM bodyElement = $('body') headerElement = $('#welcome').css('background-color', "blue"); headerElement = $('#welcome').css('visibility', "initial"); headerElement = $('#welcome').css('border', "dotted"); //RELEASE 3: // Add code here to modify the css and html of DOM elements MascotName = $(".mascot h1").html("<h1>Fiery Skippers</h1>"); //RELEASE 4: Event Listener // Add the code for the event listener here // $('img').on('mouseover', function(e){ // e.preventDefault() // $(this).attr('src', 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/FierySkipper.JPG/300px-FierySkipper.JPG') // }) $('img').on('mouseleave', function(e){ e.preventDefault() $(this).attr('src', 'dbc_logo.png') }) //RELEASE 6: Experiment on your own $('img').click(function(){ $('img').animate({ left: '+=250px', opacity: '0.5', height: '150px', width: '150px' }); // $('img').off('mouseover') }); $('img').mouseleave(function(){ $('img').animate({ left: '250px', opacity: '0.5', // visibility: hidden, }); }); $('img').on('mouseover', function(e){ e.preventDefault() $(this).attr('src', 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/FierySkipper.JPG/300px-FierySkipper.JPG') for(var i = 1; i <10; i++){ $('.mascot h1').fadeOut("fast").fadeIn("fast") } }) }) // end of the document.ready function: do not remove or write DOM manipulation below this. /* What is jQuery? Jquery is a javascript library that helps with manipulating the DOM. It makes doing things like adding event listeners and animations much easier. What does jQuery do for you? It makes it dramatically easier to add create things like animations or interactive visual elements. What did you learn about the DOM while working on this challenge?\ By changing it! we messed around with a variety of methods for manipulating elements. */
var validate = require('../lib/validate'); exports.async = function(test) { function one(value, callback) { test.equal(this, context); test.equal(value, 'duck'); process.nextTick(callback.bind(null, true)); } var context = { req: { hi: 'you' } }; var value = 'duck'; validate.async(context, one, value, function(success) { test.ok(success); test.done(); }); }; exports.field = { required: function(test) { var name = 'username'; var options = { required: true }; validate.field({}, name, options, 'g6', function(err) { test.ok(!err); }); validate.field({}, name, options, undefined, function(err) { test.equal(err, name + ' is required'); }); test.expect(2); process.nextTick(test.done); }, 'not required': function(test) { var name = 'username'; var options = { required: false }; validate.field({}, name, options, 'teacher', function(err) { test.ok(!err); }); validate.field({}, name, options, undefined, function(err) { test.ok(!err); }); test.expect(2); process.nextTick(test.done); }, 'synchronous validation': function(test) { var options = { validate: [{ fn: function(value) { return value.length < 10; }, msg: 'Too long!' }] }; validate.field({}, 'foo', options, 'yes!', function(err) { test.ok(!err); }); validate.field({}, 'foo', options, 'looooooongcat', function(err) { test.equal(err, 'Too long!'); }); test.expect(2); process.nextTick(test.done); }, 'with a regular expression': function(test) { var options = { validate: [{ fn: /^.{1,10}$/, msg: 'Too long!' }] }; validate.field({}, 'foo', options, 'yes!', function(err) { test.ok(!err); }); validate.field({}, 'foo', options, 'looooooongcat', function(err) { test.equal(err, 'Too long!'); }); test.expect(2); process.nextTick(test.done); }, 'asynchronous validation': { pass: function(test) { var context = {}; var options = { validate: [{ fn: function(value, callback) { test.equal(this, context); process.nextTick(function() { callback((parseInt(value, 10) & 1) === 0); }); }, msg: 'Must be divisible by 2' }] }; validate.field(context, 'foo', options, '42', function(err) { test.ok(!err); test.done(); }); }, 'not pass': function(test) { var context = {}; var options = { validate: [{ fn: function(value, callback) { test.equal(this, context); process.nextTick(function() { callback((parseInt(value, 10) & 1) === 0); }); }, msg: 'Must be divisible by 2' }] }; validate.field(context, 'foo', options, '7', function(err) { test.equal(err, 'Must be divisible by 2'); test.done(); }); }, 'not pass with custom message': function(test) { var context = {}; var options = { validate: [{ fn: function(value, callback) { test.equal(this, context); process.nextTick(function() { callback((parseInt(value, 10) & 1) === 0, 'oh oh'); }); }, msg: 'Must be divisible by 2' }] }; validate.field(context, 'foo', options, '7', function(err) { test.equal(err, 'oh oh'); test.done(); }); } }, sanitize: function(test) { var options = { sanitize: function(value) { return value.slice(0, 5); } }; validate.field({}, 'baby', options, 'hello world', function(err, value) { test.ok(!err); test.equal(value, 'hello'); test.done(); }); }, 'sanitize with validation': function(test) { var options = { sanitize: function(value) { return value.slice(0, 5); }, validate: [{ fn: /^.{1,5}$/, msg: 'Must be between 1 and 5 characters' }] }; validate.field({}, 'baby', options, 'hello world', function(err, value) { test.ok(!err); test.equal(value, 'hello'); test.done(); }); } }; exports.all = function(test) { var context = { req: { hi: 'you' } }; var options = { fields: { username: { validate: [ { fn: /^[a-za-z0-9_]*$/ , msg: 'must contain only the characters a-za-z0-9_' } , { fn: /^.{1,15}$/, msg: 'must be between 1 and 15 characters' } , { fn: function(username, pass) { test.equal(this, context); process.nextTick(pass.bind(null, username !== 'gum')); } , msg: 'username is taken' } ] , required: true , storage: { session: true } } , displayName: { sanitize: function(name) { return name.slice(0, 3); }, validate: { fn: /^[^\n]{1,30}$/ , msg: 'must be between 1 and 30 characters' } , storage: { session: true } } }, submit: { server: null } }; var values; values = { username: '@_@', displayName: 'daddy' }; validate.all(context, options, values, function(success, results) { test.ok(!success); test.deepEqual(results, { username: { value: '@_@', success: false, msg: 'must contain only the characters a-za-z0-9_' }, displayName: { value: 'dad', success: true, msg: null } }); }); values = { username: 'bobby', displayName: 'daddy' }; validate.all(context, options, values, function(success, results) { test.ok(success); test.deepEqual(results, { username: { value: 'bobby', success: true, msg: null }, displayName: { value: 'dad', success: true, msg: null } }); }); test.expect(5); process.nextTick(test.done); }; exports['all with submit.server function'] = function(test) { var context = { req: { hi: 'you' } }; var options = { fields: { username: { validate: [ { fn: /^[a-za-z0-9_]*$/ , msg: 'must contain only the characters a-za-z0-9_' } , { fn: /^.{1,15}$/, msg: 'must be between 1 and 15 characters' } , { fn: function(username, pass) { test.equal(this, context); process.nextTick(pass.bind(null, username !== 'gum')); } , msg: 'username is taken' } ] , required: true , sanitize: function(s) { return s.slice(0, 4); } , storage: { session: true } } }, submit: { server: function(values, pass) { test.equal(this, context); test.deepEqual(values, { username: 'what' }); pass(true); } } }; var values = { username: 'whatever' }; validate.all(context, options, values, function(success, results) { test.ok(success); test.ok(!results); }); test.expect(5); process.nextTick(test.done); };
var Interval = require('interval-js'); var generateDrawFn = function(options) { var devicePixelRatio = window.devicePixelRatio, canvas = options.canvas, width = options.width, height = options.height, ctx = canvas.getContext('2d'), container = options.container, elements = options.elements, reverse = options.reverse; canvas.width = width * devicePixelRatio; canvas.height = height * devicePixelRatio; return function() { ctx.clearRect(0, 0, canvas.width, canvas.height); var scrollTop = container.scrollTop, containerHeight = container.offsetHeight; var visibleElements = []; var getTop = function(elem) { return elem.offsetTop - container.offsetTop - scrollTop; }; for(var i = 0; i < elements.length; i++) { var elem = elements[i]; if(elem.offsetHeight === 0) continue; var top = getTop(elem); if( top >= -elem.offsetHeight && top < containerHeight) { visibleElements.push(elem); } } visibleElements.forEach(function(elem) { // [{width: 48, color: "rgba(0, 0, 0, .5)"}, {}] try { var branches = JSON.parse(elem.dataset.flyBranch); } catch(e) { return; } var maxWidth = Math.max.apply(this, branches.map(function(branch) { return branch.width; })); branches.forEach(function(branch) { var w = branch.width; if(w < 1) { return; } var top = getTop(elem); // L1 L2 // L3 L4 var L1 = { x: reverse ? canvas.width : 0, y: (top + (elem.offsetHeight - maxWidth) / 2) * devicePixelRatio }; var L3 = {x: L1.x, y: L1.y + w * devicePixelRatio}; var L2 = { x: reverse ? 0 : canvas.width, y: (canvas.height - w) / 2 }; var L4 = { x: L2.x, y: (canvas.height + w) / 2 }; var control = {x: canvas.width / 2, y: canvas.height / 2}; ctx.beginPath(); ctx.moveTo(L1.x, L1.y); ctx.quadraticCurveTo(control.x, control.y, L2.x, L2.y); ctx.lineTo(L4.x, L4.y); ctx.quadraticCurveTo(control.x, control.y, L3.x, L3.y); ctx.lineTo(L1.x, L1.y); ctx.fillStyle = branch.color; ctx.fill(); }); }); }; }; var FlyBranchChart = function(options) { if(!Array.isArray(options)) { options = [options]; } var fns = options.map(function(opts) { return generateDrawFn(opts); }); return new Interval(function() { fns.forEach(function(fn) { fn(); }); }, {lifetime: 5000, useRequestAnimationFrame: true}); }; module.exports = FlyBranchChart;
import React from 'react'; import Helmet from 'react-helmet'; // import { Basic, Domain } from 'czechidm-core'; import SystemGroupSystemTable from './SystemGroupSystemTable'; import { SystemGroupSystemManager } from '../../redux'; /** * Table of system groups-system relations. * * @author Vít Švanda * @since 11.2.0 * */ export default class SystemGroupSystems extends Basic.AbstractContent { constructor(props) { super(props); this.manager = new SystemGroupSystemManager(); } getContentKey() { return 'acc:content.systemGroupSystem'; } getNavigationKey() { return this.getRequestNavigationKey('system-group-systems', this.props.match.params); } render() { const forceSearchParameters = new Domain.SearchParameters().setFilter('systemGroupId', this.props.match.params.entityId); return ( <div> <Helmet title={this.i18n('detail')} /> <Basic.ContentHeader text={ this.i18n('detail') } style={{ marginBottom: 0 }}/> <SystemGroupSystemTable uiKey="system-group-systems-table" forceSearchParameters={ forceSearchParameters } className="no-margin" manager={ this.manager } match={ this.props.match }/> </div> ); } }
(function() { 'use strict'; angular.module('app.services.!!NAME!!', []); })();
module.exports.safe = true; /* Purpose: Executes jquery paths to extract a single value or an array of values from an HTML document. Each key is the location where the captures will be stored. The value of each key should be a jquery path. If the path/value is a single-value array, then all matches will be captured as an array. Syntax: - jquery: key1: "jquery path to capture" # only first instance will be captured array1: [ "jquery path" ] # all instances will be captured */ var _ = require("lodash"); var cheerio = require("cheerio"); var verror = require("verror"); module.exports.process = function (context) { var target = this.target; if(_.isNil(target)) { var response = context.getSessionValue("hyperpotamus.response", null, undefined); if (_.isNil(response)) { throw new verror.VError({ name: "InvalidActionPlacement.jquery", info: { path: this.path + ".jquery" } }, "If the jquery action is not used within the .response of a request action, then an explicit .target must be specified."); } target = response.body.toString(); } var compare; var $ = cheerio.load(target); var matches = $(this.jquery); if (this.count) { if (!_.isNumber(this.count)) { throw new verror.VError({ name: "InvalidCountValue", info: { path: this.path + ".jquery.count" } }, "jquery.count value must be a number"); } if (_.isNumber(this.count)) { compare = this.count; } if (matches.length !== compare) { throw new verror.VError({ name: "JQueryCountDidNotMatch", info: { path: this.path } }, "Expected count of matches did not match"); } } if (this.capture) { for (var key in this.capture) { var expression = this.capture[key]; var asArray = false; if (_.isArray(expression)) { asArray = true; if (expression.length != 1) { throw new verror.VError({ name: "InvalidCaptureValue", info: { path: this.path + ".capture." + key, value: this.capture[key] } }, "If jquery.capture value is an array it must have a single element"); } expression = expression[0]; } if (asArray) { context.setSessionValue(key, _.map(matches, function (match) { return getNodeValue($(match), expression); })); } else { context.setSessionValue(key, getNodeValue($(matches[0]), expression)); } } } }; function getNodeValue(node, expression) { if (!expression || expression === "html" || expression === "outerHTML") { return node.toString(); } else if (expression === "innerHTML") { return node.html(); } else if (expression === "text") { return node.text(); } else if (expression[0] === "@") { return node.attr(expression.substring(1)); } else if (expression === "val") { return node.val(); } }
const should = require("should"); const makebuffer_from_trace = require("node-opcua-debug").makebuffer_from_trace; const inlineText = require("node-opcua-debug").inlineText; const hexDump = require("node-opcua-debug").hexDump; const crypto_utils = require("node-opcua-crypto"); let buffer = makebuffer_from_trace( function () { /* 00000000: 4f 50 4e 46 59 06 00 00 00 00 00 00 38 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 OPNFY.......8...http://opcfounda 00000020: 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 69 63 tion.org/UA/SecurityPolicy#Basic 00000040: 31 32 38 52 73 61 31 35 75 04 00 00 30 82 04 71 30 82 03 59 a0 03 02 01 02 02 04 53 a3 ca d0 30 128Rsa15u...0..q0..Y.......S#JP0 00000060: 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 43 31 0a 30 08 06 03 55 04 08 13 01 41 31 0a 30 08 ...*.H.w......0C1.0...U....A1.0. 00000080: 06 03 55 04 07 13 01 41 31 0a 30 08 06 03 55 04 0a 13 01 41 31 0a 30 08 06 03 55 04 0b 13 01 41 ..U....A1.0...U....A1.0...U....A 000000a0: 31 11 30 0f 06 03 55 04 03 13 08 55 61 45 78 70 65 72 74 30 1e 17 0d 31 34 30 36 32 30 30 35 34 1.0...U....UaExpert0...140620054 000000c0: 36 35 36 5a 17 0d 31 39 30 36 31 39 30 35 34 36 35 36 5a 30 43 31 0a 30 08 06 03 55 04 08 13 01 656Z..190619054656Z0C1.0...U.... 000000e0: 41 31 0a 30 08 06 03 55 04 07 13 01 41 31 0a 30 08 06 03 55 04 0a 13 01 41 31 0a 30 08 06 03 55 A1.0...U....A1.0...U....A1.0...U 00000100: 04 0b 13 01 41 31 11 30 0f 06 03 55 04 03 13 08 55 61 45 78 70 65 72 74 30 82 01 22 30 0d 06 09 ....A1.0...U....UaExpert0.."0... 00000120: 2a 86 48 86 f7 0d 01 01 01 05 00 03 82 01 0f 00 30 82 01 0a 02 82 01 01 00 a1 8c a0 41 83 63 43 *.H.w...........0........!..A.cC 00000140: b5 5a 14 d6 21 cf 79 f6 3a cb 71 b6 bb 71 70 04 bb a4 46 fc b7 0a 93 e6 f4 ae d1 bd 9b 3c d2 7c 5Z.V!Oyv:Kq6;qp.;$F|7..ft.Q=.<R| 00000160: 27 02 60 0f 24 4d 2b 10 4f 19 e5 aa bc b9 42 33 d2 51 bc 28 d2 e4 01 24 f4 99 2d c6 d0 8a fe be '.`.$M+.O.e*<9B3RQ<(Rd.$t.-FP.~> 00000180: 99 23 6a b7 01 42 6c 5b 86 d4 cc f4 74 fa f1 ec 9c 87 7b 33 ea c4 b6 80 51 52 8d a6 67 b0 e9 51 .#j7.Bl[.TLttzql..{3jD6.QR.&g0iQ 000001a0: e6 de 94 97 16 5b 90 99 1f fc 79 ef cb 01 e6 00 f2 be e1 00 45 12 5f 14 3e 04 fc 4b 0b 0c 11 87 f^...[...|yoK.f.r>a.E._.>.|K.... 000001c0: 9e 5b cc f0 d7 77 33 8b 5e ce f0 4f 33 5e 6a 68 93 55 e0 4d ce d2 99 6a 01 fa 19 c7 55 dd a6 d2 .[LpWw3.^NpO3^jh.U`MNR.j.z.GU]&R 000001e0: 05 ee 5a c3 f5 d3 73 2e 28 79 9a c0 a7 c3 e7 fb cf 55 bc 3e dd 6b 53 2e 52 b5 3e cf 08 4d 15 31 .nZCuSs.(y.@'Cg{OU<>]kS.R5>O.M.1 00000200: 53 ec fc e9 16 4a 07 ce 62 12 6f db d9 2a d4 be 79 3e bc 30 36 f0 fa 10 17 25 ae 80 f4 3c a4 90 Sl|i.J.Nb.o[Y*T>y><06pz..%..t<$. 00000220: cb b8 13 c3 eb 37 82 17 3c fc 2b c0 ec 09 70 53 e2 0a 6b 12 e7 2b 1a 78 e7 02 03 01 00 01 a3 82 K8.Ck7..<|+@l.pSb.k.g+.xg.....#. 00000240: 01 6b 30 82 01 67 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 00 30 50 06 09 60 86 48 01 86 f8 42 01 .k0..g0...U.......0.0P..`.H..xB. 00000260: 0d 04 43 16 41 22 47 65 6e 65 72 61 74 65 64 20 77 69 74 68 20 55 6e 69 66 69 65 64 20 41 75 74 ..C.A"Generated.with.Unified.Aut 00000280: 6f 6d 61 74 69 6f 6e 20 55 41 20 42 61 73 65 20 4c 69 62 72 61 72 79 20 75 73 69 6e 67 20 4f 70 omation.UA.Base.Library.using.Op 000002a0: 65 6e 53 53 4c 22 30 1d 06 03 55 1d 0e 04 16 04 14 22 ef e8 cb 76 10 7f 26 81 3e 8c 59 cf 26 f2 enSSL"0...U......"ohKv..&.>.YO&r 000002c0: a7 fb 97 ed 1a 30 6e 06 03 55 1d 23 04 67 30 65 80 14 22 ef e8 cb 76 10 7f 26 81 3e 8c 59 cf 26 '{.m.0n..U.#.g0e.."ohKv..&.>.YO& 000002e0: f2 a7 fb 97 ed 1a a1 47 a4 45 30 43 31 0a 30 08 06 03 55 04 08 13 01 41 31 0a 30 08 06 03 55 04 r'{.m.!G$E0C1.0...U....A1.0...U. 00000300: 07 13 01 41 31 0a 30 08 06 03 55 04 0a 13 01 41 31 0a 30 08 06 03 55 04 0b 13 01 41 31 11 30 0f ...A1.0...U....A1.0...U....A1.0. 00000320: 06 03 55 04 03 13 08 55 61 45 78 70 65 72 74 82 04 53 a3 ca d0 30 0e 06 03 55 1d 0f 01 01 ff 04 ..U....UaExpert..S#JP0...U...... 00000340: 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 30 14 06 08 2b 06 01 05 05 07 03 01 06 08 2b ....t0...U.%.....0...+.........+ 00000360: 06 01 05 05 07 03 02 30 44 06 03 55 1d 11 04 3d 30 3b 86 2b 75 72 6e 3a 50 43 45 54 49 45 4e 4e .......0D..U...=0;.+urn:PCETIENN 00000380: 45 2d 50 43 3a 55 6e 69 66 69 65 64 41 75 74 6f 6d 61 74 69 6f 6e 3a 55 61 45 78 70 65 72 74 82 E-PC:UnifiedAutomation:UaExpert. 000003a0: 0c 50 43 45 54 49 45 4e 4e 45 2d 50 43 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 82 01 01 .PCETIENNE-PC0...*.H.w.......... 000003c0: 00 1e 76 5c 60 05 f4 8a 34 8a 14 e7 de b5 73 7f c6 d9 a8 3a e5 7f 36 32 f5 84 66 e7 e9 56 a5 d5 ..v\`.t.4..g^5s.FY(:e.62u.fgiV%U 000003e0: c4 81 46 15 7b 69 46 56 e6 4e 34 c5 6e 3f 01 1f 5d 6b 49 0c cc 20 1b 32 7d b1 3f eb 31 a2 8d 0d D.F.{iFVfN4En?..]kI.L..2}1?k1".. 00000400: 48 16 1e 65 d7 8e 37 43 c0 32 07 fb f6 fb d8 b3 cb 31 aa 6e c6 c2 07 6f b6 68 33 bf b3 17 65 3f H..eW.7C@2.{v{X3K1*nFB.o6h3?3.e? 00000420: 54 9f 80 63 e8 ce 3c ae 9b e2 6e 22 01 f1 8c e2 2a 55 1c 61 12 17 5c 64 49 ab fd c9 1d 01 32 37 T..chN<..bn".q.b*U.a..\dI+}I..27 00000440: d8 c8 05 40 03 cd 8c 75 9e 80 0d 2a a5 e5 f3 be 8c e5 96 2b b5 2a 01 fa f7 c8 20 fc 9f cc 69 50 XH.@.M.u...*%es>.e.+5*.zwH.|.LiP 00000460: 91 ac 93 01 5b be ec 64 5d e5 25 05 50 7b 1f 94 6e 6b f3 06 f5 bb 71 3a d8 0e 80 d5 65 e5 ee 08 .,..[>ld]e%.P{..nks.u;q:X..Ueen. 00000480: 63 ab 51 04 b8 63 18 2e b6 3e 9c a5 29 39 4e b2 43 6c 96 31 45 10 3d 89 4f 29 d2 8c 28 c8 40 bf c+Q.8c..6>.%)9N2Cl.1E.=.O)R.(H@? 000004a0: 7a 34 52 89 08 8a f6 69 90 3a 7e 03 4a 49 e8 b4 4f c7 a4 89 7e 96 88 56 50 4b 2c 0e a8 91 e7 4d z4R...vi.:~.JIh4OG$.~..VPK,.(.gM 000004c0: b8 14 00 00 00 88 1c f6 98 5d 76 50 57 f8 aa de 4c e1 8d 62 00 5c c4 a1 d5 22 be 29 e3 6e 4a 71 8......v.]vPWx*^La.b.\D!U">)cnJq 000004e0: 19 04 76 bd 6f 18 91 12 66 08 61 f9 5e e6 59 a7 8e f4 1f a3 6f a7 9f c0 8a 3d 8c 69 0f 12 5f e0 ..v=o...f.ay^fY'.t.#o'.@.=.i.._` 00000500: 1b 6e e3 c4 c3 18 bb 77 62 ff dc 42 0b dc 59 ea 5a 53 9d e8 23 19 4e 69 b4 14 f5 10 56 2e 36 61 .ncDC.;wb.\B.\YjZS.h#.Ni4.u.V.6a 00000520: d8 79 06 ad b8 ec 95 dd ee ac e5 06 24 db b1 b2 cd 66 72 1d 1b 63 70 a7 98 ec e8 77 3b bf a3 f7 Xy.-8l.]n,e.$[12Mfr..cp'.lhw;?#w 00000540: 31 1c 41 91 09 fa 81 46 18 84 bc 37 c6 37 17 c5 bb 08 28 6d fe 38 ca 52 bb 2b 8f 16 06 65 f2 be 1.A..z.F..<7F7.E;.(m~8JR;+...er> 00000560: 89 4e 8f b6 40 1e b0 29 9a 4c c6 f0 64 0a e2 d6 54 e2 73 8e bb 8f 9a 3f eb 02 bf 8c 1c 89 87 40 .N.6@.0).LFpd.bVTbs.;..?k.?....@ 00000580: f6 f1 5f e1 2d e9 c0 d8 c3 6e e4 a5 6e 2a ce b3 8f dd 1d ed b0 51 9f 2d 6f ef 23 c6 2e 67 23 c4 vq_a-i@XCnd%n*N3.].m0Q.-oo#F.g#D 000005a0: 2d 3f f3 95 ef 18 8a ac b3 0e 99 d6 84 c4 ec af 42 63 af 3a 01 8c 3c 0c 8e a2 10 ca bf d2 59 b0 -?s.o..,3..V.Dl/Bc/:..<..".J?RY0 000005c0: 00 bf 23 e1 9a 04 2b 0a 9c dc 12 62 21 30 cb ea a7 b4 81 ec f4 90 7d 76 39 b8 97 37 b8 cc 70 16 .?#a..+..\.b!0Kj'4.lt.}v98.78Lp. 000005e0: fb 6c e1 9d 11 ae 9a 88 41 ba 70 b1 7b c8 8d b5 04 4b 88 d1 05 d5 b8 ac 9b 10 54 45 c8 80 65 8d {la.....A:p1{H.5.K.Q.U8,..TEH.e. 00000600: 5f 1e 1e 58 bd 7b 33 7f fd 98 fd 20 9d 71 30 3a 3c 84 1e 87 b8 1b 2d 51 2b 55 62 41 e4 b9 a5 29 _..X={3.}.}..q0:<...8.-Q+UbAd9%) 00000620: 24 2a 91 b6 06 05 01 df 80 dd b1 04 2e 05 aa 17 ef 6a 53 46 05 78 0c c7 5c 9c 7f cf e4 37 80 de $*.6..._.]1...*.ojSF.x.G\..Od7.^ 00000640: bf 31 de 11 13 70 f4 93 fe 0c a2 4f ef 58 b9 c8 a8 3a 5e 76 20 0c 87 f0 ef ?1^..pt.~."OoX9H(:^v...po */ }); //console.log(hexDump(buffer, 32 , 10000)); const privateKey = inlineText( function () { /* -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDVTV+bramiaPZc24RhmoFdL3ztiXS7QEoW3qvCfDqx4tAJKSZW trLfWnl92RhUUFXBhNhSuTccMzioWew+8lsQAL3lOUACMRvlxbRefH1PWcx6wi95 sFLe74PLgIcI5h9/a5Rj8N6bnAcj/8GpsMW2Vwna4lN8xkEgDK3GWW5tcQIDAQAB AoGAAjJo0K6qN50DJJOyOlsgB/isPboTtLYFzVR/ymIDLL/cSqvc1DnPf9NruusY gA3PxE18+OUldynj5IAAmelfHLdDSXIsoRaSb5LQe5O4sjLu8wIrZ66dy7JpAav0 QiPSw/Er2zvLuVzew+WvB/CAxNr/nVfr8Lr1uBwYC38aLS0CQQD2J0gmw4Vx5wZV e7Ma3AFyV7QbB7hPeauNiru8d7E3mg3M1prBiJHJgzjeW0y/dveEU/RTEsX7TM4v 6fOuD2FvAkEA3dWuV9y4NtqNzX9xRvp13esgfgnZpI39Eg/JPRH2Ll4XAEmUOHRR p/1eomAO/e8JPwAbEr+ExLc7jpQxDJXvHwJBAJA3kZlMgpmqblaVI+l/rsVMRzRz AHRn57AE8VtJkSXvd1hk/8SV/DxhSmdUfJHM5NW9zm8Bl8dVR5Rg8KkxT7cCQQDE X6dBMiuEq35B/uIpIgh7Feyihle7GtJ/TagoPqE+NJ6J65ihTR8H5fwDI6PB2PvH YHGW7CE8/rNjKP4ulP+jAkAUhrdwf6Wr4KeyOqysE5V7AnHgBHgyUvi95bjJEtVm g9s5xs14gqCBGGf2CTN+xnJehplg562CQG6f70heivC7 -----END RSA PRIVATE KEY----- */ }); describe("testing message decryption", function () { it("should decrypt an OPN packet and verify that the signature is correct", function () { // extract the client certificate from the unencrypted part const senderCertificate = buffer.slice(0x4C, 0x475 + 0x4C); // where the encrypted part starts const start = buffer.length - ( 128 * 3 ); const encrypted_part = buffer.slice(start); // decrypt the encrypted part const decrypted_part = crypto_utils.privateDecrypt_long(encrypted_part, privateKey, 128); // recompose the buffer decrypted_part.copy(buffer, start); buffer = buffer.slice(0, start + decrypted_part.length); buffer.length.should.equal(start + 3 * (128 - 11)); // verify signature const publicKey = crypto_utils.toPem(senderCertificate, "CERTIFICATE"); const options = { algorithm: "RSA-SHA1", signatureLength: 256, publicKey: publicKey }; const boolSignatureIsOK = crypto_utils.verifyChunkSignature(buffer, options); boolSignatureIsOK.should.eql(true); }); });
import { expect } from 'chai'; import { ClientFunction } from 'testcafe'; import { saveWindowState, restoreWindowState } from '../../../../../window-helpers'; const getWindowDimensionsInfo = ClientFunction(() => { return { innerWidth: window.innerWidth, innerHeight: window.innerHeight, outerWidth: window.outerWidth, outerHeight: window.outerHeight, availableHeight: screen.availHeight, availableWidth: screen.availWidth }; }); const INITIAL_SIZE = 500; fixture `Maximize Window` .page `http://localhost:3000/fixtures/api/es-next/maximize-window/pages/index.html` .beforeEach(async t => { await saveWindowState(t); await t.resizeWindow(INITIAL_SIZE, INITIAL_SIZE); }) .afterEach(async t => { await restoreWindowState(t); }); test('Maximize window', async t => { await t.maximizeWindow(); var dimensions = await getWindowDimensionsInfo(); expect(dimensions.outerWidth).to.be.at.least(dimensions.availableWidth); expect(dimensions.outerHeight).to.be.at.least(dimensions.availableHeight); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ErrorMessage = " is not correct"; var recruitment = (function () { function recruitment(_id, _ref) { var job = _ref.job; var body = _ref.body; var school_exp = _ref.school_exp; var prize = _ref.prize; var ability = _ref.ability; var cert = _ref.cert; var job_exp = _ref.job_exp; _classCallCheck(this, recruitment); //初始化 this._id = _id; this.school_exp = new Array(); this.prize = new Array(); this.ability = new Array(); this.cert = new Array(); this.job_exp = new Array(); //初次赋值 this.set_job = job; this.set_body = body; this.set_school_exp = school_exp; this.set_prize = prize; this.set_ability = ability; this.set_cert = cert; this.set_job_exp = job_exp; } //招聘职位信息 _createClass(recruitment, [{ key: "throwError", value: function throwError(propName) { throw new Error(propName + ErrorMessage); } }, { key: "set_job", set: function set(obj) { if (obj instanceof job) { this.job = obj; } else { this.throwError('job'); } } }, { key: "set_body", set: function set(obj) { if (obj instanceof body) { this.body = obj; } else { this.throwError('body'); } } }, { key: "set_school_exp", set: function set(obj) { if (obj instanceof Array) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = obj[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var o = _step.value; this.school_exp.push(o); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"]) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else if (obj instanceof school_exp) { this.school_exp.push(obj); } else { this.throwError('school_exp'); } } }, { key: "set_prize", set: function set(obj) { if (obj instanceof Array) { var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = obj[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var o = _step2.value; this.prize.push(o); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"]) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } else if (obj instanceof prize) { this.prize.push(obj); } else { this.throwError('prize'); } } }, { key: "set_ability", set: function set(obj) { if (obj instanceof Array) { var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = obj[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var o = _step3.value; this.ability.push(o); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3["return"]) { _iterator3["return"](); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } } else if (obj instanceof ability) { this.ability.push(obj); } else { this.throwError('ability'); } } }, { key: "set_cert", set: function set(obj) { if (obj instanceof Array) { var _iteratorNormalCompletion4 = true; var _didIteratorError4 = false; var _iteratorError4 = undefined; try { for (var _iterator4 = obj[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { var o = _step4.value; this.cert.push(o); } } catch (err) { _didIteratorError4 = true; _iteratorError4 = err; } finally { try { if (!_iteratorNormalCompletion4 && _iterator4["return"]) { _iterator4["return"](); } } finally { if (_didIteratorError4) { throw _iteratorError4; } } } } else if (obj instanceof cert) { this.cert.push(obj); } else { this.throwError('cert'); } } }, { key: "set_job_exp", set: function set(obj) { if (obj instanceof Array) { var _iteratorNormalCompletion5 = true; var _didIteratorError5 = false; var _iteratorError5 = undefined; try { for (var _iterator5 = obj[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { var o = _step5.value; this.job_exp.push(o); } } catch (err) { _didIteratorError5 = true; _iteratorError5 = err; } finally { try { if (!_iteratorNormalCompletion5 && _iterator5["return"]) { _iterator5["return"](); } } finally { if (_didIteratorError5) { throw _iteratorError5; } } } } else if (obj instanceof job_exp) { this.job_exp.push(obj); } else { this.throwError('job_exp'); } } }]); return recruitment; })(); exports.recruitment = recruitment; var job = (function () { function job(_ref2) { var job_name = _ref2.job_name; var type = _ref2.type; var work_time = _ref2.work_time; var job_type = _ref2.job_type; var salary = _ref2.salary; _classCallCheck(this, job); this.job_name = job_name; this.type = type; this.set_work_time = work_time; this.job_type = job_type; this.set_salary = salary; } //身体情况 _createClass(job, [{ key: "set_work_time", set: function set(_ref3) { var start = _ref3.start; var end = _ref3.end; var start_time = start.split(":"); var end_time = end.split(":"); this.work_time = { start: parseInt(start_time[0]) * 60 + parseInt(start_time[1]), end: parseInt(end_time[0]) * 60 + parseInt(end_time[1]) }; } }, { key: "set_salary", set: function set(_ref4) { var type = _ref4.type; var max = _ref4.max; var min = _ref4.min; switch (type) { case 0: this.salary = { type: type, max: max, min: min }; break; case 1: this.salary = { type: type }; break; default: throw new Error(ErrorMessage); } } }]); return job; })(); exports.job = job; var body = function body(_ref5) { var isDeformity = _ref5.isDeformity; var age = _ref5.age; var sex = _ref5.sex; var height = _ref5.height; var sight = _ref5.sight; var weight = _ref5.weight; _classCallCheck(this, body); this.isDeformity = isDeformity; this.age = age; this.sex = sex; this.height = height; this.sight = sight; this.weight = weight; } //学校经历 ; exports.body = body; var school_exp = function school_exp(_ref6) { var degree = _ref6.degree; _classCallCheck(this, school_exp); this.degree = degree; } //获奖情况 ; exports.school_exp = school_exp; var prize = function prize(_ref7) { var type = _ref7.type; var level = _ref7.level; _classCallCheck(this, prize); this.type = type; this.level = level; } //技能 ; exports.prize = prize; var ability = function ability(_ref8) { var aname = _ref8.aname; var level = _ref8.level; var need = _ref8.need; _classCallCheck(this, ability); this.aname = aname; this.level = parseInt(level); this.need = parseInt(need); } //证书 ; exports.ability = ability; var cert = function cert(_ref9) { var cname = _ref9.cname; var type = _ref9.type; var level = _ref9.level; var need = _ref9.need; _classCallCheck(this, cert); this.cname = cname; this.type = type; this.level = parseInt(level); this.need = parseInt(need); } //工作经历 ; exports.cert = cert; var job_exp = function job_exp(_ref10) { var job = _ref10.job; var num = _ref10.num; _classCallCheck(this, job_exp); this.job = job; this.num = parseInt(num); } /*职位匹配模型 职位编号 职位信息 职位名称 分类 工作时间 时起 时末 职位类型 0全职 1实习 2兼职 月薪 类型 0面议 1固定 最小 最大 身体要求 是否接收残疾 0不接收 1接收 年龄 最小 最大 性别 身高 最小 最大 视力 最小 最大 体重 最小 最大 学校经历 学历 0初中及以下 1中专/技校 2大专 3本科 4硕士 5博士 获奖 奖项类型 奖项等级 0区级 1市级 2国家级 3世界级 加分 1~5 技能[] 能力名称 掌握情况 0 掌握 1精通 需要证书类型[] 证书颁发机构 证书类型 证书等级0~10 证书需求类型 0优先 1 必须 工作经历[] 职位 /正则匹配/ 年数 */ ; exports.job_exp = job_exp;
'use strict' module.exports = { ADD:{ USER:"ADD_USER", TASK:"ADD_TASK", }, UPDATE:{ TASK:"UPDATE_TASK", }, DEL:{ USER:"DEL_USER", TASK:"DEL_TASK", }, }
var fs = require('fs'), uglify = require('uglify-js'); var FILE_ENCODING = 'utf-8', PROJECT_NAME = 'app', LICENSE = '../LICENSE.md', INPUT_DIR = '../src', OUTPUT_DIR = '../dist', FILE_EXT = '.js', SCRIPTS = [ 'core.js', 'routes.js', 'router.js', 'template.js', 'about.js', 'users.js', 'run.js' ]; function path() { return [].join.call(arguments, '/'); } function build() { var join, license, un, min; license = fs.readFileSync(LICENSE, FILE_ENCODING); join = SCRIPTS.map(function (name) { return fs.readFileSync(path(INPUT_DIR, name), FILE_ENCODING); }); un = license + '\n' + join; min = license + uglify.minify(join, {fromString: true}).code; fs.writeFileSync(path(OUTPUT_DIR, PROJECT_NAME + FILE_EXT), un, FILE_ENCODING); fs.writeFileSync(path(OUTPUT_DIR, PROJECT_NAME + '.min' + FILE_EXT), min, FILE_ENCODING); console.log('Build Complete!'); } build();
"use strict"; var glob = require("glob"); function config() { var cfg = {}; cfg.dest = "."; cfg.styles = "sass"; cfg.template = "templates/email.tpl.html"; cfg.srcFiles = glob.sync("src/**/*.js?(x)"); cfg.srcMainEntry = "./index.js"; cfg.testDest = "test/build"; cfg.testFiles = glob.sync("./test/src/*.js?(x)"); return cfg; } module.exports = config();
// Module variables var PATTERN_REGEXP = /\{\{([\w\*\.]*?)\}\}/g; var DOT_REGEXP = /([^\.]+)/g; /** * Compile template * @param {String} template String to precompile * @param {Object} object Template arguments * @return {String} Precompiled template * @api public */ export function compile(template, object) { var args = arguments.length > 2 ? arguments : object; return template.replace(PATTERN_REGEXP, (value, property) => { var key; var map = args; while ((key = DOT_REGEXP.exec(property)) && (key = key[1])) { map = map ? (key === '*' ? map : map[key]) : null; } return map === void 0 ? '' : map; }); }
(function (){ var Documentor, util, emitter, isNode=typeof module == 'object' && module.exports; if(isNode){ util=require('../lib/util'); Documentor=module.exports; emitter=require('../lib/events').EventEmitter; }else{ util=window.util; Documentor=util.ns('Documentor'); emitter=window.EventEmitter; } /** * @class Documentor.Api * Excapsulates all data, configuration and methods of the target API's documentation. * @extends EventEmitter * @constructor */ Documentor.Api=function (cfg){ Documentor.Api.super_.apply(this, arguments); this.initialize(); }; util.inherits(Documentor.Api, emitter); util.extend(Documentor.Api.prototype, { /** * @cfg {String} NSPathSeparator * Defaults to the dot character (".") . */ NSPathSeparator:'.', initialize:function (){ /** * @cfg {Object} ns * Namespace defaults. */ /** * @property {Object} ns * This object has the complete API description. It has very little upon creation but the SourceProcessor object's job is to fill it with details. */ if('ns' in this){ this.nsDefaults=this.ns; delete this.ns; } this.reset(); /** * @cfg {Documentor.SourceLoader} sourceLoader (required) * The loader to use. */ // if(this.renderer) // this.bind('sourceProcessed', function (){ // if(this.sourceFiles.length==0) // this.renderer.render(this); // }); /** * @cfg {Documentor.SourceProcessor} sourceProcessor * The source processor to use. */ /** * @cfg {Array} sourceFiles * If the list is provided it will be processed on initialization. */ if(this.sourceFiles) this.processSourceFiles(this.sourceFiles); }, /** * @method reset * Reset the ns object to its initial state. This is useful before rebuilding it from new sources. */ reset:function (){ var defNS={ name:'API', type:'api', children:{} }; this.ns=util.extend(true, {}, defNS, this.nsDefaults); }, /** * @method processSourceFiles * @param {Array} sourceFiles A list of file to process. */ processSourceFiles:function (sourceFiles){ var fileLoadedCb=function (fileData, fileURL){ if(!fileData) console.error('Could not load "'+fileURL+'"'); else this.sourceProcessor.process(fileData, this, fileURL); }.scope(this); for(var i=0; i<sourceFiles.length; i++){ this.sourceLoader.getSourceFile(sourceFiles[i], fileLoadedCb); } }, sourceFileEnd:function (fileURL){ /** * @event sourceProcessed * Fires when a source file has been processed. * @param {Documentor.Api} this * @param {String} fileURL */ this.emit('sourceProcessed', this, fileURL); if(this.sourceLoader.queue.length==0){ /** * @event sourceQueueEmpty * Fires when the source files queue of the loader is emptied - all given source files are loaded. * @param {Documentor.Api} this */ this.emit('sourceQueueEmpty', this); /** * @cfg {Documentor.render.DocumentationRenderer} renderer * If provided will call its render() method after the last source file is processed. */ if(this.renderer) this.renderer.render(this); } }, /** * @method getNSObject * Returns the namespace object on the given path. * @param {String} path * @param {Boolean} autoCreate (optional) Set to true to have a "namespace" object created if nothing exists for that path. * @return {Object} The object on that path. */ getNSObject:function (path, autoCreate){ var obj=null, pathNames = typeof path=='string'?path.split(this.NSPathSeparator):path; if(typeof path=='string') pathNames=path.split(this.NSPathSeparator); else{ pathNames=path; path=path.join(this.NSPathSeparator); } if(pathNames.length){ obj=this.ns; var currentPath=[]; if(pathNames[0]==this.ns.name) pathNames.shift(); while(pathNames.length){ var p=pathNames.shift(); currentPath.push(p); if(!(p in obj.children)){ if(autoCreate) obj.children[p]={ type:'namespace', name:currentPath.join(this.NSPathSeparator), children:{}, methods:{}, description:'' }; else return null; } obj=obj.children[p]; } } return obj; } }); }());
//============================================================================= // AddEscapeCommandForAllActor.js //============================================================================= /*: * @plugindesc This plugin add a Escape Command for all Actor. * @author masami * * @help This plugin does not provide plugin commands. */ /*:ja * @plugindesc Actor全員に「逃げる」コマンドを追加します。 * @author masami * * @help このプラグインには、プラグインコマンドはありません。 */ (function(){ Window_ActorCommand.prototype.addEscapeCommand = function() { this.addCommand(TextManager.escape, 'escape', BattleManager.canEscape()); }; var _Window_ActorCommand_makeCommandList = Window_ActorCommand.prototype.makeCommandList; Window_ActorCommand.prototype.makeCommandList = function() { _Window_ActorCommand_makeCommandList.call(this); if (this._actor) { this.addEscapeCommand(); } }; var _Scene_Battle_createActorCommandWindow = Scene_Battle.prototype.createActorCommandWindow; Scene_Battle.prototype.createActorCommandWindow = function() { _Scene_Battle_createActorCommandWindow.call(this); this._actorCommandWindow.setHandler('escape', this.commandEscape.bind(this)); }; var _Window_ActorCommand_numVisibleRows = Window_ActorCommand.prototype.numVisibleRows; Window_ActorCommand.prototype.numVisibleRows = function() { return _Window_ActorCommand_numVisibleRows.call(this) + 1; }; })();
'use strict'; const Util = require('./util'); /** * All movement methods should have the same signature so that execute() can call them. */ class MovementStrategy { /** * @param board * @param methodName * @param frightMethodName * @param scatterx (optional) * @param scattery (optional) * @param pacman (optional) * @param blinky (optional) */ constructor(board, methodName, frightMethodName, scatterx= null, scattery=null, pacman=null, blinky=null) { this._board = board; this._method = this[methodName]; this._frightMethod = this[frightMethodName]; this._scatterx = scatterx; this._scattery = scattery; this._pacman = pacman; this._blinky = blinky; } execute(entity) { if (entity.frightened) { this._frightMethod(entity); } else { if (entity.mode === 'chase') { this._method(entity); } else if (entity.mode === 'scatter') { this.scatter(entity); } } } // Movement methods begin here doNothing(entity) { // Do nothing. } random(entity) { runIfNewIntersection(entity, this._board, (directions) => { let index = Util.getRandomIntInclusive(0, directions.length - 1); entity.requestedDirection = directions[index]; }); } scatter(entity) { runIfNewIntersection(entity, this._board, (directions) => { aimTowardsTargetTile(entity, this._scatterx, this._scattery, directions); }); } /** * Blinky is the red ghost and follows Pac-Man directly. */ blinky(entity) { runIfNewIntersection(entity, this._board, (directions) => { let targetx = Util.convertToTileSpace(this._pacman.x); let targety = Util.convertToTileSpace(this._pacman.y); aimTowardsTargetTile(entity, targetx, targety, directions); }); } /** * Pinky is the pink ghost and attempts to cut Pac-Man off. */ pinky(entity) { runIfNewIntersection(entity, this._board, directions => { let targetx = Util.convertToTileSpace(this._pacman.x); let targety = Util.convertToTileSpace(this._pacman.y); switch (this._pacman.currentDirection) { case 'up': targety -= 4; break; case 'down': targety += 4; break; case 'left': targetx -= 4; break; case 'right': targetx += 4; break; } aimTowardsTargetTile(entity, targetx, targety, directions); }); } /** * Inky is the blue ghost and attempts to ambush Pac-Man by approaching from the opposite line of Blinky. */ inky(entity) { runIfNewIntersection(entity, this._board, directions => { let firstx = Util.convertToTileSpace(this._pacman.x); let firsty = Util.convertToTileSpace(this._pacman.y); switch (this._pacman.currentDirection) { case 'up': firsty -= 2; break; case 'down': firsty += 2; break; case 'left': firstx -= 2; break; case 'right': firstx += 2; break; } let secondx = Util.convertToTileSpace(this._blinky.x); let secondy = Util.convertToTileSpace(this._blinky.y); let diffx = firstx - secondx; let diffy = firsty - secondy; let targetx = firstx + diffx; let targety = firsty + diffy; aimTowardsTargetTile(entity, targetx, targety, directions); // lower right }); } /** * Clyde is the orange ghost and tends to stay away from Pac-Man. */ clyde(entity) { runIfNewIntersection(entity, this._board, directions => { let pacmanx = Util.convertToTileSpace(this._pacman.x); let pacmany = Util.convertToTileSpace(this._pacman.y); let tilex = Util.convertToTileSpace(entity.x); let tiley = Util.convertToTileSpace(entity.y); let distanceSquared = Util.qs( pacmanx - tilex, pacmany - tiley ); if (distanceSquared >= 64) { aimTowardsTargetTile(entity, pacmanx, pacmany, directions); } else { aimTowardsTargetTile(entity, 1, 30, directions); // same as scatter tile } }); } } module.exports = MovementStrategy; /** * Run the given function IF the entity has arrived at an intersection. * Otherwise it will proceed along its path if there is only one direction to move. * Run AI once per intersection; do this by tracking the last tile. */ function runIfNewIntersection(entity, board, cb) { let currenttilex = Util.convertToTileSpace(entity.x); let currenttiley = Util.convertToTileSpace(entity.y); if (currenttilex !== entity.lastTileAIx || currenttiley !== entity.lastTileAIy) { entity.lastTileAIx = currenttilex; entity.lastTileAIy = currenttiley; let directions = determinePossibleDirections(currenttilex, currenttiley, entity.currentDirection, board); if (directions.length === 1) { // either in a cooridor or a turn entity.requestedDirection = directions[0]; } else if (directions.length >= 2) { cb(directions); } } } function aimTowardsTargetTile(entity, targetx, targety, directions) { // Determine how far each open adjacent tile is from Pac-Man let distances = directions.map((direction) => { let dx = 0; let dy = 0; switch (direction) { case 'up': dy = -1; break; case 'down': dy = 1; break; case 'left': dx = -1; break; case 'right': dx = 1; break; } let tilex = Util.convertToTileSpace(entity.x); let tiley = Util.convertToTileSpace(entity.y); let distance = Util.qs( tilex + dx - targetx, tiley + dy - targety ); return { direction: direction, distance: distance }; }); // Sort the distances so that the shortest is first distances.sort((a, b) => { return a.distance - b.distance; }); // Use the direction from the shortest distance entity.requestedDirection = distances[0].direction; } /** * Given where the entity is currently and where it was one tile ago, * return the array of directions it is allowed to go in at this intersection. * It will either be a total of 1, 2, or 3 directions. */ function determinePossibleDirections(tilex, tiley, currentDirection, board) { let directions = []; if (currentDirection !== 'up' && board.isWallOpen(tilex, tiley+1)) { directions.push('down'); } if (currentDirection !== 'down' && board.isWallOpen(tilex, tiley-1)) { directions.push('up'); } if (currentDirection !== 'left' && board.isWallOpen(tilex+1, tiley)) { directions.push('right'); } if (currentDirection !== 'right' && board.isWallOpen(tilex-1, tiley)) { directions.push('left'); } return directions; }
/* global require, describe, it */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Matrix data structure: matrix = require( 'dstructs-matrix' ), // Deep close to: deepCloseTo = require( './utils/deepcloseto.js' ), // Validate a value is NaN: isnan = require( 'validate.io-nan' ), // Module to be tested: variance = require( './../lib' ), // Function to apply element-wise VARIANCE = require( './../lib/number.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'compute-variance', function tests() { it( 'should export a function', function test() { expect( variance ).to.be.a( 'function' ); }); it( 'should throw an error if provided an invalid option', function test() { var values = [ '5', 5, true, undefined, null, NaN, [], {} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { variance( [1,2,3], { 'accessor': value }); }; } }); it( 'should throw an error if provided an array and an unrecognized/unsupported data type option', function test() { var values = [ 'beep', 'boop' ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( Error ); } function badValue( value ) { return function() { variance( [1,2,3], { 'dtype': value }); }; } }); it( 'should throw an error if provided a typed-array and an unrecognized/unsupported data type option', function test() { var values = [ 'beep', 'boop' ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( Error ); } function badValue( value ) { return function() { variance( new Int8Array([1,2,3]), { 'dtype': value }); }; } }); it( 'should throw an error if provided a matrix and an unrecognized/unsupported data type option', function test() { var values = [ 'beep', 'boop' ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( Error ); } function badValue( value ) { return function() { variance( matrix( [2,2] ), { 'dtype': value }); }; } }); it( 'should return NaN if the first argument is neither a number, array-like, or matrix-like', function test() { var values = [ // '5', // valid as is array-like (length) true, undefined, null, // NaN, // allowed function(){}, {} ]; for ( var i = 0; i < values.length; i++ ) { assert.isTrue( isnan( variance( values[ i ] ) ) ); } }); it( 'should compute the distribution variance when provided a number', function test() { assert.closeTo( variance( 0.2 ), 20, 1e-5 ); assert.closeTo( variance( 0.4 ), 3.75, 1e-5 ); assert.closeTo( variance( 0.6 ), 10/9, 1e-5 ); assert.closeTo( variance( 0.8 ), 0.3125, 1e-5 ); }); it( 'should compute the distribution variance when provided a plain array', function test() { var p, actual, expected; p = [ 0.2, 0.4, 0.6, 0.8 ]; expected = [ 20, 3.75, 10/9, 0.3125 ]; actual = variance( p ); assert.notEqual( actual, p ); assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) ); // Mutate... actual = variance( p, { 'copy': false }); assert.strictEqual( actual, p ); assert.isTrue( deepCloseTo( p, expected, 1e-5 ) ); }); it( 'should compute the distribution variance when provided a typed array', function test() { var p, actual, expected; p = new Float64Array ( [ 0.2,0.4,0.6,0.8 ] ); expected = new Float64Array( [ 20,3.75,10/9,0.3125 ] ); actual = variance( p ); assert.notEqual( actual, p ); assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) ); // Mutate: actual = variance( p, { 'copy': false }); expected = new Float64Array( [ 20,3.75,10/9,0.3125 ] ); assert.strictEqual( actual, p ); assert.isTrue( deepCloseTo( p, expected, 1e-5 ) ); }); it( 'should compute the distribution variance and return an array of a specific type', function test() { var p, actual, expected; p = [ 0.2, 0.4, 0.6, 0.8 ]; expected = new Int32Array( [19,3.75,10/9,0.3125] ); actual = variance( p, { 'dtype': 'int32' }); assert.notEqual( actual, p ); assert.strictEqual( actual.BYTES_PER_ELEMENT, 4 ); }); it( 'should compute the distribution variance using an accessor', function test() { var p, actual, expected; p = [ {'p':0.2}, {'p':0.4}, {'p':0.6}, {'p':0.8} ]; expected = [ 20, 3.75, 10/9, 0.3125 ]; actual = variance( p, { 'accessor': getValue }); assert.notEqual( actual, p ); assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) ); // Mutate: actual = variance( p, { 'accessor': getValue, 'copy': false }); assert.strictEqual( actual, p ); assert.isTrue( deepCloseTo( p, expected, 1e-5 ) ); function getValue( d ) { return d.p; } }); it( 'should compute an element-wise distribution variance and deep set', function test() { var data, actual, expected; data = [ {'x':[9,0.2]}, {'x':[9,0.4]}, {'x':[9,0.6]}, {'x':[9,0.8]} ]; expected = [ {'x':[9,20]}, {'x':[9,3.75]}, {'x':[9,10/9]}, {'x':[9,0.3125]} ]; actual = variance( data, { 'path': 'x.1' }); assert.strictEqual( actual, data ); assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) ); // Specify a path with a custom separator... data = [ {'x':[9,0.2]}, {'x':[9,0.4]}, {'x':[9,0.6]}, {'x':[9,0.8]} ]; actual = variance( data, { 'path': 'x/1', 'sep': '/' }); assert.strictEqual( actual, data ); assert.isTrue( deepCloseTo( actual, expected, 1e-5 ) ); }); it( 'should compute an element-wise distribution variance when provided a matrix', function test() { var mat, out, d1, d2, d3, i; d1 = new Int16Array( 25 ); d2 = new Float64Array( 25 ); d3 = new Int16Array( 25 ); for ( i = 0; i < d1.length; i++ ) { d1[ i ] = i + 1; d2[ i ] = VARIANCE( i + 1 ); d3[ i ] = VARIANCE( i + 1 ); } mat = matrix( d1, [5,5], 'int16' ); out = variance( mat ); assert.deepEqual( out.data, d2 ); // Mutate... out = variance( mat, { 'copy': false }); assert.strictEqual( mat, out ); assert.deepEqual( mat.data, d3 ); }); it( 'should compute an element-wise distribution variance and return a matrix of a specific type', function test() { var mat, out, d1, d2, i; d1 = new Int16Array( 25 ); d2 = new Float32Array( 25 ); for ( i = 0; i < d1.length; i++ ) { d1[ i ] = i + 1; d2[ i ] = VARIANCE( i + 1 ); } mat = matrix( d1, [5,5], 'int16' ); out = variance( mat, { 'dtype': 'float32' }); assert.strictEqual( out.dtype, 'float32' ); assert.deepEqual( out.data, d2 ); }); it( 'should return an empty data structure if provided an empty data structure', function test() { assert.deepEqual( variance( [] ), [] ); assert.deepEqual( variance( matrix( [0,0] ) ).data, new Float64Array() ); assert.deepEqual( variance( new Int8Array() ), new Float64Array() ); }); });
"use strict"; var app = { map: undefined, marker: undefined, rectangle: undefined, rectangleBounds: undefined, initialize: function() { app.map = new google.maps.Map(document.getElementById('map'), { center: { lat: 41.99081, lng: -87.9634719 }, zoom: 8 }); app.rectangleBounds = new google.maps.LatLngBounds( new google.maps.LatLng(41.02233540581116, -89.39368031718755), new google.maps.LatLng(41.8697309, -87.77302040000001) ); app.rectangle = new google.maps.Rectangle({ strokeColor: '#0000FF', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#0000FF', fillOpacity: 0.1, map: app.map, draggable: true, editable: true, bounds: app.rectangleBounds }); app.rectangle.addListener('bounds_changed', app.rectangleChanged); app.rectangle.addListener('dragend', app.rectangleDragged); app.marker = new google.maps.Marker({ position: app.rectangle.getBounds().getCenter(), map: app.map, draggable: true }); app.marker.addListener('dragend', app.markerDragged); }, markerDragged: function(event) { var currentRectangleBounds = undefined, rectangleCenter = undefined, distanceToNE = 0, distanceToSW = 0, bearingToNE = 0, bearingToSW = 0, newNE = undefined, newSW = undefined; // Are we still inside the rectangle? if (! app.rectangle.getBounds().contains(app.marker.getPosition())) { currentRectangleBounds = app.rectangle.getBounds(); rectangleCenter = currentRectangleBounds.getCenter(); // Get distance from rectangle center to NE, SW corners distanceToNE = google.maps.geometry.spherical.computeDistanceBetween(currentRectangleBounds.getNorthEast(), rectangleCenter); distanceToSW = google.maps.geometry.spherical.computeDistanceBetween(currentRectangleBounds.getSouthWest(), rectangleCenter); // Get heading from rectangle center to NE, SW corners bearingToNE = google.maps.geometry.spherical.computeHeading(rectangleCenter, currentRectangleBounds.getNorthEast()); bearingToSW = google.maps.geometry.spherical.computeHeading(rectangleCenter, currentRectangleBounds.getSouthWest()); // Get new NE corner newNE = google.maps.geometry.spherical.computeOffset(app.marker.getPosition(), distanceToNE, bearingToNE); newSW = google.maps.geometry.spherical.computeOffset(app.marker.getPosition(), distanceToSW, bearingToSW); // Move the rectangle to new location with the marker at center app.rectangle.setOptions({ bounds: new google.maps.LatLngBounds(newSW, newNE) }); } }, rectangleDragged: function(event) { if (! app.rectangle.getBounds().contains(app.marker.getPosition())) { app.marker.setPosition(app.rectangle.getBounds().getCenter()); } app.rectangleBounds = app.rectangle.getBounds(); }, rectangleChanged: function(event) { // Did we get resized? var currentBounds = app.rectangle.getBounds(), priorBounds = app.rectangleBounds, currentNE = currentBounds.getNorthEast(), priorNE = priorBounds.getNorthEast(), currentSW = currentBounds.getSouthWest(), priorSW = priorBounds.getSouthWest(), neChanged = ! ((currentNE.lat() === priorNE.lat()) && (currentNE.lng() === priorNE.lng())), swChanged = ! ((currentSW.lat() === priorSW.lat()) && (currentSW.lng() === priorSW.lng())), nwChanged = ! ((currentNE.lat() === priorNE.lat()) && (currentSW.lng() === priorSW.lng())), seChanged = ! ((currentNE.lng() === priorNE.lng()) && (currentSW.lat() === priorSW.lat())); if (neChanged && swChanged && nwChanged && seChanged) { // Do nothing we are being dragged } else { // Resized, see if we still contain the marker app.rectangleBounds = app.rectangle.getBounds(); if (! app.rectangle.getBounds().contains(app.marker.getPosition())) { // Marker was outside rectangle snap it to center app.marker.setPosition(app.rectangle.getBounds().getCenter()); } } } } window.onload = function() { app.initialize(); }
'use strict'; var myApp = angular.module('projects').controller('ProjectsController', ['$scope','$rootScope', '$http', '$stateParams', '$location', '$upload', '$modal', '$sce', 'Authentication', 'Projects','$state', '$timeout', function($scope, $rootScope, $http, $stateParams, $location, $upload, $modal, $sce, Authentication, Projects, $state, $timeout) { $scope.authentication = Authentication; $scope.textToAppend = ''; $scope.sc = $sce; $scope.heading= ''; $scope.obj={}; $scope.activeElementIndex = -1; $scope.foundTop = false; $scope.chart ={}; $scope.graphTitle = ''; $scope.xTitle = ''; $scope.yTitle = ''; $scope.graphPoints = []; $scope.chartArray = []; $scope.videoEmbed = ''; $scope.elementsOfCurrentProject = []; //Looks up the project id $scope.lookup = function(id) { var projects = $scope.projects; for (var i =0; i < projects.length; i++) { if (projects[i]._id === id) return projects[i]; } return false; }; //Finds the top level(project) of the current project we're in $scope.resolveTop = function(project) { //var project = $scope.project; var projects = $scope.projects; if ($scope.foundTop) return true; var current = project; while (current.parent !== undefined) { current = $scope.lookup(current.parent); } if (current.parent === undefined) { $scope.topProject = current; $scope.foundTop = true; return true; } return false; }; $scope.setScopeProjectElementsArray = function(id) { $scope.elementsOfCurrentProject = $scope.lookup(id).elements; }; //Finds the ID for the top level project $scope.resolveTopID = function(project) { var projects = $scope.projects; var current = project; while(current.parent !== undefined){ current = $scope.lookup(current.parent); } if(current.parent === undefined){ return current._id; } return false; }; // Checks to see if the user has permissions to edit the project $scope.canEdit = function() { var project = $scope.project; var projects = $scope.projects; if (projects.$resolved && project.$resolved) { $scope.resolveTop(project); var topProject = $scope.topProject; if (!Authentication.user.isAdmin) return false; else if ($rootScope.inPreview) return false; else if (topProject.editPermission === 'public') return true; else if ($scope.authentication.user._id === topProject.user._id) return true; else if (topProject.editContributers.indexOf($scope.authentication.user.email) !== -1) return true; else return false; } }; //Checks to see if the user has permissions to view the project $scope.canView = function(project) { if ($scope.resolveTop(project)) { var topProject = $scope.topProject; if (topProject.viewPermission === 'public') return true; else if (Authentication.user._id === topProject.user._id) return true; else if (topProject.viewContributers.indexOf(Authentication.user.email) !== -1) return true; else return false; } }; //Adds a user who can contribute to a project $scope.addViewContributer = function (email) { var project = $scope.project; if (project.viewContributers.indexOf(email) === -1) { project.viewContributers.push(email); } }; //Adds a user who can contribute to a project $scope.addEditContributer = function (email) { var project = $scope.project; if (project.editContributers.indexOf(email) === -1) { project.editContributers.push(email); } }; //Opens Modal of every contributor who can view the project $scope.openViewContributorsModal = function (isView, msg, size) { var modalInstance = $modal.open({ templateUrl: 'modules/projects/views/modals/view-contributors.modal.client.html', controller: 'ModalController', size: size, resolve: { message: function() { return msg; }, project: function() { return $scope.project; } } }); modalInstance.result.then(function (response) { console.log(response); return response; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; //Opens Modal of every contributor who can add to the project $scope.openAddContributorsModal = function (isView, msg, size) { var modalInstance = $modal.open({ templateUrl: 'modules/projects/views/modals/add-contributors.modal.client.html', controller: 'ModalController', size: size, resolve: { message: function() { return msg; }, project: function() { return $scope.project; } } }); modalInstance.result.then(function (response) { console.log(response); var i; if (isView) { for (i =0; i< response.length; i++) { $scope.addViewContributer(response[i]); } } else { for (i =0; i< response.length; i++) { $scope.addEditContributer(response[i]); } } $scope.project.$update(function() { //$location.path('projects/' + $scope.project._id + '/permissions'); $state.go('home.permissionsProject',{projectId:$scope.project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); return response; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; //Opens Modal of every contributor who can remove from the project $scope.openRemoveContributorsModal = function (isView, msg, size) { var modalInstance = $modal.open({ templateUrl: 'modules/projects/views/modals/remove-contributors.modal.client.html', controller: 'ModalController', size: size, resolve: { message: function() { return msg; }, project: function() { return $scope.project; } } }); modalInstance.result.then(function (response) { console.log(response); var i; var index; if (isView) { for (i =0; i< response.length; i++) { index = $scope.project.viewContributers.indexOf(response[i]); if (index !== -1) $scope.project.viewContributers.splice(index,1); } } else { for (i =0; i< response.length; i++) { for (i =0; i< response.length; i++) { index = $scope.project.editContributers.indexOf(response[i]); if (index !== -1) $scope.project.editContributers.splice(index,1); } } } $scope.project.$update(function() { //$location.path('projects/' + $scope.project._id + '/permissions'); $state.go('home.permissionsProject',{projectId:$scope.project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); return response; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; //changes the permission of the person viewing the project $scope.changePermission = function (permission, state) { var project = $scope.project; if (permission === 'edit') { project.editPermission = state; } else { project.viewPermission = state; } project.$update(function() { //$location.path('projects/' + project._id + '/permissions'); $state.go('home.permissionsProject',{projectId:project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //Adds a contibutor to a project $scope.addContributer = function () { var project = $scope.project; if (project.contributers.indexOf($scope.authentication.user._id) === -1) { project.contributers.push($scope.authentication.user._id); } }; //checks to see if the person is a contributor to a project $scope.isContributer = function (project) { if (project.contributers.indexOf(Authentication.user._id) !== -1) { return true; } else { return false; } }; //This will open a delete modal // put no_element if the object is a project, msg will be displayed, size =['sm','lg'] or default $scope.openDeleteModal = function (element, msg, size) { var modalInstance = $modal.open({ templateUrl: 'modules/projects/views/modals/confirmation-modal.client.view.html', controller: 'ModalController', size: size, resolve: { message: function() { return msg; }, project: function() { return $scope.project; } } }); modalInstance.result.then(function (response) { if (element === 'no_element') { $scope.remove(); } else { $scope.deleteElement(element); } return response; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; //This will open a delete question modal $scope.openDeleteQuestionModal = function (question, msg, size) { var modalInstance = $modal.open({ templateUrl: 'modules/projects/views/modals/confirmation-modal.client.view.html', controller: 'ModalController', size: size, resolve: { message: function() { return msg; }, project: function() { return $scope.project; } } }); modalInstance.result.then(function (response) { $scope.deleteQuestion(question); return response; }, function () { console.log('Modal dismissed at: ' + new Date()); }); }; //closes and opens the editing feature $scope.toggleEdit = function(element){ element.isEditing = !element.isEditing; }; //cancels the edit feature $scope.cancelEdit = function(element) { $scope.findOne(); }; //Initiates element $scope.setActiveElement = function(element) { $scope.activeElementIndex = $scope.project.elements.indexOf(element); }; //creates a new project $scope.create_project = function() { var project = new Projects({ title: this.title, content: this.content, contributers: [Authentication.user._id], level: 1 }); project.$save(function(response) { $state.go('home.viewProject',{projectId:response._id},{reload:true}); $scope.title = ''; $scope.content = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //deletes an element in a project $scope.deleteElement = function(element) { $scope.addContributer(); var project = $scope.project; project.elements.splice(project.elements.indexOf(element),1); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //this is a legacy function. Can remove if you want. //Allows the user to edit an element $scope.edit_element = function(element) { $scope.addContributer(); var project = $scope.project; $scope.activeElementIndex = project.elements.indexOf(element); console.log(element); console.log('index: ' + $scope.activeElementIndex); if (element.tag === 'text') { //$location.path('projects/' + project._id + '/edit-text/' + project.elements.indexOf(element)); $state.go('home.editTextProject', {projectId:project._id, elementIndex:project.elements.indexOf(element)},{reload:true}); } if (element.tag === 'image' || element.tag === 'video' || element.tag === 'audio') { //$location.path('projects/' + project._id + '/edit-file/' + project.elements.indexOf(element)); $state.go('home.editFileProject', {projectId:project._id, elementIndex:project.elements.indexOf(element)},{reload:true}); } }; //Allows the user to remove a project function removeProjects() { $scope.project.$remove(function() { $state.go('home.viewProject', {}, {reload:true}); }); } //Allows the user to remove a certain element $scope.remove = function() { $scope.addContributer(); var proj = $scope.project; var arr = new Array(proj); delete_func(proj._id, arr, proj.level, proj.title); for(var index = 0; index < arr.length; index++){ if (arr[index]) { arr[index].$remove(); for (var i in $scope.projects) { if ($scope.projects[i] === arr[index]) { $scope.projects.splice(i, 1); } } } else { removeProjects(); } } $state.go('home.openProject',{},{reload:true}); }; function delete_func(del_id, arr, level, del_title){ for (var i = 0; i < $scope.projects.length; i++){ //console.log($scope.projects[i].title); if($scope.projects[i].parent === del_id){ arr.push($scope.projects[i]); delete_func($scope.projects[i]._id, arr, level + 1); } else if($scope.projects[i].children.length > 0){ for(var j = 0; j < $scope.projects[i].children.length; j++){ if($scope.projects[i].children[j].title === del_title){ $scope.projects[i].children.splice(j,1); $scope.projects[i].$update(function(){}); } } } } } //Adds text to a certain element $scope.appendText = function() { $scope.addContributer(); var project = $scope.project; var my_index = get_insert_index(project); project.elements.push({tag: 'text', value: $scope.textToAppend, index: my_index}); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject', {projectId:project._id}); $scope.textToAppend = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Adds the table structure to the element $scope.appendTable = function() { $scope.addContributer(); var project = $scope.project; var my_index = get_insert_index(project); project.elements.push({tag: 'table', value: $scope.textToAppend, index: my_index}); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject', {projectId:project._id}); $scope.textToAppend = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //Adds a link to a element $scope.appendLink = function(workspaceID, sectionID, elementID){ console.log(workspaceID); console.log(sectionID); $scope.addContributer(); var project = $scope.project; var determineTarget = workspaceID; var my_index = get_insert_index(project); if(sectionID){ determineTarget = sectionID; } var determineProject = $scope.lookup(determineTarget); var determineTitle = determineProject.title; console.log(determineTitle); console.log(determineTarget); //data title is used by graph element, we will use dataTitle to test if we can actually pass elementID project.elements.push({tag: 'linkButton', value: determineTarget, heading: determineTitle, index: my_index, dataTitle: elementID}); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject', {projectId:project._id}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //Sets a graph to certain type $scope.setGraphType = function(label){ $scope.graphType = label; $scope.drawGraphPreview(); }; //Gets the index number of the graph $scope.getGraphIndex = function(element){ for(var i = 0; i< element.length; i++){ if(element.heading === $scope.chartArray.options.title) return i; } return -1; }; //Adds a point to the graph $scope.addGraphPoint = function(){ var points = $scope.graphPoints; var x = $scope.xToAppend; for(var i = 0; i < points.length; ++i){ if(points[i].x === x){ points[i].y = $scope.yToAppend; $scope.xToAppend = ''; $scope.yToAppend = ''; $scope.drawGraphPreview(); return; } else if(parseInt(points[i].x,10) > parseInt(x)){ points.splice(i, 0, {x: $scope.xToAppend, y: $scope.yToAppend}); $scope.xToAppend = ''; $scope.yToAppend = ''; $scope.drawGraphPreview(); return; } } $scope.graphPoints.push({x: $scope.xToAppend,y: $scope.yToAppend}); $scope.xToAppend = ''; $scope.yToAppend = ''; $scope.drawGraphPreview(); }; //Adds a graph to an element $scope.appendGraph = function(){ $scope.addContributer(); var project = $scope.project; var my_index = get_insert_index(project); project.elements.push({ tag: 'graph', heading: $scope.graphTitle, index: my_index, x_name: $scope.xTitle, y_name: $scope.yTitle, dataTitle: $scope.dataTitle, graphType: $scope.graphType, graph_points: $scope.graphPoints }); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //Gives you a preview of a graph that was drawn $scope.drawGraphPreview = function(){ console.log('In draw graph'); //console.log(element.x_name); //console.log(element.y_name); //console.log(element.heading); //console.log(element.graph_points); var chart1 = $scope.chart; if($scope.graphType) chart1.type = $scope.graphType; else chart1.type = 'ColumnChart'; chart1.cssStyle = 'height:200px; width:300px;'; chart1.data = {'cols': [ {id: 'month', label: 'Month', type: 'string'}, {id: 'cost-id', label: $scope.dataTitle, type: 'number'} ], 'rows': [] }; for(var i=0; i<$scope.graphPoints.length; i++){ chart1.data.rows.push( {c: [ {v: $scope.graphPoints[i].x}, {v: $scope.graphPoints[i].y}, ]} ); } chart1.options = { 'title': $scope.graphTitle, 'isStacked': 'true', 'fill': 20, 'displayExactValues': true, 'vAxis': { 'title': $scope.yTitle, 'gridlines': {'count': 6} }, 'hAxis': { 'title': $scope.xTitle } }; }; // Creates an element which allows the user to draw a graph $scope.drawGraph = function(element){ console.log('In draw graph'); //console.log(element.x_name); //console.log(element.y_name); //console.log(element.heading); //console.log(element.graph_points); element.graph ={}; element.graph.type = element.graphType; element.graph.cssStyle = 'height:200px; width:300px;'; element.graph.data = {'cols': [ {id: 'month', label: 'Month', type: 'string'}, {id: 'cost-id', label: element.dataTitle, type: 'number'} ], 'rows': [] }; for(var i=0; i<element.graph_points.length; i++){ element.graph.data.rows.push( {c: [ {v: element.graph_points[i].x}, {v: element.graph_points[i].y}, ]} ); } element.graph.options = { 'title': element.heading, 'isStacked': 'true', 'fill': 20, 'displayExactValues': true, 'vAxis': { 'title': element.y_name, 'gridlines': {'count': 6} }, 'hAxis': { 'title': element.x_name } }; }; //gets the index of the element that is going to be inserted function get_insert_index (project) { var elements = project.elements; var length = elements.length; var max_index = 0; for (var i = 0; i !== length; ++i) { if (elements[i].index > max_index) { max_index = elements[i].index; } } return max_index + 1; } //allows the user to insert a question $scope.insertQuestion = function() { var project = $scope.project; var questionType; var correctAnswers; var answerChoices; var feedbacks; if (document.getElementById('r1').checked) { /* Multiple Choice */ questionType = document.getElementById('r1').value; answerChoices = [document.getElementById('mcAnswer1').value]; answerChoices.push(document.getElementById('mcAnswer2').value); answerChoices.push(document.getElementById('mcAnswer3').value); feedbacks = [document.getElementById('mcFeedback1').value]; feedbacks.push(document.getElementById('mcFeedback2').value); feedbacks.push(document.getElementById('mcFeedback3').value); if($scope.numChoices >= 4){ answerChoices.push(document.getElementById('mcAnswer4').value); feedbacks.push(document.getElementById('mcFeedback4').value); } if($scope.numChoices >= 5){ answerChoices.push(document.getElementById('mcAnswer5').value); feedbacks.push(document.getElementById('mcFeedback5').value); } if($scope.numChoices >= 6){ answerChoices.push(document.getElementById('mcAnswer6').value); feedbacks.push(document.getElementById('mcFeedback6').value); } if (document.getElementById('mc1').checked) correctAnswers = [document.getElementById('mcAnswer1').value]; else if(document.getElementById('mc2').checked) correctAnswers = [document.getElementById('mcAnswer2').value]; else if(document.getElementById('mc3').checked) correctAnswers = [document.getElementById('mcAnswer3').value]; else if(document.getElementById('mc4').checked) correctAnswers = [document.getElementById('mcAnswer4').value]; else if(document.getElementById('mc5').checked) correctAnswers = [document.getElementById('mcAnswer5').value]; else if(document.getElementById('mc6').checked) correctAnswers = [document.getElementById('mcAnswer6').value]; } else if (document.getElementById('r2').checked) { /* Multiple Selection */ questionType = document.getElementById('r2').value; answerChoices = [document.getElementById('msAnswer1').value]; answerChoices.push(document.getElementById('msAnswer2').value); answerChoices.push(document.getElementById('msAnswer3').value); feedbacks = [document.getElementById('msFeedback1').value]; feedbacks.push(document.getElementById('msFeedback2').value); feedbacks.push(document.getElementById('msFeedback3').value); if($scope.numSelections >= 4){ answerChoices.push(document.getElementById('msAnswer4').value); feedbacks.push(document.getElementById('msFeedback4').value); } if($scope.numSelections >= 5){ answerChoices.push(document.getElementById('msAnswer5').value); feedbacks.push(document.getElementById('msFeedback5').value); } if($scope.numSelections >= 6){ answerChoices.push(document.getElementById('msAnswer6').value); feedbacks.push(document.getElementById('msFeedback6').value); } correctAnswers = []; if (document.getElementById('ms1').checked) correctAnswers.push(document.getElementById('msAnswer1').value); if(document.getElementById('ms2').checked) correctAnswers.push(document.getElementById('msAnswer2').value); if(document.getElementById('ms3').checked) correctAnswers.push(document.getElementById('msAnswer3').value); if($scope.numSelections >= 4 && document.getElementById('ms4').checked) correctAnswers.push(document.getElementById('msAnswer4').value); if($scope.numSelections >= 5 && document.getElementById('ms5').checked) correctAnswers.push(document.getElementById('msAnswer5').value); if($scope.numSelections >= 6 && document.getElementById('ms6').checked) correctAnswers.push(document.getElementById('msAnswer6').value); } else if (document.getElementById('r3').checked) { /* True/False */ questionType = document.getElementById('r3').value; if(document.getElementById('tf1').checked) correctAnswers = [document.getElementById('tf1').value]; else correctAnswers = [document.getElementById('tf2').value]; answerChoices = ['True']; answerChoices.push('False'); feedbacks = [document.getElementById('tfFeedback1').value]; feedbacks.push(document.getElementById('tfFeedback2').value); } project.questions.push({tag: questionType, explanation: $scope.explanation, query: $scope.query, choices: answerChoices, answers: correctAnswers, result: false, answered: false, responses: [], checked: false, feedback: feedbacks}); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject', {projectId:project._id}, {reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //allows user to delete a question $scope.deleteQuestion = function(question) { var project = $scope.project; project.questions.splice(project.questions.indexOf(question),1); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //allows the user to set the answer to the question $scope.setAnswer = function(selection, question) { question.responses = [selection]; if(selection === question.answers[0]){ question.result = true; } else{ question.result = false; } question.answered = false; question.checked = true; }; //allows the user to set multiple answers to the question $scope.setMultipleAnswer = function(selection, question) { for(var i = 0; i < question.responses.length; ++i){ if(question.responses[i] === selection){ question.responses.splice(i, 1); if(question.responses.length === 0){ question.checked = false; } question.answered = false; if(compareAnswers(question.responses,question.answers)){ question.result = true; question.answered = false; $scope.score++; } else question.result = false; return; } } question.responses.push(selection); if(compareAnswers(question.responses,question.answers)){ question.result = true; } else question.result = false; question.answered = false; question.checked = true; }; //compares the answer recorded to the correct answer function compareAnswers(arr1, arr2){ arr1.sort(); arr2.sort(); if(arr1.length !== arr2.length) return false; for(var i = 0; i < arr1.length; ++i){ if(arr1[i] !== arr2[i]) return false; } return true; } //checks the answer recorded to see if it is correct $scope.checkAnswer = function(question) { var proj = $scope.project; var tally = 0; var i; for(i = 0; i < proj.questions.length; ++i){ if(proj.questions[i].result === true) ++tally; } $scope.score = tally; $scope.numQuestions = proj.questions.length; proj.reports.push({quizTitle: proj.title, question: question.explanation, selectedAnswers: [], correctAnswers: question.answers, isCorrect: question.result, student: Authentication.user.displayName}); for(i = 0; i < question.responses.length; ++i){ proj.reports[proj.reports.length-1].selectedAnswers.push(question.responses[i]); } $scope.hasQuestions = true; question.answered = true; $scope.displayFeedback = true; }; //the function to see whether or not the answer is correct $scope.displayFeedbackFunc = function(){ var proj = $scope.project; for(var i = 0; i < proj.questions.length; ++i){ proj.questions[i].responses = []; proj.questions[i].answered = false; } proj.$update(function() { //$location.path('projects/' + proj._id); $state.go('home.viewProject',{projectId:proj._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); $scope.displayFeedback = true; $scope.displayScore = true; }; //shows the feedback about whether or not the answer is correct $scope.showFeedback = function(question, i) { for(var j = 0; j < question.responses.length; ++j){ if(question.responses[j] === question.choices[i]){ if(question.feedback[i] !== '') return true; } } return false; }; //allows user to edit an equation $scope.appendEquation = function() { $scope.addContributer(); var project = $scope.project; var my_index = get_insert_index(project); project.elements.push({tag: 'equation', value: $scope.textToAppend, index: my_index}); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id},{reload:true}); $scope.textToAppend = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; //records the type of question selected $scope.questionTypeSelected = function(type) { $scope.questionType = type; }; //records the number of solutions in multiple choice question $scope.numberMultipleChoices = function(num) { $scope.numChoices = num; $scope.pickedMC = true; $scope.pickedMS = false; }; /*$scope.getNumChoices = function(num) { return numChoices; };*/ //records the number of solutions in multiple selections question $scope.numberMultipleSelections = function(num) { $scope.numSelections = num; $scope.pickedMS = true; $scope.pickedMC = false; }; //$scope.number = 0; $scope.getNumber = function(num) { return new Array(num); }; //allows user to edit a file $scope.editFile = function(files) { $scope.addContributer(); var project = $scope.project; var fd = new FormData(); console.log('*****************'); console.log($scope.activeElementIndex); console.log(project.elements[$scope.activeElementIndex]); //Take the first selected file fd.append('file', files[0]); $http.post('/public/uploads', fd, { withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity }) .success( function(data, status, headers, config, statusText) { console.log(data); var filepath = data; project.elements[$scope.activeElementIndex] = {tag: project.elements[$scope.activeElementIndex].tag, value: filepath.data.replace('public/', '').replace('\\', '/')}; project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); } ); }; // allows user to upload a file $scope.uploadFile = function(files, indicator) { $scope.addContributer(); var project = $scope.project; var my_index = get_insert_index(project); var fd = new FormData(); //Take the first selected file fd.append('file', files[0]); //console.log(files[0].name); //console.log(files[0].type); $http.post('/public/uploads', fd, { withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity }) .success( function(data, status, headers, config, statusText) { //console.log(data); var filepath = data; var tag_type = ''; if(indicator === 0) tag_type = 'image'; else if(indicator === 1) tag_type = 'video'; else if(indicator === 2) tag_type = 'audio'; project.elements.push({tag: tag_type, value: filepath.data.replace('public/', '').replace('\\', '/'), isEditing: false, index: my_index, showMedia: $scope.showMedia}); project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); } ); }; // allows user to embed a file $scope.embedFile = function(indicator) { $scope.addContributer(); var project = $scope.project; var my_index = get_insert_index(project); var tag_type = ''; if(indicator === 0) tag_type = 'image'; else if(indicator === 1) tag_type = 'video'; else if(indicator === 2) tag_type = 'audio'; project.elements.push({tag: tag_type, value: $scope.videoEmbed, isEditing: false, index: my_index, isEmbedded: true, showMedia: $scope.showMedia}); project.$update(function() { $state.go('home.viewProject',{projectId:project._id}); $scope.textToAppend = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Adds a level to the hierarchy. curr_level corresponds to the level of the hierarchy // Project-1, Course-2, Topic-3, etc. $scope.addLevel = function(curr_level) { $scope.addContributer(); var parent_proj = $scope.project; var curr_proj; if(curr_level === -1){ /* Inserting a quiz into the hierarchy! Make it fit into this spot no matter what */ curr_level = parent_proj.level+1; curr_proj = new Projects({ title: this.title, content: this.content, parent: parent_proj._id, level: curr_level, reports: [], isQuiz: true }); } else{ if(parent_proj.level+1 !== curr_level){ $scope.error = 'Cannot insert a ' + get_hierarchy_name(curr_level) + ' under a ' + get_hierarchy_name(parent_proj.level) + '!'; return; } curr_proj = new Projects({ title: this.title, content: this.content, parent: parent_proj._id, level: curr_level, }); } parent_proj.children.push(curr_proj); parent_proj.$update(function(){ curr_proj.$save(function(response) { //$location.path('projects/' + response._id); $state.go('home.viewProject',{projectId:response._id},{reload:true}); $scope.title = ''; $scope.content = ''; },function(errorResponse) { $scope.error = errorResponse.data.message; }); }); }; // returns the hierachy name function get_hierarchy_name(level){ if(level === 1) return 'Project'; else if(level === 2) return 'Course'; else if(level === 3) return 'Topic'; else if(level === 4) return 'Concept'; else if(level === 5) return 'Section'; else if(level === 6) return 'Subsection'; else if(level === 7) return 'Quiz'; } // updates the project $scope.update = function() { $scope.addContributer(); var project = $scope.project; project.$update(function() { //$location.path('projects/' + project._id); $state.go('home.viewProject',{projectId:project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // finds list of the projects $scope.find = function() { $scope.projects = Projects.query(); }; // looks for a single project $scope.findOne = function() { $scope.project = Projects.get({ projectId: $stateParams.projectId }); }; // looks for a single project $scope.findOne_report = function() { $scope.project = Projects.get({ projectId: $stateParams.projectId }); }; // returns a certain type of user $scope.getUniqueUsers = function(report){ var ret = [report[0].student]; for(var i = 1; i < report.length; ++i){ var add = true; for(var j = 0; j < ret. length; ++j){ if(ret[j] === report[i].student) add = false; } if(add){ ret.push(report[i].student); } } return ret; }; // find an element in the project $scope.findElement = function() { var url = $location.path(); $scope.activeElementIndex = url.substring(url.lastIndexOf('/') + 1, url.length); }; // converts it to a string $scope.to_string = function(proj){ return JSON.stringify(proj, null, 2); }; // displays the answers $scope.printAnswers = function(answers){ var ret = answers[0]; for(var i = 1; i < answers.length; ++i){ ret += ', '; ret += answers[i]; } return ret; }; // shows whether or not the result is correct $scope.printResult = function(result){ if(result) return 'Correct'; else return 'Incorrect'; }; // when element is dropped it is updated and checked to see if it is in a correct place $scope.onDropComplete = function (start_element, end_element, evt) { //console.log(start_element); //console.log(end_element); var elements = $scope.project.elements; var const_elements = $scope.project.elements; var start_index = start_element.index; var end_index = end_element.index; /* console.log(start_index); console.log(end_index); console.log(elements); console.log(start_element); console.log(end_element); */ console.log('\n\npre'); console.log(elements[0].value + ' :: index: ' + elements[0].index); console.log(elements[1].value + ' :: index: ' + elements[1].index); for (var i = 0; i !== elements.length; ++i) { if (start_index < end_index) { if (elements[i].index > start_index && elements[i].index <= end_index) { elements[i].index = elements[i].index - 1; } } else if (start_index > end_index) { if (elements[i].index < start_index && elements[i].index >= end_index) { elements[i].index = elements[i].index + 1; } } } start_element.index = end_index; $scope.project.$update(function() { //$location.path('projects/' + $scope.project._id); $state.go('home.viewProject',{projectId:$scope.project._id},{reload:true}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); console.log('\npost'); console.log(elements[0].value + ' :: index: ' + elements[0].index); console.log(elements[1].value + ' :: index: ' + elements[1].index); }; // returns the element selected function get_element(elements, index) { var length = elements.length; for (var i = 0; i !== length; ++i) { if (elements[i].index === index) { return elements[i]; } } return false; } //allows user to drag an element $scope.canDrag = function(element) { return $scope.canEdit() && !element.isEditing; }; // the function with the magic $scope.openProjectModal = function (projectId, elementId) { var modalInstance = $modal.open({ templateUrl: 'modules/projects/views/modals/project-modal.client.view.html', controller: 'LinkModalController', size: 'lg', resolve: { prjId: function() { return projectId; }, eleId: function() { return elementId; } } }); }; // changes all hash links (<a href='#foo'></a>) to call a scroll function // meant to be used with the wait-until-loaded directive $scope.replaceHashLinks = function() { // gotoId is used to smoothly scroll to the appropriate element id // id is defined by targetHash which is set onto the anchor id function gotoId(evt) { var id = evt.target.targetHash; // retrieve the id from the targetHash attribute // find the current position on the page function currentYPos() { // Firefox, Chrome, Safari if(document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7, 8 if(document.body.scrollTop) return document.body.scrollTop; return 0; } // find the position of the element we want to scroll to function elemYPos(id) { var offset = 60; // offset for the menu bar var elem = document.getElementById(id); if(!elem) return 0; // if element not found, return 0 var y = elem.offsetTop; var node = elem; while(node.offsetParent && node.offsetParent !== document.body) { node = node.offsetParent; y += node.offsetTop; } if(y - offset < 0) return 0; return y - offset; } var startY = currentYPos(); var stopY = elemYPos(id); //console.log('startY: '+startY+' stopY: '+stopY); var distance = stopY > startY ? stopY - startY : startY - stopY; if(distance < 100) { scrollTo(0, stopY); return; } var speed = Math.round(distance / 100); if(speed >= 20) speed = 20; var step = Math.round(distance / 25); var leapY = stopY > startY ? startY + step : startY - step; var timer = 0; if(stopY > startY) { for(var i = startY; i < stopY; i+=step) { setTimeout('window.scrollTo(0, '+leapY+')', timer * speed); leapY += step; if(leapY > stopY) leapY = stopY; timer++; } } else { for(var j = startY; j > stopY; j-=step) { setTimeout('window.scrollTo(0, '+leapY+')', timer * speed); leapY -= step; if(leapY < stopY) leapY = stopY; timer++; } } } // function that waits until all elements are loaded and then // replaces all <a href="#foo"></a> with <a id="anchorToFoo"></a> // and creates an eventListener that will execute gotoId when clicked $timeout(function() { var links = document.getElementsByTagName('a'); // get all links for( var i = 0; i < links.length; i++ ) { var str = links[i].href; // check for the # sign, however skip the #! if(str.indexOf('#!') === -1 && str.indexOf('#') !== -1) { // extract hash name str = str.substring(str.indexOf('#')+1); if(str) { // make sure it is not blank // remove href attribute links[i].removeAttribute('href'); // set the id links[i].setAttribute('id', 'anchorTo_'+str); // create an EventListener to run a custom scrolling function links[i].addEventListener('click', gotoId, false); // set the target attribute (where to scroll to) links[i].targetHash = str; } } } }, 0); }; } ]);
"use strict"; var React = require('react'), S3Upload = require('./s3upload.js'), objectAssign = require('object-assign'), ProgressBar = require('react-bootstrap/lib/ProgressBar'); var ReactS3Uploader = React.createClass({ getInitialState:function(){ return{ filename:"", progress:0 } }, propTypes: { signingUrl: React.PropTypes.string.isRequired, onProgress: React.PropTypes.func, onFinish: React.PropTypes.func, onError: React.PropTypes.func }, onProgress: function(percent){ this.setState({progress: percent}); }, getDefaultProps: function() { return { onProgress: function(percent, message) { console.log('Upload progress: ' + percent + '% ' + message); }, onFinish: function(signResult) { console.log("Upload finished: " + signResult.publicUrl) }, onError: function(message) { console.log("Upload error: " + message); } }; }, uploadFile: function(e) { var file = e.target.files[0]; this.setState({filename:file.name}); var self=this; new S3Upload({ fileElement: file, signingUrl: this.props.signingUrl, onProgress: self.onProgress, onFinishS3Put: this.props.onFinish, onError: this.props.onError }); }, render: function() { return ( React.createElement("div", {className: "react-s3-uploader"}, React.createElement("div", {className: "button"}, React.createElement("div", {className: "fileUpload btn btn-primary"}, React.createElement("span", null, React.createElement("i", {className: "fa fa-paperclip"})), React.createElement("input", { className: "upload", type: "file", accept: "/*", onChange: this.uploadFile}) ) ), React.createElement("div", {className: "filename"}, this.state.filename ), React.createElement(ProgressBar,{now:this.state.progress, label:'%(percent)s%', srOnly:true}) ) ); } }); module.exports = ReactS3Uploader;
var objects = require('../src/09-objects.js').objects; describe('Objects ', function () { 'use strict'; it('should ', function () { var p1 = objects.point(1, 3); var p2 = objects.point(-2, 2); var p3 = objects.point(3, -1); expect(Math.floor(objects.calculateDistances(p1, p2))).toBe(3); expect(Math.floor(objects.calculateDistances(p2, p3))).toBe(5); expect(Math.floor(objects.calculateDistances(p3, p1))).toBe(4); var l1 = objects.line(p1, p2); var l2 = objects.line(p2, p3); var l3 = objects.line(p3, p1); expect(objects.isTriangle(l1, l2, l3)).toBeTruthy(); }); // it('should remove elements from array', function () { // var arr = [1, 2, 1, 4, 1, 3, 4, 1, 111, 3, 2, 1, '1']; // var expected = [2, 4, 3, 4, 111, 3, 2, '1']; // expect(objects.removeElement(arr, 1)).toEqual(expected); // }); it('should check if object has property', function () { expect(objects.hasProperty({length: 1}, 'length')).toBeTruthy(); expect(objects.hasProperty({size: 1}, 'length')).toBeFalsy(); }); it('should print tha names of the youngest person', function () { var people = [ {firstName: 'AA', lastName: 'AA', age: 32}, {firstName: 'BB', lastName: 'BB', age: 81}, {firstName: 'CC', lastName: 'CC', age: 19}, {firstName: 'DD', lastName: 'DD', age: 25}, {firstName: 'EE', lastName: 'EE', age: 51} ]; expect(objects.youngestPerson(people)).toBe('CC CC'); }); it('should group people by given statement', function () { objects.People.addPerson('firstName1', 'lastName1', 10); objects.People.addPerson('firstName2', 'lastName2', 12); objects.People.addPerson('firstName3', 'lastName3', 11); objects.People.addPerson('firstName4', 'lastName4', 10); expect(objects.People.getPeople()).toEqual([ {'firstName': 'firstName1', 'lastName': 'lastName1', 'age': 10}, {'firstName': 'firstName2', 'lastName': 'lastName2', 'age': 12}, {'firstName': 'firstName3', 'lastName': 'lastName3', 'age': 11}, {'firstName': 'firstName4', 'lastName': 'lastName4', 'age': 10} ]); expect(objects.People.group('age')).toEqual({ 10: [ {'firstName': 'firstName1', 'lastName': 'lastName1', 'age': 10}, {'firstName': 'firstName4', 'lastName': 'lastName4', 'age': 10} ], 11: [{'firstName': 'firstName3', 'lastName': 'lastName3', 'age': 11}], 12: [{'firstName': 'firstName2', 'lastName': 'lastName2', 'age': 12}] }); }); });
import proxyquire from 'proxyquire'; import {stub} from 'sinon'; import should from 'should'; const noop = function() {}; describe('Move Resource', function(){ let r; let req = {body: {upperX: 5, upperY: 5, robots: {}}}; let res = {}; let Grid; let move; let robotFactory; let Resource; beforeEach(() => { Grid = stub({ default: (x, y) => { //Validate grid constructor usage x.should.eql(req.body.upperX); y.should.eql(req.body.upperY); }, }); robotFactory = stub({ default: (robots) => { robots.should.eql(req.body.robots) } }); move = stub({ default: () => {} }); r = proxyquire('./../move', { './../model/grid': Grid, './../service/robot_factory': robotFactory, './../service/move': move, }).default; res = stub({end: noop, json: noop}); }); it('should have handle property', function(){ (typeof r).should.eql('function'); }) it('should call next', function(done){ r(req, res, done); }); it('should construct grid', function() { r(req, res, noop); Grid.default.calledOnce.should.eql(true); }); it('should construct robots', function() { r(req, res, noop); robotFactory.default.calledOnce.should.eql(true); }); it('should processMove', function() { r(req, res, noop); move.default.calledOnce.should.eql(true); }); it('should return output of move svc', function() { move.default.returns({test: true}); r(req, res, noop); const response = res.json.getCall(0).args; response[0].should.eql({test: true}); }); })
export default class VideoRepository { constructor(httpClient) { this.httpClient = httpClient; } latest() { return this.httpClient.get('/api/videos/latest'); } get(videoId) { return this.httpClient.get('/api/videos/' + videoId); } labels(videoId) { return this.httpClient.get('/api/videos/' + videoId + '/labels'); } vote(videoId, vote) { return this.httpClient.post('/api/votes/video/' + videoId, { vote }); } }
angular.module('option', [ 'filter.i18n', 'service.storage', 'service.setting', 'ui.bootstrap.bindHtml' ]) .config(function() { }) .controller('optionController', function($rootScope, $scope, appSetting) { appSetting.bind('ready', function() { $scope.setting = $.extend(true, {}, appSetting.data); $("#spectrum-color").spectrum({ showInput: true, color: $scope.setting.color, chooseText: chrome.i18n.getMessage('spectrumChoose'), cancelText: chrome.i18n.getMessage('spectrumCancel'), change: function (c) { $scope.setting.color = c.toHexString(); } }); $("#spectrum-bgcolor").spectrum({ showInput: true, color: $scope.setting.bgColor, chooseText: chrome.i18n.getMessage('spectrumChoose'), cancelText: chrome.i18n.getMessage('spectrumCancel'), change: function (color) { $scope.setting.bgColor = color.toHexString(); } }); $("#spectrum-bordercolor").spectrum({ showInput: true, color: $scope.setting.borderColor, chooseText: chrome.i18n.getMessage('spectrumChoose'), cancelText: chrome.i18n.getMessage('spectrumCancel'), change: function (color) { $scope.setting.borderColor = color.toHexString(); } }); $scope.saveAndClose = function() { appSetting.set($scope.setting) .then(function() { window.close(); }); }; $scope.setDefault = function() { $scope.setting = $.extend(true, {}, appSetting.default); $("#spectrum-color").spectrum("set", $scope.setting.color); $("#spectrum-bgcolor").spectrum("set", $scope.setting.bgColor); $("#spectrum-bordercolor").spectrum("set", $scope.setting.borderColor); }; $scope.$watch('setting', function(newValue, oldValue) { //if(newValue === oldValue) return; if(newValue.hotKeySimple == newValue.hotKeyEntire || newValue.hotKeySimple == newValue.hotKeySmart || newValue.hotKeySmart == newValue.hotKeyEntire) { //$scope.error = 'Duplicate Hot Key.' $scope.error = chrome.i18n.getMessage('errorDuplicate'); } else { $scope.error = ''; } }, true); $scope.error = ''; }); }) .run(function() { });
conn = new Mongo(); db = conn.getDB("sci") //var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/; db.tweets.find().forEach(function(element) { var dStr = element.created_at; dStr.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/,"$1 $2 $4 $3 UTC"); var d = new Date(dStr); print(d); // Just to make sure it's still working... element.created_at = d; db.tweets.save(element); }) print(db.tweets.find({},{created_at:1}).limit(10).forEach(function(f) { print (f.created_at instanceof Date) } )); cursor = db.tweets.find().sort({created_at:1}).limit(5); while (cursor.hasNext()) { printjson(cursor.next()); }
import frRegionsMerc from "./frRegionsMerc.json"; import frRegionsMill from "./frRegionsMill.json"; export { frRegionsMerc, frRegionsMill }; //# sourceMappingURL=index.js.map
/** * Created by pomy on 10/01/2017. */ 'use strict'; let Handlebars = require('handlebars'); let Metalsmith = require('metalsmith'); let ora = require('ora'); let async = require('async'); let render = require('consolidate').handlebars.render; let path = require('path'); let chalk = require('chalk'); let log = require('./log'); let getSetting = require('./settings'); let ask = require('./ask'); let filesFilter = require('./files-filter'); let utils = require('./utils'); // support for vuejs template Handlebars.registerHelper('if_eq', function (a, b, opts) { return a === b ? opts.fn(this) : opts.inverse(this) }); Handlebars.registerHelper('unless_eq', function (a, b, opts) { return a === b ? opts.inverse(this) : opts.fn(this) }); /** * Generate a template given a `tmpDir` and `dest`. * * @param {String} projectName * @param {String} tmpDir * @param {String} dest * @param {Function} done */ module.exports = function (projectName, tmpDir, dest, done) { let metalsmith; let setting = getSetting(projectName, tmpDir); let tplPath = path.join(tmpDir, 'template'); // register handlebars helpers setting.helpers && Object.keys(setting.helpers).map(function (key) { Handlebars.registerHelper(key, setting.helpers[key]) }); if(utils.isExist(tplPath)){ metalsmith = Metalsmith(tplPath); } else { metalsmith = Metalsmith(tmpDir); } let data = Object.assign(metalsmith.metadata(), { destDirName: projectName, isCwd: dest === process.cwd(), noEscape: true }); ora({ text: `generating project ${projectName}...`, }).stopAndPersist(chalk.blue('**')); log.tips(); metalsmith .use(askQuestions(setting)) .use(filter(setting)) .use(template) .clean(false) .source('.') // start from template root instead of `./src` which is Metalsmith's default for `source` .destination(dest) .build(function (err) { log.tips(); if(err){ return done(err); } //Generated success ora({ text: chalk.green(`${projectName} generated success`) }).succeed(); log.tips(); done(null,setting.completeMessage); }); return data; }; //ask user for input info function askQuestions (setting) { return (files, metalsmith, done) => { ask(setting.prompts, metalsmith.metadata(), done); } } //files filter function filter (setting) { return (files,metalsmith,done) => { filesFilter(setting.filters,files,metalsmith.metadata(),done); } } //generate template function template (files,metalsmith,done) { let keys = Object.keys(files); let metadata = metalsmith.metadata(); async.each(keys, (file, next) => { //judge file is in node_modules directory let inNodeModules = /node_modules/.test(file); let str = inNodeModules ? '' : files[file].contents.toString(); // do not attempt to render files that do not have mustaches and is in node_modules directory if (inNodeModules || !/{{([^{}]+)}}/g.test(str)) { return next(); } render(str, metadata, (err, res) => { if (err) { return next(err); } files[file].contents = new Buffer(res); next(); }); },done); }
/** * @license Copyright (c) 2012, Viet Trinh All Rights Reserved. * Available via MIT license. */ /** * Test tests handler B. */ define([], function() { return { name: 'testsHandlerB' }; });
/** * Main controller for Ghost frontend */ /*global require, module */ var moment = require('moment'), RSS = require('rss'), _ = require('lodash'), url = require('url'), when = require('when'), Route = require('express').Route, api = require('../api'), config = require('../config'), errors = require('../errorHandling'), filters = require('../../server/filters'), template = require('../helpers/template'), frontendControllers, // Cache static post permalink regex staticPostPermalink = new Route(null, '/:slug/:edit?'); function getPostPage(options) { return api.settings.read('postsPerPage').then(function (postPP) { var postsPerPage = parseInt(postPP.value, 10); // No negative posts per page, must be number if (!isNaN(postsPerPage) && postsPerPage > 0) { options.limit = postsPerPage; } return api.posts.browse(options); }).then(function (page) { // A bit of a hack for situations with no content. if (page.pages === 0) { page.pages = 1; } return page; }); } function formatPageResponse(posts, page) { return { posts: posts, pagination: { page: page.page, prev: page.prev, next: page.next, limit: page.limit, total: page.total, pages: page.pages } }; } function handleError(next) { return function (err) { var e = new Error(err.message); e.status = err.errorCode; return next(e); }; } frontendControllers = { 'homepage': function (req, res, next) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, options = { page: pageParam }; // No negative pages, or page 1 if (isNaN(pageParam) || pageParam < 1 || (pageParam === 1 && req.route.path === '/page/:page/')) { return res.redirect(config().paths.subdir + '/'); } return getPostPage(options).then(function (page) { // If page is greater than number of pages we have, redirect to last page if (pageParam > page.pages) { return res.redirect(page.pages === 1 ? config().paths.subdir + '/' : (config().paths.subdir + '/page/' + page.pages + '/')); } // Render the page of posts filters.doFilter('prePostsRender', page.posts).then(function (posts) { res.render('index', formatPageResponse(posts, page)); }); }).otherwise(handleError(next)); }, 'tag': function (req, res, next) { // Parse the page number var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, options = { page: pageParam, tag: req.params.slug }; // Get url for tag page function tagUrl(tag, page) { var url = config().paths.subdir + '/tag/' + tag + '/'; if (page && page > 1) { url += 'page/' + page + '/'; } return url; } // No negative pages, or page 1 if (isNaN(pageParam) || pageParam < 1 || (req.params.page !== undefined && pageParam === 1)) { return res.redirect(tagUrl(options.tag)); } return getPostPage(options).then(function (page) { // If page is greater than number of pages we have, redirect to last page if (pageParam > page.pages) { return res.redirect(tagUrl(options.tag, page.pages)); } // Render the page of posts filters.doFilter('prePostsRender', page.posts).then(function (posts) { api.settings.read('activeTheme').then(function (activeTheme) { var paths = config().paths.availableThemes[activeTheme.value], view = paths.hasOwnProperty('tag') ? 'tag' : 'index', // Format data for template response = _.extend(formatPageResponse(posts, page), { tag: page.aspect.tag }); res.render(view, response); }); }); }).otherwise(handleError(next)); }, 'single': function (req, res, next) { var path = req.path, params, editFormat, usingStaticPermalink = false; api.settings.read('permalinks').then(function (permalink) { editFormat = permalink.value[permalink.value.length - 1] === '/' ? ':edit?' : '/:edit?'; // Convert saved permalink into an express Route object permalink = new Route(null, permalink.value + editFormat); // Check if the path matches the permalink structure. // // If there are no matches found we then // need to verify it's not a static post, // and test against that permalink structure. if (permalink.match(path) === false) { // If there are still no matches then return. if (staticPostPermalink.match(path) === false) { // Throw specific error // to break out of the promise chain. throw new Error('no match'); } permalink = staticPostPermalink; usingStaticPermalink = true; } params = permalink.params; // Sanitize params we're going to use to lookup the post. var postLookup = _.pick(permalink.params, 'slug', 'id'); // Query database to find post return api.posts.read(postLookup); }).then(function (post) { if (!post) { return next(); } function render() { // If we're ready to render the page but the last param is 'edit' then we'll send you to the edit page. if (params.edit !== undefined) { return res.redirect(config().paths.subdir + '/ghost/editor/' + post.id + '/'); } filters.doFilter('prePostsRender', post).then(function (post) { api.settings.read('activeTheme').then(function (activeTheme) { var paths = config().paths.availableThemes[activeTheme.value], view = template.getThemeViewForPost(paths, post); res.render(view, {post: post}); }); }); } // If we've checked the path with the static permalink structure // then the post must be a static post. // If it is not then we must return. if (usingStaticPermalink) { if (post.page === 1) { return render(); } return next(); } // If there is any date based paramter in the slug // we will check it against the post published date // to verify it's correct. if (params.year || params.month || params.day) { var slugDate = [], slugFormat = []; if (params.year) { slugDate.push(params.year); slugFormat.push('YYYY'); } if (params.month) { slugDate.push(params.month); slugFormat.push('MM'); } if (params.day) { slugDate.push(params.day); slugFormat.push('DD'); } slugDate = slugDate.join('/'); slugFormat = slugFormat.join('/'); if (slugDate === moment(post.published_at).format(slugFormat)) { return render(); } return next(); } render(); }).otherwise(function (err) { // If we've thrown an error message // of 'no match' then we found // no path match. if (err.message === 'no match') { return next(); } return handleError(next)(err); }); }, 'rss': function (req, res, next) { // Initialize RSS var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, feed; // No negative pages, or page 1 if (isNaN(pageParam) || pageParam < 1 || (pageParam === 1 && req.route.path === '/rss/:page/')) { return res.redirect(config().paths.subdir + '/rss/'); } // TODO: needs refactor for multi user to not use first user as default return when.settle([ api.users.read({id : 1}), api.settings.read('title'), api.settings.read('description'), api.settings.read('permalinks') ]).then(function (result) { var user = result[0].value, title = result[1].value.value, description = result[2].value.value, permalinks = result[3].value, siteUrl = config.urlFor('home', null, true), feedUrl = config.urlFor('rss', null, true); feed = new RSS({ title: title, description: description, generator: 'Ghost v' + res.locals.version, feed_url: feedUrl, site_url: siteUrl, ttl: '60' }); return api.posts.browse({page: pageParam}).then(function (page) { var maxPage = page.pages, feedItems = []; // A bit of a hack for situations with no content. if (maxPage === 0) { maxPage = 1; page.pages = 1; } // If page is greater than number of pages we have, redirect to last page if (pageParam > maxPage) { return res.redirect(config().paths.subdir + '/rss/' + maxPage + '/'); } filters.doFilter('prePostsRender', page.posts).then(function (posts) { posts.forEach(function (post) { var deferred = when.defer(), item = { title: _.escape(post.title), guid: post.uuid, url: config.urlFor('post', {post: post, permalinks: permalinks}, true), date: post.published_at, categories: _.pluck(post.tags, 'name'), author: user ? user.name : null }, content = post.html; //set img src to absolute url content = content.replace(/src=["|'|\s]?([\w\/\?\$\.\+\-;%:@&=,_]+)["|'|\s]?/gi, function (match, p1) { /*jslint unparam:true*/ p1 = url.resolve(siteUrl, p1); return "src='" + p1 + "' "; }); //set a href to absolute url content = content.replace(/href=["|'|\s]?([\w\/\?\$\.\+\-;%:@&=,_]+)["|'|\s]?/gi, function (match, p1) { /*jslint unparam:true*/ p1 = url.resolve(siteUrl, p1); return "href='" + p1 + "' "; }); item.description = content; feed.item(item); deferred.resolve(); feedItems.push(deferred.promise); }); }); when.all(feedItems).then(function () { res.set('Content-Type', 'text/xml'); res.send(feed.xml()); }); }); }).otherwise(handleError(next)); } }; module.exports = frontendControllers;
'use strict'; var Events = require('Events'); var profile = require('../../../../views/profile/index.js'); var msgPlus = require('../../../../views/msgPlus/index.js'); var modal = require('../../../../views/modal/index.js'); var industryWarn = require('../../../../views/industryWarn/index.js'); /**IE8不支持 function haloPlugins(options) { var opts = options || {}; this.profile = profile; this.msgPlus = msgPlus; //this.$ = window.jQuery; } **/ var haloPlugins = {}; haloPlugins.profile = profile; haloPlugins.msgPlus = msgPlus; haloPlugins.modal = modal; haloPlugins.industryWarn = industryWarn; haloPlugins.HandleEvents = (function(){ var isIDCard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/; var events = new Events({ '.search-chip-input input@keyup':'enter', '.search-chip-input .input-group@click':'getFocus', '.search-chip-input input@focus':'inputFocus', '.search-chip-input input@blur':'inputBlur', '.search-chip-input i@click':'search' }) function initProfile(code) { if(isIDCard2.test(code)){ profile.init({ certificateCode:code }); }else{ var err = $('.search-chip-input input').attr('err-msg'); $('.search-chip-input input').val(err); $('.search-chip-input input').blur(); profile.destroy(); } } return { init: function() { events.dispatch(this); }, enter: function(e) { var idCard = $(this).val(); if(e.keyCode == 13 ){ initProfile(idCard); } }, getFocus: function() { var $placeholder=$(this).find('span'); var $input=$(this).find('input'); $placeholder.hide(); $input.focus(); }, inputFocus: function() { var err = $('.search-chip-input input').attr('err-msg'); var value = $(this).val(); if(value == ''){ $(this).next('span').hide(); }else if(value == err){ $(this).val(''); } }, inputBlur: function() { if($(this).val()==''){ $(this).next('span').show(); } }, search: function() { var idCard = $('.search-chip-input input').val(); initProfile(idCard); } } }()); haloPlugins.HandleEvents.init(); module.exports=haloPlugins;//function 对象必须用new
var assert = require('assert'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var logger = require('../../../../mage').core.logger.context('msgStream', 'HttpPolling'); function HttpPollingHost(style, cfg) { assert(style === 'shortpolling' || style === 'longpolling', 'Invalid HttpPolling style'); EventEmitter.call(this); this.style = style; this.timeout = (cfg.heartbeat || 0) * 1000; this.res = null; this.address = { address: null, type: null }; this.confirmIds = null; } util.inherits(HttpPollingHost, EventEmitter); exports.longpolling = { create: function (cfg) { return new HttpPollingHost('longpolling', cfg); } }; exports.shortpolling = { create: function (cfg) { return new HttpPollingHost('shortpolling', cfg); } }; // Universal transport API: HttpPollingHost.prototype.getDisconnectStyle = function () { return this.style === 'shortpolling' ? 'always' : 'ondelivery'; }; HttpPollingHost.prototype.getAddressInfo = function () { return this.address; }; HttpPollingHost.prototype.getConfirmIds = function () { var ids = this.confirmIds; this.confirmIds = null; return ids; }; HttpPollingHost.prototype.deliver = function (msgs) { if (!this.res) { logger.warning('No client to deliver to'); return; } logger.verbose('Delivering', msgs.length, 'messages'); // msgs: [id, content, id, content, id, content, etc...] // build a response JSON string // msgs: { msgId: jsonstring, msgId: jsonstring, msgId: jsonstring } if (msgs.length === 0) { if (this.style === 'shortpolling') { this.res.writeHead(204, { pragma: 'no-cache' }); this.res.end(); this._closeConnection(); } return; } var props = []; for (var i = 0, len = msgs.length; i < len; i += 2) { var id = msgs[i]; var msg = msgs[i + 1]; props.push('"' + id + '":' + msg); } var data = '{' + props.join(',') + '}'; this.res.writeHead(200, { 'content-type': 'application/json', pragma: 'no-cache' }); this.res.end(data); this._closeConnection(); }; HttpPollingHost.prototype.respondBadRequest = function (reason) { if (this.res.finished) { logger.verbose('Cannot respond bad request (client gone)'); return; } logger.verbose('Responding bad request:', reason); this.res.writeHead(400, { 'content-type': 'text/plain; charset=UTF-8', pragma: 'no-cache' }); if (reason) { this.res.end(reason); } else { this.res.end(); } this._closeConnection(); }; HttpPollingHost.prototype.respondServerError = function () { // used when we fail to confirm a session key for example if (this.res.finished) { logger.verbose('Cannot respond server error (client gone)'); return; } logger.verbose('Responding server error'); this.res.writeHead(500, { // 500: Internal service error pragma: 'no-cache' }); this.res.end(); this._closeConnection(); }; HttpPollingHost.prototype.close = function () { logger.verbose('Closing client'); this._sendHeartbeat(); }; // HTTP transport specific API: HttpPollingHost.prototype.setConnection = function (req, res, query) { logger.verbose('Connection established'); this.res = res; if (query.confirmIds) { this.confirmIds = query.confirmIds.split(','); } if (query.sessionKey) { this.address.address = query.sessionKey; this.address.type = 'session'; } query = null; // set up heartbeat timeout and premature connection-lost handling if (this.timeout) { req.setTimeout(this.timeout, () => this._sendHeartbeat()); res.setTimeout(this.timeout, () => this._sendHeartbeat()); } // "close" indicates that the underlying connection was terminated before response.end() was // called or able to flush. req.on('close', () => { logger.debug('Client connection disappeared'); this._closeConnection(); }); }; HttpPollingHost.prototype.respondToHead = function () { if (this.res.finished) { logger.verbose('Cannot respond to HEAD request (client gone)'); return; } this.res.writeHead(200, { 'content-type': 'application/json', pragma: 'no-cache' }); this.res.end(); this._closeConnection(); }; HttpPollingHost.prototype._closeConnection = function () { if (this.res.finished) { return; } this.emit('close'); this.removeAllListeners(); }; HttpPollingHost.prototype._sendHeartbeat = function () { if (this.res.finished) { return; } this.res.writeHead(204, { pragma: 'no-cache' }); this.res.end(); this._closeConnection(); };
"use strict"; var debug = require("debug")("ch-arge:lib/bootstrap.js"); var types = require("./types.js"); var mTable = require("../tools/map-table.js").mapTable; var initTable = require("../tools/map-table.js").initTable; var docDone = require("../tools/map-table.js").saveTable; exports.newType = newType; exports.mkRegExp = mkRegExp; /* add types and create a ghmd-table along the way */ initTable(); newTypeAndDoc("Object", checkObject, ["Object", "object", "Obj", "obj"]); newTypeAndDoc("Array", checkArray, ["Array", "array", "Arr", "arr"]); newTypeAndDoc( "Function", checkFunction, ["Function", "function", "Fn", "fn", "Func", "func"]); newTypeAndDoc("RegExp", checkRegExp, ["RegExp", "regexp", "regExp", "Regexp"]); newTypeAndDoc("Date", checkDate, ["Date", "date"]); newTypeAndDoc("Symbol", checkSymbol, ["Symbol", "symbol", "Sym", "sym"]); newTypeAndDoc("String", checkString, ["String", "Str"]); newTypeAndDoc("Number", checkNumber, ["Number", "Num"]); newTypeAndDoc("Boolean", checkBoolean, ["Boolean", "Bool"]); newTypeAndDoc("null", checkNull, ["null"]); newTypeAndDoc("undefined", checkUndefined, ["undefined"]); newTypeAndDoc("string", checkstring, ["string", "str"]); newTypeAndDoc("number", checknumber, ["number", "num"]); newTypeAndDoc("integer", checkInteger, ["integer", "int"]); newTypeAndDoc("float", checkFloat, ["float", "flt"]); newTypeAndDoc("boolean", checkboolean, ["boolean", "bool"]); newTypeAndDoc("NaN", isNaN, ["NaN", "Nan", "naN", "nan"]); docDone(); /* type checks */ // use if necessary function escape (string) { return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // complex types function checkObject (thing) { return typeof thing === "object" && thing !== null && ( Object.getPrototypeOf(thing) === Object.prototype || thing instanceof Object); } function checkArray (thing) { return Array.isArray(thing) && thing instanceof Array; } function checkFunction (thing) { return typeof thing === "function" && Function.prototype.isPrototypeOf(thing); } function checkRegExp (thing) { return thing instanceof RegExp; } function checkDate (thing) { return thing instanceof Date; } function checkSymbol (thing) { return typeof thing === "symbol"; } function checkString (thing) { return typeof thing === "object" && thing instanceof String; } function checkNumber (thing) { return typeof thing === "object" && thing instanceof Number; } function checkBoolean (thing) { return typeof thing === "object" && thing instanceof Boolean; } // primitives function checkNull (thing) { return thing === null; } function checkUndefined (thing) { return thing === undefined; } function checkstring (thing) { return typeof thing === "string" && !(thing instanceof String); } function checknumber (thing) { return typeof thing === "number" && !isNaN(thing) && !(thing instanceof Number); } // NOTE: integer is both comlex and primitive aka integer === Integer function checkInteger (thing) { return parseInt(thing) === thing && !isNaN(thing); } // NOTE: float is both complex and primitive aka float === Float function checkFloat (thing) { return parseInt(thing) !== thing && !isNaN(thing); } function checkboolean (thing) { return typeof thing === "boolean" && !(thing instanceof Boolean); } function newType (name, checkFn, aliases) { if (typeof name !== "string") throw new TypeError("'name' must be a string"); if (name in types) throw new Error("'name': " + name + " already taken"); if ("function" !== typeof checkFn) throw new TypeError("'checkFn' must be an fn"); if (!Array.isArray(aliases)) throw new TypeError("'aliases' not array"); var re, reFn; re = mkRegExp.apply(null, aliases); if (!(re instanceof RegExp)) throw new Error("failed to make reg exp from aliases"); reFn = function (str) { str = str.trim(); return str.match(re); }; if (debug.enabled) reFn._name = "re" + name[0].toUpperCase() + name.slice(1); types[name] = [reFn, checkFn]; }; function mkRegExp () { var aliases, regExp, inner, alias, sep, pattern, lastAlias; aliases = Array.prototype.slice.call(arguments, 0, arguments.length); lastAlias = aliases.length -1; inner = ""; sep = "[|\\s,]+"; if (aliases.length === 0) throw new Error("at least one alias is required"); for (var ind in aliases) { if (!aliases.hasOwnProperty(ind)) continue; // avoid props in [[prototype]] alias = aliases[ind]; if (typeof alias !== "string") throw new TypeError("'alias' must be of type string"); debug ("mkRegExp() alias #%d: %s", ind, alias); inner += alias + (+ind === lastAlias ? "" : "|"); } pattern = "(?:" + "^" + "|" + sep + ")" + "(!*)" + "(?:" + inner + ")" + "(?:" + sep + "|" + "$" + ")"; regExp = new RegExp(pattern); return regExp; } function newTypeAndDoc (_1, _2, _3) { newType(_1, _2, _3); mTable(_1, _3); }
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Card, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import Avatar from 'material-ui/Avatar'; import FontIcon from 'material-ui/FontIcon'; import moment from 'moment'; import Constatns from '../../config/Constants'; const defaultAvatar = <Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />; class NewsItem extends PureComponent { render () { const { article } = this.props; const link = <a className="news-link" href={article.url} target="_blank">{article.title}</a>; return ( <Card className="news-item"> <CardHeader title={article.author || 'Anonymous'} subtitle={`Published on ${moment(article.publishedAt).format(Constatns.datetime.format)}`} avatar={defaultAvatar} /> { article.urlToImage ? <CardMedia className="news-item-media" overlay={<CardTitle title={link} subtitle={article.description} />} > <img src={article.urlToImage} alt={article.title} /> </CardMedia> : <CardText> <CardTitle title={link} subtitle={article.description} /> </CardText> } </Card> ); } } NewsItem.propTypes = { article: PropTypes.object.isRequired, }; export default NewsItem;
module.exports = { frameworks: ['jasmine'], basePath: '../', files: [ 'test/unit/jasmine/*.js' ], preprocessors: { 'src/**/*.js': ['webpack'], 'test/**/*.js': ['webpack'] }, webpack: require('./webpack.config.js'), webpackMiddleware: { noInfo: true }, plugins: [ 'karma-webpack', 'karma-chrome-launcher', 'karma-jasmine' ] };
const Deferred = require('promised-io/promise').Deferred const all = require('promised-io/promise').all const when = require('promised-io/promise').when const debug = require('debug')('p3api-server:TranscriptomicsGene') const request = require('request') const config = require('../config') const distributeURL = config.get('distributeURL') const workspaceAPI = config.get('workspaceAPI') function getWorkspaceObjects (paths, metadataOnly, token) { const def = new Deferred() if (!(paths instanceof Array)) { paths = [paths] } paths = paths.map(decodeURIComponent) request({ method: 'POST', url: workspaceAPI, json: true, body: { id: 1, method: 'Workspace.get', version: '1.1', params: [{objects: paths, metadata_only: metadataOnly}] }, headers: { 'accept': 'application/json', 'content-type': 'application/json', 'authorization': token } }, function (err, resObj, results) { if (err) { debug('Error retrieving object from workspace: ', err) def.reject(err) return } if (results.result) { // const data = []; const defs = results.result[0].map(function (obj) { // debug("reading obj0: ", obj[0]); // debug("reading obj1: ", obj[1]); const meta = { name: obj[0][0], type: obj[0][1], path: obj[0][2], creation_time: obj[0][3], id: obj[0][4], owner_id: obj[0][5], size: obj[0][6], userMeta: obj[0][7], autoMeta: obj[0][8], user_permissions: obj[0][9], global_permission: obj[0][10], link_reference: obj[0][11] } // debug("meta: ", meta); if (metadataOnly) { // data.push(meta); // return true; return meta // def.resolve(meta); // return true; } if (!meta.link_reference) { // data.push({metadata: meta, data: obj[1]}); // return true; return ({metadata: meta, data: obj[1]}) // def.resolve({metadata: meta, data: obj[1]}); // return true; } else { const headers = { 'Authorization': 'OAuth ' + token } // debug("headers: ", headers); const defShock = new Deferred() request({ method: 'GET', url: meta.link_reference + '?download', headers: headers }, function (err, res, d) { // debug("err", err); // debug("res: ", res); // debug("downloaded: ", d); defShock.resolve({ metadata: meta, data: d }) // return true; }) return defShock.promise } }) // debug("defs: ", defs); all(defs).then(function (d) { // debug("all defs are resolved", paths); // debug("body: ", d); def.resolve(d) }) } }) return def.promise } function readWorkspaceExperiments (tgState, options) { const wsExpIds = tgState['wsExpIds'] const wsComparisonIds = tgState['wsComparisonIds'] const def = new Deferred() const expressionFiles = wsExpIds.map(function (exp_id) { const parts = exp_id.split('/') const jobName = parts.pop() return parts.join('/') + '/.' + jobName + '/expression.json' }) // debug("expressionFiles: ", expressionFiles); when(getWorkspaceObjects(expressionFiles, false, options.token), function (results) { const p3FeatureIdSet = {} const p2FeatureIdSet = {} const expressions = results.map(function (d) { // debug("expressionFile results", typeof d.data, wsComparisonIds); // debug(d.data); if (!wsComparisonIds) { return JSON.parse(d.data)['expression'] } else { return JSON.parse(d.data)['expression'].filter(function (e) { return wsComparisonIds.indexOf(e.pid) >= 0 }) } }) const flattened = [].concat.apply([], expressions) // debug("expressions: ", typeof flattened, flattened.length); flattened.forEach(function (expression) { // debug("expression: ", typeof expression, expression.feature_id, expression.na_feature_id); if (expression.hasOwnProperty('feature_id')) { if (!p3FeatureIdSet.hasOwnProperty(expression.feature_id)) { p3FeatureIdSet[expression.feature_id] = true } } else if (expression.hasOwnProperty('na_feature_id')) { if (!p2FeatureIdSet.hasOwnProperty(expression.na_feature_id)) { p2FeatureIdSet[expression.na_feature_id] = true } } }) // debug("expressions:", flattened.length, "p3 ids: ", Object.keys(p3FeatureIdSet).length, "p2 ids: ", Object.keys(p2FeatureIdSet).length); def.resolve({ expressions: flattened, p3FeatureIds: Object.keys(p3FeatureIdSet), p2FeatureIds: Object.keys(p2FeatureIdSet) }) }) return def.promise } function readPublicExperiments (tgState, options) { const def = new Deferred() request.post({ url: distributeURL + 'transcriptomics_gene/', headers: { 'Accept': 'application/solr+json', 'Content-Type': 'application/rqlquery+x-www-form-urlencoded', 'Authorization': options.token || '' }, body: tgState.query + '&select(pid,refseq_locus_tag,feature_id,log_ratio,z_score)&limit(1)' }, function (error, res, response) { if (error || res.statusCode !== 200) { debug(error, res.statusCode) def.reject(error) return } try { response = JSON.parse(response) }catch(err){ return def.reject("readPublicExperiments(): Error parsing JSON from SOLR: " + err) } const numFound = response.response.numFound const fetchSize = 25000 const steps = Math.ceil(numFound / fetchSize) const allRequests = [] for (let i = 0; i < steps; i++) { const deferred = new Deferred() const range = 'items=' + (i * fetchSize) + '-' + ((i + 1) * fetchSize - 1) // debug("Range: ", range); request.post({ url: distributeURL + 'transcriptomics_gene/', headers: { 'Accept': 'application/json', 'Content-Type': 'application/rqlquery+x-www-form-urlencoded', 'Range': range, 'Authorization': options.token || '' }, body: tgState.query + '&select(pid,refseq_locus_tag,feature_id,log_ratio,z_score)' }, function (err, res, body) { if (err) { deferred.reject(err) return } try { body = JSON.parse(body) }catch(err){ return deferred.reject("Unable to parse JSON from SOLR: " + err); } deferred.resolve(body) }) allRequests.push(deferred) } all(allRequests).then(function (results) { const expressions = [] const p3FeatureIdSet = {} // const p2FeatureIdSet = {}; results.forEach(function (genes) { // debug("genes count: ", genes.length); genes.forEach(function (gene) { expressions.push(gene) if (gene.hasOwnProperty('feature_id')) { if (!p3FeatureIdSet.hasOwnProperty(gene.feature_id)) { p3FeatureIdSet[gene.feature_id] = true } // }else if(gene.hasOwnProperty("na_feature_id")){ // if(!p2FeatureIdSet.hasOwnProperty(gene.na_feature_id)){ // p2FeatureIdSet[gene.na_feature_id] = true; // } } }) }) // debug("expressions:", expressions.length, "p3 ids: ", Object.keys(p3FeatureIdSet).length, "p2 ids: ", Object.keys(p2FeatureIdSet).length); def.resolve({expressions: expressions, p3FeatureIds: Object.keys(p3FeatureIdSet), p2FeatureIds: []}) }) }) return def.promise } function processTranscriptomicsGene (tgState, options) { const def = new Deferred() let wsCall = new Deferred() if (tgState.hasOwnProperty('wsExpIds')) { wsCall = readWorkspaceExperiments(tgState, options) } else { wsCall.resolve({expressions: [], p3FeatureIds: [], p2FeatureIds: []}) } let publicCall = new Deferred() if (tgState.hasOwnProperty('pbExpIds')) { publicCall = readPublicExperiments(tgState, options) } else { publicCall.resolve({expressions: [], p3FeatureIds: [], p2FeatureIds: []}) } all(publicCall, wsCall).then(function (results) { // all(publicCall).then(function(results){ const comparisonIdList = tgState.comparisonIds const wsP3FeatureIdList = results[1].p3FeatureIds const wsP2FeatureIdList = results[1].p2FeatureIds const wsExpressions = results[1].expressions const pbP3FeatureIdList = results[0].p3FeatureIds const pbP2FeatureIdList = results[0].p2FeatureIds // [] const pbExpressions = results[0].expressions const p3FeatureIdList = wsP3FeatureIdList.concat(pbP3FeatureIdList) const p2FeatureIdList = wsP2FeatureIdList.concat(pbP2FeatureIdList) const expressions = wsExpressions.concat(pbExpressions) debug('p3 ids: ', p3FeatureIdList.length, 'p2 ids: ', p2FeatureIdList.length) const query = { q: [(p3FeatureIdList.length > 0) ? 'feature_id:(' + p3FeatureIdList.join(' OR ') + ')' : '', (p3FeatureIdList.length > 0 && p2FeatureIdList.length > 0) ? ' OR ' : '', (p2FeatureIdList.length > 0) ? 'p2_feature_id:(' + p2FeatureIdList.join(' OR ') + ')' : ''].join(''), fl: 'feature_id,p2_feature_id,strand,product,accession,start,end,patric_id,refseq_locus_tag,alt_locus_tag,genome_name,genome_id,gene' } // debug("genome_feature query: ", query); const q = Object.keys(query).map(p => p + '=' + query[p]).join('&') const fetchSize = 25000 const steps = Math.ceil((p3FeatureIdList.length + p2FeatureIdList.length) / fetchSize) const allRequests = [] for (let i = 0; i < steps; i++) { const subDef = Deferred() const range = 'items=' + (i * fetchSize) + '-' + ((i + 1) * fetchSize - 1) // debug("Range: ", range); request.post({ url: distributeURL + 'genome_feature/', headers: { 'Accept': 'application/json', 'Content-Type': 'application/solrquery+x-www-form-urlencoded', 'Range': range, 'Authorization': options.token || '' }, body: q }, function (err, res, body) { if (err) { subDef.reject(err) return } try { body = JSON.parse(body) }catch(err){ return subDef.reject("Error parsing JSON from SOLR: " + err) } subDef.resolve(body); }) allRequests.push(subDef) } all(allRequests).then(function (body) { const features = [].concat.apply([], body) const expressionHash = {} expressions.forEach(function (expression) { let featureId if (expression.hasOwnProperty('feature_id')) { featureId = expression.feature_id } else if (expression.hasOwnProperty('na_feature_id')) { featureId = expression.na_feature_id } if (!expressionHash.hasOwnProperty(featureId)) { var expr = {samples: {}} if (expression.hasOwnProperty('feature_id')) { expr.feature_id = expression.feature_id } if (expression.hasOwnProperty('na_feature_id')) { expr.p2_feature_id = expression.na_feature_id } if (expression.hasOwnProperty('refseq_locus_tag')) { expr.refseq_locus_tag = expression.refseq_locus_tag } const log_ratio = expression.log_ratio const z_score = expression.z_score expr.samples[expression.pid.toString()] = { log_ratio: log_ratio || '', z_score: z_score || '' } expr.up = (log_ratio != null && Number(log_ratio) > 0) ? 1 : 0 expr.down = (log_ratio != null && Number(log_ratio) < 0) ? 1 : 0 expressionHash[featureId] = expr } else { expr = expressionHash[featureId] if (!expr.samples.hasOwnProperty(expression.pid.toString())) { log_ratio = expression.log_ratio z_score = expression.z_score expr.samples[expression.pid.toString()] = { log_ratio: log_ratio || '', z_score: z_score || '' } if (log_ratio != null && Number(log_ratio) > 0) { expr.up++ } if (log_ratio != null && Number(log_ratio) < 0) { expr.down++ } expressionHash[featureId] = expr } } }) const data = [] features.forEach(function (feature) { let expr if (expressionHash.hasOwnProperty(feature.feature_id)) { expr = expressionHash[feature.feature_id] } else if (expressionHash.hasOwnProperty(feature.p2_feature_id)) { expr = expressionHash[feature.p2_feature_id] } if (expr) { // build expr object let count = 0 expr.sample_binary = comparisonIdList.map(function (comparisonId) { if (expr.samples.hasOwnProperty(comparisonId) && expr.samples[comparisonId].log_ratio !== '') { count++ return '1' } else { return '0' } }).join('') expr.sample_size = count const datum = Object.assign(feature, expr) data.push(datum) } }) def.resolve(data) }) }) return def.promise } module.exports = { requireAuthentication: false, validate: function (params) { const tgState = params[0] return tgState && tgState.comparisonIds.length > 0 }, execute: function (params) { const def = new Deferred() const tgState = params[0] const opts = params[1] when(processTranscriptomicsGene(tgState, opts), function (result) { def.resolve(result) }, function (err) { def.reject('Unable to process protein family queries. ' + err) }) return def.promise } }
var data = []; for (var i = 0; i < 100; ++i) data.push(i); var pred = function (x) { return x % 3 === 0; }; var etalon = []; for (var i = 0; i < 100; i += 3) etalon.push(i); module.exports = { data: data, pred: pred, etalon: etalon };