text
stringlengths
7
3.69M
/** * Created by a689638 on 6/13/2016. */ (function () { 'use strict'; angular.module('routerApp').directive('archetypeRowView', [function () { return { restrict:'A', scope:{ definitions:'=', data:'=', archetype:'=' }, templateUrl:'views/archetypes/archetype-row.html' } }]); })();
export const USER_LOGIN = 'USER_LOGIN'; export const USER_LOGIN_OUT = 'USER_LOGIN_OUT'; export const USER_REGISTER = 'USER_REGISTER'; export const USER_RESET_PASSWORD = 'USER_RESET_PASSWORD'; export const USER_INFO = 'USER_INFO'; export const DEPART = 'DEPART'; export const DOCTOR_LIST = 'DOCTOR_LIST';
(function ($) { $.fn.ee_calendar = function(opts) { var options = { onSelect: function (dateText, inst) {} }; $.extend(options, opts); var $el = this; var tzoffset = (new Date()).getTimezoneOffset() * 60000; var holidays = getHolidays(); var $datepicker = $el.find('.ee-calendar__datepicker'); var highlightDays = $el.data('highlighted-days'); $datepicker.datepicker({ showOtherMonths: true, dateFormat: "D, dd.mm.yy", onSelect: function (dateText, inst) { updateDateControls(inst); $(inst.input).datepicker('refresh'); options.onSelect(dateText, inst); }, beforeShowDay: function (date){ var classes = ''; var title = 'Нет мероприятий за этот день'; var highlightDay = findHighlightDay(new Date(date - tzoffset).toISOString().slice(0, 10), highlightDays); if (highlightDay) { classes+= 'ui-state-highlighted ui-state-highlighted-' + highlightDay.color; title = highlightDay.caption; } var year = date.getFullYear(), month = date.getMonth(), day = date.getDate(); // see if the current date should be highlighted for (var i=0; i < holidays.length; ++i) if (year == holidays[i][0] && month == holidays[i][1] - 1 && day == holidays[i][2]) return [true, classes + ' ui-datepicker-week-end', title]; return [true, classes, title]; } }); updateDateControls($.datepicker._getInst($datepicker[0])); $el.find('.ee-calendar__controls i').click(function () { dateIncDec($(this), $datepicker); }); return $el; }; function updateDateControls(inst) { var $controls = $(inst.input[0]).prev(); $controls.find('.ee-calendar__controls-day span').text(inst.currentDay); $controls.find('.ee-calendar__controls-month span').text($.datepicker.formatDate("MM", new Date( inst.currentYear, inst.currentMonth ))); $controls.find('.ee-calendar__controls-year span').text(inst.currentYear); } function dateIncDec($element, $datepicker) { var date = $datepicker.datepicker("getDate"); var $parent = $element.parent(); if ($parent.hasClass('ee-calendar__controls-day')) { date.setDate(date.getDate() + ($element.is(':first-child') ? -1 : 1)); } if ($parent.hasClass('ee-calendar__controls-month')) { date.setMonth(date.getMonth() + ($element.is(':first-child') ? -1 : 1)); } if ($parent.hasClass('ee-calendar__controls-year')) { date.setFullYear(date.getFullYear() + ($element.is(':first-child') ? -1 : 1)); } $datepicker.datepicker("setDate", date); updateDateControls($.datepicker._getInst($datepicker[0])); } function findHighlightDay(day, highlightDays) { if (!highlightDays) return false; var result = false; $.each(highlightDays, function () { if (day === this.day) { result = this; return false; } }); return result; } function getHolidays() { var holidays = [ { "Год/Месяц": 1999, "Январь": "1,2,3,4,6*,7,9,10,16,17,23,24,30,31", "Февраль": "6,7,13,14,20,21,27,28", "Март": "6,7,8,13,14,20,21,27,28", "Апрель": "3,4,10,11,17,18,24,25,30*", "Май": "1,2,3,4,8,9,10,15,16,22,23,29,30", "Июнь": "5,6,11*,12,13,14,19,20,26,27", "Июль": "3,4,10,11,17,18,24,25,31", "Август": "1,7,8,14,15,21,22,28,29", "Сентябрь": "4,5,11,12,18,19,25,26", "Октябрь": "2,3,9,10,16,17,23,24,30,31", "Ноябрь": "6,7,8,13,14,20,21,27,28", "Декабрь": "4,5,11,12,13,18,19,25,26,31*", "Всего рабочих дней": 251, "Всего праздничных и выходных дней": 114, "Количество рабочих часов при 40-часовой рабочей неделе": 2004, "Количество рабочих часов при 36-часовой рабочей неделе": 1807.2, "Количество рабочих часов при 24-часовой рабочей неделе": 1204.8 }, { "Год/Месяц": 2000, "Январь": "1,2,3,4,6*,7,8,9,15,16,22,23,29,30", "Февраль": "5,6,12,13,19,20,26,27", "Март": "4,5,7*,8,11,12,18,19,25,26", "Апрель": "1,2,8,9,15,16,22,23,29,30", "Май": "1,2,6,7,8*,9,13,14,20,21,27,28", "Июнь": "3,4,10,11,12,17,18,24,25", "Июль": "1,2,8,9,15,16,22,23,29,30", "Август": "5,6,12,13,19,20,26,27", "Сентябрь": "2,3,9,10,16,17,23,24,30", "Октябрь": "1,7,8,14,15,21,22,28,29", "Ноябрь": "4,5,7,11,12,18,19,25,26", "Декабрь": "2,3,9,10,11*,12,16,17,23,24,30,31", "Всего рабочих дней": 250, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1995, "Количество рабочих часов при 36-часовой рабочей неделе": 1800, "Количество рабочих часов при 24-часовой рабочей неделе": 1200 }, { "Год/Месяц": 2001, "Январь": "1,2,6,7,8,13,14,20,21,27,28", "Февраль": "3,4,10,11,17,18,24,25", "Март": "3,4,7*,8,10,11,17,18,24,25,31", "Апрель": "1,7,8,14,15,21,22,28,29,30*", "Май": "1,2,5,6,8*,9,12,13,19,20,26,27", "Июнь": "2,3,9,10,11*,12,16,17,23,24,30", "Июль": "1,7,8,14,15,21,22,28,29", "Август": "4,5,11,12,18,19,25,26", "Сентябрь": "1,2,8,9,15,16,22,23,29,30", "Октябрь": "6,7,13,14,20,21,27,28", "Ноябрь": "3,4,6*,7,10,11,17,18,24,25", "Декабрь": "1,2,8,9,12,15,16,22,23,29,30", "Всего рабочих дней": 251, "Всего праздничных и выходных дней": 114, "Количество рабочих часов при 40-часовой рабочей неделе": 2001, "Количество рабочих часов при 36-часовой рабочей неделе": 1807.2, "Количество рабочих часов при 24-часовой рабочей неделе": 1204.8 }, { "Год/Месяц": 2002, "Январь": "1,2,5,6,7,12,13,19,20,26,27", "Февраль": "2,3,9,10,16,17,22*,23,24,25", "Март": "2,3,7*,8,9,10,16,17,23,24,30,31", "Апрель": "6,7,13,14,20,21,28,30*", "Май": "1,2,3,4,5,8*,9,10,11,12,19,25,26", "Июнь": "1,2,8,9,11*,12,15,16,22,23,29,30", "Июль": "6,7,13,14,20,21,27,28", "Август": "3,4,10,11,17,18,24,25,31", "Сентябрь": "1,7,8,14,15,21,22,28,29", "Октябрь": "5,6,12,13,19,20,26,27", "Ноябрь": "2,3,6*,7,8,9,16,17,23,24,30", "Декабрь": "1,7,8,11*,12,13,14,21,22,28,29,31*", "Всего рабочих дней": 250, "Всего праздничных и выходных дней": 115, "Количество рабочих часов при 40-часовой рабочей неделе": 1992, "Количество рабочих часов при 36-часовой рабочей неделе": 1792, "Количество рабочих часов при 24-часовой рабочей неделе": 1192 }, { "Год/Месяц": 2003, "Январь": "1,2,3,5*,6,7,11,12,18,19,25,26", "Февраль": "1,2,8,9,15,16,22,23,24", "Март": "1,2,7*,8,9,10,15,16,22,23,29,30", "Апрель": "5,6,12,13,19,20,26,27,30*", "Май": "1,2,3,4,8*,9,10,11,17,18,24,25,31", "Июнь": "1,7,8,11*,12,13,14,15,22,28,29", "Июль": "5,6,12,13,19,20,26,27", "Август": "2,3,9,10,16,17,23,24,30,31", "Сентябрь": "6,7,13,14,20,21,27,28", "Октябрь": "4,5,11,12,18,19,25,26", "Ноябрь": "1,2,6*,7,8,9,15,16,22,23,29,30", "Декабрь": "6,7,11*,12,13,14,20,21,27,28,31*", "Всего рабочих дней": 250, "Всего праздничных и выходных дней": 115, "Количество рабочих часов при 40-часовой рабочей неделе": 1992, "Количество рабочих часов при 36-часовой рабочей неделе": 1792, "Количество рабочих часов при 24-часовой рабочей неделе": 1192 }, { "Год/Месяц": 2004, "Январь": "1,2,3,4,6*,7,10,11,17,18,24,25,31", "Февраль": "1,7,8,14,15,21,22,23,28,29", "Март": "6,7,8,13,14,20,21,27,28", "Апрель": "3,4,10,11,17,18,24,25,30*", "Май": "1,2,3,4,8,9,10,15,16,22,23,29,30", "Июнь": "5,6,11*,12,13,14,19,20,26,27", "Июль": "3,4,10,11,17,18,24,25,31", "Август": "1,7,8,14,15,21,22,28,29", "Сентябрь": "4,5,11,12,18,19,25,26", "Октябрь": "2,3,9,10,16,17,23,24,30,31", "Ноябрь": "6,7,8,13,14,20,21,27,28", "Декабрь": "4,5,11,12,13,18,19,25,26,31*", "Всего рабочих дней": 251, "Всего праздничных и выходных дней": 115, "Количество рабочих часов при 40-часовой рабочей неделе": 2004, "Количество рабочих часов при 36-часовой рабочей неделе": 1803.2, "Количество рабочих часов при 24-часовой рабочей неделе": 1200.8 }, { "Год/Месяц": 2005, "Январь": "1,2,3,4,5,6,7,8,9,10,15,16,22,23,29,30", "Февраль": "5,6,12,13,19,20,22*,23,26,27", "Март": "5*,6,7,8,12,13,19,20,26,27", "Апрель": "2,3,9,10,16,17,23,24,30", "Май": "1,2,7,8,9,14,15,21,22,28,29", "Июнь": "4,5,11,12,13,18,19,25,26", "Июль": "2,3,9,10,16,17,23,24,30,31", "Август": "6,7,13,14,20,21,27,28", "Сентябрь": "3,4,10,11,17,18,24,25", "Октябрь": "1,2,8,9,15,16,22,23,29,30", "Ноябрь": "3*,4,5,6,12,13,19,20,26,27", "Декабрь": "3,4,10,11,17,18,24,25,31", "Всего рабочих дней": 248, "Всего праздничных и выходных дней": 117, "Количество рабочих часов при 40-часовой рабочей неделе": 1981, "Количество рабочих часов при 36-часовой рабочей неделе": 1782.6, "Количество рабочих часов при 24-часовой рабочей неделе": 1187.4 }, { "Год/Месяц": 2006, "Январь": "1,2,3,4,5,6,7,8,9,14,15,21,22,28,29", "Февраль": "4,5,11,12,18,19,22*,23,24,25", "Март": "4,5,7*,8,11,12,18,19,25,26", "Апрель": "1,2,8,9,15,16,22,23,29,30", "Май": "1,6*,7,8,9,13,14,20,21,27,28", "Июнь": "3,4,10,11,12,17,18,24,25", "Июль": "1,2,8,9,15,16,22,23,29,30", "Август": "5,6,12,13,19,20,26,27", "Сентябрь": "2,3,9,10,16,17,23,24,30", "Октябрь": "1,7,8,14,15,21,22,28,29", "Ноябрь": "3*,4,5,6,11,12,18,19,25,26", "Декабрь": "2,3,9,10,16,17,23,24,30,31", "Всего рабочих дней": 248, "Всего праздничных и выходных дней": 117, "Количество рабочих часов при 40-часовой рабочей неделе": 1981, "Количество рабочих часов при 36-часовой рабочей неделе": 1782.6, "Количество рабочих часов при 24-часовой рабочей неделе": 1187.4 }, { "Год/Месяц": 2007, "Январь": "1,2,3,4,5,6,7,8,13,14,20,21,27,28", "Февраль": "3,4,10,11,17,18,22*,23,24,25", "Март": "3,4,7*,8,10,11,17,18,24,25,31", "Апрель": "1,7,8,14,15,21,22,28*,29,30", "Май": "1,5,6,8*,9,12,13,19,20,26,27", "Июнь": "2,3,9*,10,11,12,16,17,23,24,30", "Июль": "1,7,8,14,15,21,22,28,29", "Август": "4,5,11,12,18,19,25,26", "Сентябрь": "1,2,8,9,15,16,22,23,29,30", "Октябрь": "6,7,13,14,20,21,27,28", "Ноябрь": "3,4,5,10,11,17,18,24,25", "Декабрь": "1,2,8,9,15,16,22,23,29*,30,31", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1986, "Количество рабочих часов при 36-часовой рабочей неделе": 1786.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1189.2 }, { "Год/Месяц": 2008, "Январь": "1,2,3,4,5,6,7,8,12,13,19,20,26,27", "Февраль": "2,3,9,10,16,17,22*,23,24,25", "Март": "1,2,7*,8,9,10,15,16,22,23,29,30", "Апрель": "5,6,12,13,19,20,26,27,30*", "Май": "1,2,3,8*,9,10,11,17,18,24,25,31", "Июнь": "1,8,11*,12,13,14,15,21,22,28,29", "Июль": "5,6,12,13,19,20,26,27", "Август": "2,3,9,10,16,17,23,24,30,31", "Сентябрь": "6,7,13,14,20,21,27,28", "Октябрь": "4,5,11,12,18,19,25,26", "Ноябрь": "1*,2,3,4,8,9,15,16,22,23,29,30", "Декабрь": "6,7,13,14,20,21,27,28,31*", "Всего рабочих дней": 250, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1993, "Количество рабочих часов при 36-часовой рабочей неделе": 1793, "Количество рабочих часов при 24-часовой рабочей неделе": 1193 }, { "Год/Месяц": 2009, "Январь": "1,2,3,4,5,6,7,8,9,10,17,18,24,25,31", "Февраль": "1,7,8,14,15,21,22,23,28", "Март": "1,7,8,9,14,15,21,22,28,29", "Апрель": "4,5,11,12,18,19,25,26", "Май": "1,2,3,8*,9,10,11,16,17,23,24,30,31", "Июнь": "6,7,11*,12,13,14,20,21,27,28", "Июль": "4,5,11,12,18,19,25,26", "Август": "1,2,8,9,15,16,22,23,29,30", "Сентябрь": "5,6,12,13,19,20,26,27", "Октябрь": "3,4,10,11,17,18,24,25,31", "Ноябрь": "1,3*,4,7,8,14,15,21,22,28,29", "Декабрь": "5,6,12,13,19,20,26,27,31*", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1987, "Количество рабочих часов при 36-часовой рабочей неделе": 1787.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1190.2 }, { "Год/Месяц": 2010, "Январь": "1,2,3,4,5,6,7,8,9,10,16,17,23,24,30,31", "Февраль": "6,7,13,14,20,21,22,23,27*,28", "Март": "6,7,8,13,14,20,21,27,28", "Апрель": "3,4,10,11,17,18,24,25,30*", "Май": "1,2,3,8,9,10,15,16,22,23,29,30", "Июнь": "5,6,11*,12,13,14,19,20,26,27", "Июль": "3,4,10,11,17,18,24,25,31", "Август": "1,7,8,14,15,21,22,28,29", "Сентябрь": "4,5,11,12,18,19,25,26", "Октябрь": "2,3,9,10,16,17,23,24,30,31", "Ноябрь": "3*,4,5,6,7,14,20,21,27,28", "Декабрь": "4,5,11,12,18,19,25,26,31*", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1987, "Количество рабочих часов при 36-часовой рабочей неделе": 1787.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1190.2 }, { "Год/Месяц": 2011, "Январь": "1,2,3,4,5,6,7,8,9,10,15,16,22,23,29,30", "Февраль": "5,6,12,13,19,20,22*,23,26,27", "Март": "5*,6,7,8,12,13,19,20,26,27", "Апрель": "2,3,9,10,16,17,23,24,30", "Май": "1,2,7,8,9,14,15,21,22,28,29", "Июнь": "4,5,11,12,13,18,19,25,26", "Июль": "2,3,9,10,16,17,23,24,30,31", "Август": "6,7,13,14,20,21,27,28", "Сентябрь": "3,4,10,11,17,18,24,25", "Октябрь": "1,2,8,9,15,16,22,23,29,30", "Ноябрь": "3*,4,5,6,12,13,19,20,26,27", "Декабрь": "3,4,10,11,17,18,24,25,31", "Всего рабочих дней": 248, "Всего праздничных и выходных дней": 117, "Количество рабочих часов при 40-часовой рабочей неделе": 1981, "Количество рабочих часов при 36-часовой рабочей неделе": 1782.6, "Количество рабочих часов при 24-часовой рабочей неделе": 1187.4 }, { "Год/Месяц": 2012, "Январь": "1,2,3,4,5,6,7,8,9,14,15,21,22,28,29", "Февраль": "4,5,11,12,18,19,22*,23,25,26", "Март": "3,4,7*,8,9,10,17,18,24,25,31", "Апрель": "1,7,8,14,15,21,22,28*,29,30", "Май": "1,6,7,8,9,12*,13,19,20,26,27", "Июнь": "2,3,9*,10,11,12,16,17,23,24,30", "Июль": "1,7,8,14,15,21,22,28,29", "Август": "4,5,11,12,18,19,25,26", "Сентябрь": "1,2,8,9,15,16,22,23,29,30", "Октябрь": "6,7,13,14,20,21,27,28", "Ноябрь": "3,4,5,10,11,17,18,24,25", "Декабрь": "1,2,8,9,15,16,22,23,29*,30,31", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 117, "Количество рабочих часов при 40-часовой рабочей неделе": 1986, "Количество рабочих часов при 36-часовой рабочей неделе": 1786.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1189.2 }, { "Год/Месяц": 2013, "Январь": "1,2,3,4,5,6,7,8,12,13,19,20,26,27", "Февраль": "2,3,9,10,16,17,22*,23,24", "Март": "2,3,7*,8,9,10,16,17,23,24,30,31", "Апрель": "6,7,13,14,20,21,27,28", "Май": "1,2,3,4,5,8*,9,10,11,12,18,19,25,26", "Июнь": "1,2,8,9,11*,12,15,16,22,23,29,30", "Июль": "6,7,13,14,20,21,27,28", "Август": "3,4,10,11,17,18,24,25,31", "Сентябрь": "1,7,8,14,15,21,22,28,29", "Октябрь": "5,6,12,13,19,20,26,27", "Ноябрь": "2,3,4,9,10,16,17,23,24,30", "Декабрь": "1,7,8,14,15,21,22,28,29,31*", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 118, "Количество рабочих часов при 40-часовой рабочей неделе": 1970, "Количество рабочих часов при 36-часовой рабочей неделе": 1772.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1179.6 }, { "Год/Месяц": 2014, "Январь": "1,2,3,4,5,6,7,8,11,12,18,19,25,26", "Февраль": "1,2,8,9,15,16,22,23,24*", "Март": "1,2,7*,8,9,10,15,16,22,23,29,30", "Апрель": "5,6,12,13,19,20,26,27,30*", "Май": "1,2,3,4,8*,9,10,11,17,18,24,25,31", "Июнь": "1,7,8,11*,12,13,14,15,21,22,28,29", "Июль": "5,6,12,13,19,20,26,27", "Август": "2,3,9,10,16,17,23,24,30,31", "Сентябрь": "6,7,13,14,20,21,27,28", "Октябрь": "4,5,11,12,18,19,25,26", "Ноябрь": "1,2,3,4,8,9,15,16,22,23,29,30", "Декабрь": "6,7,13,14,20,21,27,28", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 118, "Количество рабочих часов при 40-часовой рабочей неделе": 1970, "Количество рабочих часов при 36-часовой рабочей неделе": 1772.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1179.6 }, { "Год/Месяц": 2015, "Январь": "1,2,3,4,5,6,7,8,9,10,11,17,18,24,25,31", "Февраль": "1,7,8,14,15,21,22,23,28", "Март": "1,7,8,9,14,15,21,22,28,29", "Апрель": "4,5,11,12,18,19,25,26,30*", "Май": "1,2,3,4,8*,9,10,11,16,17,23,24,30,31", "Июнь": "6,7,11*,12,13,14,20,21,27,28", "Июль": "4,5,11,12,18,19,25,26", "Август": "1,2,8,9,15,16,22,23,29,30", "Сентябрь": "5,6,12,13,19,20,26,27", "Октябрь": "3,4,10,11,17,18,24,25,31", "Ноябрь": "1,3*,4,7,8,14,15,21,22,28,29", "Декабрь": "5,6,12,13,19,20,26,27,31*", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 118, "Количество рабочих часов при 40-часовой рабочей неделе": 1971, "Количество рабочих часов при 36-часовой рабочей неделе": 1773.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1180.6 }, { "Год/Месяц": 2016, "Январь": "1,2,3,4,5,6,7,8,9,10,16,17,23,24,30,31", "Февраль": "6,7,13,14,20*,21,22,23,27,28", "Март": "5,6,7,8,12,13,19,20,26,27", "Апрель": "2,3,9,10,16,17,23,24,30", "Май": "1,2,3,7,8,9,14,15,21,22,28,29", "Июнь": "4,5,11,12,13,18,19,25,26", "Июль": "2,3,9,10,16,17,23,24,30,31", "Август": "6,7,13,14,20,21,27,28", "Сентябрь": "3,4,10,11,17,18,24,25", "Октябрь": "1,2,8,9,15,16,22,23,29,30", "Ноябрь": "3*,4,5,6,12,13,19,20,26,27", "Декабрь": "3,4,10,11,17,18,24,25,31", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 119, "Количество рабочих часов при 40-часовой рабочей неделе": 1974, "Количество рабочих часов при 36-часовой рабочей неделе": 1776.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1183.6 }, { "Год/Месяц": 2017, "Январь": "1,2,3,4,5,6,7,8,14,15,21,22,28,29", "Февраль": "4,5,11,12,18,19,22*,23,24,25,26", "Март": "4,5,7*,8,11,12,18,19,25,26", "Апрель": "1,2,8,9,15,16,22,23,29,30", "Май": "1,6,7,8,9,13,14,20,21,27,28", "Июнь": "3,4,10,11,12,17,18,24,25", "Июль": "1,2,8,9,15,16,22,23,29,30", "Август": "5,6,12,13,19,20,26,27", "Сентябрь": "2,3,9,10,16,17,23,24,30", "Октябрь": "1,7,8,14,15,21,22,28,29", "Ноябрь": "3*,4,5,6,11,12,18,19,25,26", "Декабрь": "2,3,9,10,16,17,23,24,30,31", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 118, "Количество рабочих часов при 40-часовой рабочей неделе": 1973, "Количество рабочих часов при 36-часовой рабочей неделе": 1775.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1182.6 }, { "Год/Месяц": 2018, "Январь": "1,2,3,4,5,6,7,8,13,14,20,21,27,28", "Февраль": "3,4,10,11,17,18,22*,23,24,25", "Март": "3,4,7*,8,9,10,11,17,18,24,25,31", "Апрель": "1,7,8,14,15,21,22,28*,29,30", "Май": "1,2,5,6,8*,9,12,13,19,20,26,27", "Июнь": "2,3,9*,10,11,12,16,17,23,24,30", "Июль": "1,7,8,14,15,21,22,28,29", "Август": "4,5,11,12,18,19,25,26", "Сентябрь": "1,2,8,9,15,16,22,23,29,30", "Октябрь": "6,7,13,14,20,21,27,28", "Ноябрь": "3,4,5,10,11,17,18,24,25", "Декабрь": "1,2,8,9,15,16,22,23,29*,30,31", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 118, "Количество рабочих часов при 40-часовой рабочей неделе": 1970, "Количество рабочих часов при 36-часовой рабочей неделе": 1772.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1179.6 }, { "Год/Месяц": 2019, "Январь": "1,2,3,4,5,6,7,8,12,13,19,20,26,27", "Февраль": "2,3,9,10,16,17,22*,23,24", "Март": "2,3,7*,8,9,10,16,17,23,24,30,31", "Апрель": "6,7,13,14,20,21,27,28,30*", "Май": "1,2,3,4,5,8*,9,10,11,12,18,19,25,26", "Июнь": "1,2,8,9,11*,12,15,16,22,23,29,30", "Июль": "6,7,13,14,20,21,27,28", "Август": "3,4,10,11,17,18,24,25,31", "Сентябрь": "1,7,8,14,15,21,22,28,29", "Октябрь": "5,6,12,13,19,20,26,27", "Ноябрь": "2,3,4,9,10,16,17,23,24,30", "Декабрь": "1,7,8,14,15,21,22,28,29,31*", "Всего рабочих дней": 247, "Всего праздничных и выходных дней": 118, "Количество рабочих часов при 40-часовой рабочей неделе": 1970, "Количество рабочих часов при 36-часовой рабочей неделе": 1772.4, "Количество рабочих часов при 24-часовой рабочей неделе": 1179.6 }, { "Год/Месяц": 2020, "Январь": "1,2,3,4,5,6,7,8,11,12,18,19,25,26", "Февраль": "1,2,8,9,15,16,22,23,24+,29", "Март": "1,7,8,9+,14,15,21,22,28,29", "Апрель": "4,5,11,12,18,19,25,26,30*", "Май": "1,2,3,8*,9,10,11+,16,17,23,24,30,31", "Июнь": "6,7,11*,12,13,14,20,21,27,28", "Июль": "4,5,11,12,18,19,25,26", "Август": "1,2,8,9,15,16,22,23,29,30", "Сентябрь": "5,6,12,13,19,20,26,27", "Октябрь": "3,4,10,11,17,18,24,25,31", "Ноябрь": "1,3*,4,7,8,14,15,21,22,28,29", "Декабрь": "5,6,12,13,19,20,26,27,31*", "Всего рабочих дней": 250, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1995, "Количество рабочих часов при 36-часовой рабочей неделе": 1795, "Количество рабочих часов при 24-часовой рабочей неделе": 1195 }, { "Год/Месяц": 2021, "Январь": "1,2,3,4,5,6,7,8,9,10,16,17,23,24,30,31", "Февраль": "6,7,13,14,20,21,22*,23,27,28", "Март": "6,7,8*,13,14,20,21,27,28", "Апрель": "3,4,10,11,17,18,24,25,30*", "Май": "1,2,3+,8,9,10+,15,16,22,23,29,30", "Июнь": "5,6,11*,12,13,14+,19,20,26,27", "Июль": "3,4,10,11,17,18,24,25,31", "Август": "1,7,8,14,15,21,22,28,29", "Сентябрь": "4,5,11,12,18,19,25,26", "Октябрь": "2,3,9,10,16,17,23,24,30,31", "Ноябрь": "3*,4,6,7,13,14,20,21,27,28", "Декабрь": "4,5,11,12,18,19,25,26,31*", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1987, "Количество рабочих часов при 36-часовой рабочей неделе": 1787.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1190.2 }, { "Год/Месяц": 2022, "Январь": "1,2,3,4,5,6,7,8,9,15,16,22,23,29,30", "Февраль": "5,6,12,13,19,20,22*,23,26,27", "Март": "5,6,7*,8,12,13,19,20,26,27", "Апрель": "2,3,9,10,16,17,23,24,30", "Май": "1,2+,7,8,9,14,15,21,22,28,29", "Июнь": "4,5,11,12,13+,18,19,25,26", "Июль": "2,3,9,10,16,17,23,24,30,31", "Август": "6,7,13,14,20,21,27,28", "Сентябрь": "3,4,10,11,17,18,24,25", "Октябрь": "1,2,8,9,15,16,22,23,29,30", "Ноябрь": "3*,4,5,6,12,13,19,20,26,27", "Декабрь": "3,4,10,11,17,18,24,25,31", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1989, "Количество рабочих часов при 36-часовой рабочей неделе": 1789.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1192.2 }, { "Год/Месяц": 2023, "Январь": "1,2,3,4,5,6,7,8,14,15,21,22,28,29", "Февраль": "4,5,11,12,18,19,22*,23,25,26", "Март": "4,5,7*,8,11,12,18,19,25,26", "Апрель": "1,2,8,9,15,16,22,23,29,30", "Май": "1,6,7,8*,9,13,14,20,21,27,28", "Июнь": "3,4,10,11,12,17,18,24,25", "Июль": "1,2,8,9,15,16,22,23,29,30", "Август": "5,6,12,13,19,20,26,27", "Сентябрь": "2,3,9,10,16,17,23,24,30", "Октябрь": "1,7,8,14,15,21,22,28,29", "Ноябрь": "3*,4,5,6+,11,12,18,19,25,26", "Декабрь": "2,3,9,10,16,17,23,24,30,31", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1988, "Количество рабочих часов при 36-часовой рабочей неделе": 1788.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1191.6 }, { "Год/Месяц": 2024, "Январь": "1,2,3,4,5,6,7,8,13,14,20,21,27,28", "Февраль": "3,4,10,11,17,18,22*,23,24,25", "Март": "2,3,7*,8,9,10,16,17,23,24,30,31", "Апрель": "6,7,13,14,20,21,27,28,30*", "Май": "1,4,5,8*,9,11,12,18,19,25,26", "Июнь": "1,2,8,9,11*,12,15,16,22,23,29,30", "Июль": "6,7,13,14,20,21,27,28", "Август": "3,4,10,11,17,18,24,25,31", "Сентябрь": "1,7,8,14,15,21,22,28,29", "Октябрь": "5,6,12,13,19,20,26,27", "Ноябрь": "2,3,4,9,10,16,17,23,24,30", "Декабрь": "1,7,8,14,15,21,22,28,29,31*", "Всего рабочих дней": 250, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1994, "Количество рабочих часов при 36-часовой рабочей неделе": 1794, "Количество рабочих часов при 24-часовой рабочей неделе": 1194 }, { "Год/Месяц": 2025, "Январь": "1,2,3,4,5,6,7,8,11,12,18,19,25,26", "Февраль": "1,2,8,9,15,16,22,23,24+", "Март": "1,2,7*,8,9,10+,15,16,22,23,29,30", "Апрель": "5,6,12,13,19,20,26,27,30*", "Май": "1,3,4,8*,9,10,11,17,18,24,25,31", "Июнь": "1,7,8,11*,12,14,15,21,22,28,29", "Июль": "5,6,12,13,19,20,26,27", "Август": "2,3,9,10,16,17,23,24,30,31", "Сентябрь": "6,7,13,14,20,21,27,28", "Октябрь": "4,5,11,12,18,19,25,26", "Ноябрь": "1,2,3*,4,8,9,15,16,22,23,29,30", "Декабрь": "6,7,13,14,20,21,27,28,31*", "Всего рабочих дней": 249, "Всего праздничных и выходных дней": 116, "Количество рабочих часов при 40-часовой рабочей неделе": 1986, "Количество рабочих часов при 36-часовой рабочей неделе": 1786.8, "Количество рабочих часов при 24-часовой рабочей неделе": 1189.2 } ]; var dates = []; for (var i=0;i<holidays.length;i++) { var obj = holidays[i]; var counter = 0; var year; for (var key in obj) { if (counter === 0) { year = obj[key]; } else if (counter <= 12) { var month = counter; var days = obj[key].split(','); for (var ii = 0;ii<days.length;ii++) { if (days[ii].indexOf('*') > 0) {continue} dates.push([year, month, parseInt(days[ii])]); } } counter++; } } return dates; } ( function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "../widgets/datepicker" ], factory ); } else { // Browser globals factory( jQuery.datepicker ); } }( function( datepicker ) { datepicker.regional.ru = { closeText: "Закрыть", prevText: "&#x3C;Пред", nextText: "След&#x3E;", currentText: "Сегодня", monthNames: [ "Январь","Февраль","Март","Апрель","Май","Июнь", "Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь" ], monthNamesShort: [ "Янв","Фев","Мар","Апр","Май","Июн", "Июл","Авг","Сен","Окт","Ноя","Дек" ], dayNames: [ "воскресенье","понедельник","вторник","среда","четверг","пятница","суббота" ], dayNamesShort: [ "Вс","Пн","Вт","Ср","Чт","Пт","Сб" ], dayNamesMin: [ "Вс","Пн","Вт","Ср","Чт","Пт","Сб" ], weekHeader: "Нед", dateFormat: "dd.mm.yy", firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: "" }; datepicker.setDefaults( datepicker.regional.ru ); return datepicker.regional.ru; } ) ); }(jQuery));
const car = document.getElementById('car'); const topPosition = '200px'; const speed = 100; car.style.right = '1%'; car.style.top = topPosition; let firstTime = true; const startButton = document.getElementById('start-button'); startButton.addEventListener('click', () => { if(firstTime) { carObject.moveCar(); firstTime = false; } }); let stopped = false; const stopButton = document.getElementById('stop-button'); stopButton.addEventListener('click', () => { stopped = true; }) class Car { constructor(car, speed) { this.position = 0; this.speed = speed; this.stopped = false; this.car = car; } moveCar() { if (this.stopped) return; if (this.position > 100) return; this.car.style.right = this.position + '%'; this.position++; setTimeout(() => this.moveCar(), this.speed); } }; const carObject = new Car(car, 300);
function(task, responses){ try{ let ent = JSON.parse(responses[0]['response']); let interesting = ["com.apple.security.cs.allow-jit", "com.apple.security.cs.allow-unsigned-executable-memory", "com.apple.security.cs.allow-dyld-environment-variables", "com.apple.security.cs.disable-library-validation", "com.apple.security.cs.disable-executable-page-protection", "com.apple.security.cs.debugger", "No Entitlements"]; let dict = {}; for(let i = 0; i < ent.length; i++){ if(ent[i]['code_sign'].toString(16).substring(1,2) !== "6"){ dict[ent[i]['process_id']] = {}; dict[ent[i]['process_id']]['bin_path'] = ent[i]['bin_path']; dict[ent[i]['process_id']]['code_sign'] = "0x" + ent[i]['code_sign'].toString(16); try{ for(let j = 0; j < interesting.length; j++){ if(ent[i]['entitlements'].includes(interesting[j])){ dict[ent[i]['process_id']]['entitlements'] = JSON.parse(ent[i]['entitlements']); break; } } }catch(err){ dict[ent[i]['process_id']]['entitlements'] = ent[i]['entitlements']; } } } return "<pre>" + escapeHTML(JSON.stringify(dict, null, 6)) + "</pre>"; }catch(error){ return "<pre>" + error.toString() + escapeHTML(JSON.stringify(responses, null, 6)) + "</pre>"; } }
import React from "react"; import Header from "./components/Header"; import Home from "./pages/Home"; import Detail from "./pages/Detail"; import Search from "./pages/Search"; import { Route, Switch } from "react-router-dom"; import SignInAndSignUp from "./pages/SignInAndSignUp"; function App() { return ( <div className="App"> <Header /> <main> <Switch> <Route path="/" exact component={Home} /> <Route path="/movie/:id" component={Detail} /> <Route path="/signin" component={SignInAndSignUp} /> <Route path="/search/:term" component={Search} /> </Switch> </main> </div> ); } export default App;
// gallery.js //var THREE = require("three"); //var $ = require("jquery"); //var zip = zip.js require("../polyfill.js"); var Map = require("../map"); var renderLoop = require("../model/renderloop"); require("../globals"); var warp = require("tpp-warp"); //On Ready $(function(){ MapManager.transitionTo("tGallery", 0); // currentMap = new Map("tGallery"); // currentMap.load(); // currentMap.queueForMapStart(function(){ // UI.fadeIn(); // }); renderLoop.start({ clearColor: 0x000000, ticksPerSecond : 20, }); });
import mongoose from 'mongoose'; const Schema = mongoose.Schema; const historySchema = new Schema({ name: String, products: [{ _id: Schema.Types.ObjectId, }], customer:{ _id:Schema.Types.ObjectId, phone:String, }, service:String, website:String, status: String, comment:String, billing:{ total:Number, cost:Number, revenue:Number, profit:Number, discount:Number, total_discount:Number, }, sellerId: Schema.Types.ObjectId, history:[{_id:Schema.Types.ObjectId}], meta: { createAt: {type: Date,default: Date.now()}, updateAt: {type: Date,default: Date.now()} } }, {collection:'History'}); export default (mongoose.models && mongoose.models.History ? mongoose.models.History : mongoose.model('History', historySchema))
//globals const contentArea = document.getElementById('content'); const btnHelp = document.getElementById('help_mode'); const btnViewMode = document.getElementById('view_mode'); const btnPinMode = document.getElementById('pin_mode'); const btnRouteMode = document.getElementById('route_mode'); const btnFormClose = document.getElementById('form_close'); const btnRequestDelete = document.getElementById('request_delete_button'); const elevationContainer = document.getElementById('elevation_container'); let map; let pageMode = 'view'; let drawingManager = null; var selectedShape; let drawnShapes = []; let selectedNewMarker = null; let locations = []; let routes = []; let allRouteMarkers = []; let routeLabels = []; const dotLabels = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const elevationWayPoints = 20; // buttons btnViewMode.addEventListener('click', function(e){ toggleMode(e.target.name); }); btnRouteMode.addEventListener('click', function(e){ toggleMode(e.target.name); }); btnPinMode.addEventListener('click', function(e){ toggleMode(e.target.name); }); btnHelp.addEventListener('click', function(){ $('#helpTextModal').modal('show'); }); btnFormClose.addEventListener('click',function(){ if(pageMode == 'pin'){ if(selectedNewMarker != null){ deleteMarker(selectedNewMarker); } } else if(pageMode == 'route'){ deleteAllShapes(); } }); // database call for locations (callback after map initialised) function getLocations(){ $.get("./php/getLocations.php").done(function(data){ // handle errors, get JSON if(data == '0 results'){ throwPageError(data); } else { let queryResults = JSON.parse(data); console.log(queryResults); // sort into locations & routes => put into global vars formatResults(queryResults); // display map initMap(); } }); } function formatResults(results){ results.forEach(result => { // dot markers if(result.lat != null && result.lng != null){ locations.push(result) } // routes if(result.path != null){ let route = { coords : [], elevations : [ ["x","elevation"] ], id: null, distance : null, name : null, level : null, type : null, surfacetype : null, isLoop : function(){ return (this.coords[0].lat == this.coords[this.coords.length-1].lat) && (this.coords[0].lng == this.coords[this.coords.length-1].lng); }, southpoint : function(){ let southpoint = null; let southpoint_lat = null this.coords.forEach(c => { if(southpoint_lat == null || c.lat < southpoint_lat){ southpoint_lat = c.lat; southpoint = c; } }); return new google.maps.LatLng(southpoint.lat, southpoint.lng);; } }; // make route coords array let points = result.path.split(','); points.forEach(point => { let pointObj = { lat: parseFloat(point.split(' ')[0]), lng: parseFloat(point.split(' ')[1]) } route.coords.push(pointObj); }); // make route elevation array if(result.elevation != null){ let elevs = result.elevation.split(','); for(let i=0; i<elevs.length; i++){ let waypoint = round(((i+1)*elevationWayPoints)/1000); route.elevations.push([`${waypoint.toString()} km`, parseInt(elevs[i])]); } } route.id = result.id; route.distance = result.distance; route.name = result.name; route.level = result.level; route.type = result.type; route.surfacetype = result.surfacetype; routes.push(route); } }) } // Define the overlay, derived from google.maps.OverlayView function Label(opt_options) { // Initialization this.setValues(opt_options); // Label specific var span = this.span_ = document.createElement('p'); span.style.cssText = 'position: relative; left: -50%; top: -8px; ' + 'white-space: nowrap; border: none; ' + 'padding: 2px; background-color: white'; var div = this.div_ = document.createElement('div'); div.appendChild(span); div.style.cssText = 'position: absolute; display: none; padding-top: 15px;'; //drag div.draggable = true; } function initialiseLabelClass(){ Label.prototype = new google.maps.OverlayView(); // Implement onAdd Label.prototype.onAdd = function() { var pane = this.getPanes().floatPane; pane.appendChild(this.div_); // Ensures the label is redrawn if the text or position is changed. var me = this; this.listeners_ = [ google.maps.event.addListener(this, 'position_changed', function() { me.draw(); }), google.maps.event.addListener(this, 'text_changed', function() { me.draw(); }), google.maps.event.addDomListener(this.get('map').getDiv(),'mouseleave',function(){ google.maps.event.trigger(this.div_,'mouseup'); }), google.maps.event.addDomListener(this.div_,'mousedown',function(e){ this.style.cursor='move'; me.map.set('draggable',false); me.set('origin',e); me.moveHandler = google.maps.event.addDomListener(me.get('map').getDiv(),'mousemove',function(e){ var origin = me.get('origin'), left = origin.clientX-e.clientX, top = origin.clientY-e.clientY, pos = me.getProjection().fromLatLngToDivPixel(me.get('position')), latLng = me.getProjection().fromDivPixelToLatLng(new google.maps.Point(pos.x-left, pos.y-top)); me.set('origin',e); me.set('position',latLng); me.draw(); }); }), google.maps.event.addDomListener(this.div_,'mouseup',function(){ me.map.set('draggable',true); this.style.cursor='default'; google.maps.event.removeListener(me.moveHandler); }) ]; }; // Implement onRemove Label.prototype.onRemove = function() { var i, I; // remove label this.div_.parentNode.removeChild(this.div_); // Label is removed from the map, stop updating its position/text. for (i = 0, I = this.listeners_.length; i < I; ++i) { google.maps.event.removeListener(this.listeners_[i]); } }; // Implement draw Label.prototype.draw = function() { var projection = this.getProjection(); var position = projection.fromLatLngToDivPixel(this.get('position')); var div = this.div_; div.style.left = position.x + 'px'; div.style.top = position.y + 'px'; div.style.display = 'block'; this.span_.innerHTML = this.get('text').toString(); }; } //initialise map function initMap() { // set the nav buttons toggleMode('view'); // initialise map map = new google.maps.Map(document.getElementById("map"), { center: { lat: 51.903614, lng: -8.468399 }, zoom: 9, }); // drawing controls drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: google.maps.drawing.OverlayType.MARKER, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: [ google.maps.drawing.OverlayType.POLYLINE, ], }, }); initialiseLabelClass(); //initialise line chart // draw stuff on the map drawDotMarkers(); // load the chart package, then draw routes google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawRoutes); // map event listeners // add event listener: click on the map to add new dot & hide route labels map.addListener("click", (e) => { if(pageMode == 'pin'){ placeMarkerAndPanTo(e.latLng, map); } hideAllRouteLabels(); }); // draw line complete google.maps.event.addListener(drawingManager, 'polylinecomplete', function(event) { // get the route coordinates & total distance let newRoute = ''; let distance = 0; let addElevationStr = ''; let dStart = null; event.getPath().getArray().forEach(point => { if(dStart != null){ let dEnd = new google.maps.LatLng(point.lat(), point.lng()); distance += google.maps.geometry.spherical.computeDistanceBetween(dStart, dEnd) } dStart = new google.maps.LatLng(point.lat(), point.lng()); newRoute += `${point.lat()} ${point.lng()},` }) let elevationSteps = Math.floor(distance / elevationWayPoints); distance = round(distance / 1000); newRoute = newRoute.slice(0, -1); // make an id string let idString = newRoute.split(",")[0]; idString = idString.replace(/\s/g, ''); // get route elevation const elevator = new google.maps.ElevationService(); elevator.getElevationAlongPath({path: event.getPath().getArray(),samples: elevationSteps,},function(elevations,status){ if (status !== "OK") { deleteAllShapes(); // Show the error code inside the chartDiv. if(status == 'OVER_QUERY_LIMIT'){ throwPageError('An error occurred: route too long'); } else{ throwPageError(status); } return; } elevations.forEach(elevation =>{ addElevationStr += `${elevation.elevation},`; }) // remove trailing , if(addElevationStr != ''){ addElevationStr = addElevationStr.slice(0, -1); } // set form fields setFormToAdd(); $('#locationPath').val(newRoute); $('#locationDistance').val(distance); $('#locationElevation').val(addElevationStr); $('#locationType').val("Route").change(); $('#locationType').prop("disabled", true).change(); $('#locationId').val(idString); // show modal $('#newLocationModal').modal('show'); }); }); // draw overlay complete google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) { stopDrawing(); let newShape = event.overlay; newShape.type = event.type; drawnShapes.push(newShape); }); } // draw existing data points function drawDotMarkers(){ // make dot markers const markers = locations.map((location, i) => { // get marker position let position = { lat: parseFloat(location.lat), lng: parseFloat(location.lng) } // draw the marker let marker = new google.maps.Marker({ position: position, label: dotLabels[i % dotLabels.length], title: location.name, }); // make the marker label constructDotMarkerLabel(location, marker); // event listener: right click to edit marker google.maps.event.addListener(marker, 'rightclick', function(){ // match right clicked marker with marker info obj let location = null; let idString = `${this.position.lat()}${this.position.lng()}`; locations.forEach(l =>{ if(l.id == idString){ location = l; } }) // prepare & show the form if(location != null){ setFormToUpdate(location); $('#locationType').prop("disabled", false).change(); $('#newLocationModal').modal('show'); } }); return marker; }); // Add a marker clusterer to manage the dot markers. new MarkerClusterer(map, markers, { imagePath: "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m", }); } function drawRoutes(){ const routeMarkers = routes.map((route, i) => { // draw the route let routeMarker = new google.maps.Polyline({ path: route.coords, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 3, polylineID: route.id }); allRouteMarkers.push(routeMarker); // make route visible on map routeMarker.setMap(map); // add event listener: click on route to show info label google.maps.event.addListener(routeMarker, 'click', function() { // hide all route labels hideAllRouteLabels(); // clear & populate the elevation container elevationContainer.innerHTML = ''; drawChart(route); //make the route info label constructRouteLabel(route, routeMarker, elevationContainer.innerHTML); // center map on the mid point of the route & zoom in map.panTo(getHalfWayPoint(route.coords[0],route.coords[route.coords.length-1])); map.setZoom(13); // create an invisible marker & bind the label to it let labelMarker = new google.maps.Marker({ position: getBoundsPoints().labelAnchor, map: map, visible: false }); this.label.bindTo('position', labelMarker, 'position'); // make the start point markers visible if(!route.isLoop()){ this.label.mark1.setVisible(true); this.label.mark2.setVisible(true); } //change selected route color routeMarker.setOptions({strokeColor: '#0bba31'}) // make the selected route label visible this.label.setMap(map); }); // add event listener: right click on route to edit route info google.maps.event.addListener(routeMarker, 'rightclick', function(){ // match right clicked route to route info obj let route = null; routes.forEach(r => { if(r.id == this.polylineID){ route = r; } }); // prepare & show the form if(route!= null){ setFormToUpdate(route); $('#locationType').prop("disabled", true).change(); $('#newLocationModal').modal('show'); } }); }) } // place new dot marker function placeMarkerAndPanTo(latLng, map) { // create the marker let marker = new google.maps.Marker({ position: latLng, map: map, draggable: true }); // center map on the new marker map.panTo(latLng); // make it the selected marker (delete any previously created ones) if(selectedNewMarker != null){ deleteMarker(selectedNewMarker); } selectedNewMarker = marker; // add event listener: click on placed marker to enter info & submit marker.addListener("click", (e) => { let idString = `${e.latLng.lat()}${e.latLng.lng()}`; setFormToAdd(); $('#locationLat').val(e.latLng.lat()); $('#locationLong').val(e.latLng.lng()); $('#locationId').val(idString); $('#locationType').prop("disabled", false).change(); $('#newLocationModal').modal('show'); }); } // make info labels function constructDotMarkerLabel(location, locationMarker) { const infowindow = new google.maps.InfoWindow({ content: constructMarkerLabel(location, null), }); routeLabels.push(infowindow); // add event listener: click on dot marker to open info window locationMarker.addListener("click", () => { hideAllRouteLabels(); infowindow.open(locationMarker.get("map"), locationMarker); }); } function constructRouteLabel(route, routeMarker, chart){ let start1Marker = null; let start2Marker = null; // create share orientation markers if(!route.isLoop()){ start1Marker = new google.maps.Marker({ position: route.coords[0], map: map, label: '1', visible: false }); start2Marker = new google.maps.Marker({ position: route.coords[route.coords.length-1], map: map, label: '2', visible: false }); } // create the route marker label routeMarker.label = new Label(); routeMarker.label.set('text', constructMarkerLabel(route, chart)); routeMarker.label.polylineID = route.id; if(!route.isLoop()){ routeMarker.label.mark1 = start1Marker; routeMarker.label.mark2 = start2Marker; } routeLabels.push(routeMarker.label); } // mode options function toggleMode(mode){ pageMode = mode; if(pageMode == 'view'){ enableViewMode(); disableDrawingMode(); disablePinMode(); } else if(pageMode == 'pin'){ disableViewMode(); disableDrawingMode(); enablePinMode(); } else if(pageMode == 'route'){ disableViewMode(); disablePinMode(); enableDrawingMode(); } } function enableDrawingMode(){ btnRouteMode.disabled = true; btnRouteMode.className = "btn btn-info"; drawingManager.setMap(map); startDrawing(); } function disableDrawingMode(){ btnRouteMode.disabled = false; btnRouteMode.className = "btn btn-outline-info"; if(drawingManager!= null){ drawingManager.setMap(null); } deleteAllShapes(); } function enablePinMode(){ btnPinMode.disabled = true; btnPinMode.className = "btn btn-info"; } function disablePinMode(){ btnPinMode.disabled = false; btnPinMode.className = 'btn btn-outline-info'; if(selectedNewMarker != null){ deleteMarker(selectedNewMarker); } } function enableViewMode(){ btnViewMode.disabled = true; btnViewMode.className = "btn btn-info"; } function disableViewMode(){ btnViewMode.disabled = false; btnViewMode.className = "btn btn-outline-info"; } // drawing functions function stopDrawing(){ drawingManager.setDrawingMode(null); } function startDrawing(){ drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE); } // form modes function setFormToAdd(){ // update form header & action document.getElementById('newLocationModalLabel').innerText = 'Add Location'; document.getElementById('locationForm').action = './php/addLocation.php'; // clear all form fields clearForm(); // delete form btnRequestDelete.hidden = true; } function setFormToUpdate(obj){ //update form header & action document.getElementById('newLocationModalLabel').innerText = 'Update Location'; document.getElementById('locationForm').action = './php/updateLocation.php'; // prefill values of selected location // surface checkboxes if(obj.surfacetype != null){ let formCheckBoxes = document.getElementsByClassName('form-check-input'); let conditions = obj.surfacetype.split(','); conditions.forEach(c => { [].forEach.call(formCheckBoxes, function (el) { if(c == el.value){ el.checked = true; } }); }); } $('#locationName').val(obj.name); $('#locationType').val(obj.type); $('#locationLevel').val(obj.level); $('#locationId').val(obj.id); // delete form $('#locationIdDelete').val(obj.id); $('#locationNameDelete').val(obj.name); btnRequestDelete.hidden = false; } // hide / delete stuff function deleteMarker(marker){ marker.setMap(null); marker = null; } function deleteAllShapes() { for (var i=0; i < drawnShapes.length; i++){ drawnShapes[i].setMap(null); } drawnShapes = []; } function hideAllRouteLabels(){ elevationContainer.innerHTML = ''; routeLabels.forEach(l => { l.setMap(null); if(l.mark1){ l.mark1.setVisible(false); } if(l.mark2){ l.mark2.setVisible(false); } }); allRouteMarkers.forEach(rm =>{ rm.setOptions({strokeColor: '#FF0000'}); }); } function clearForm(){ $('#locationName').val(null); $('#locationType').val('Skate Park'); $('#locationLevel').val('Beginner'); let formCheckBoxes = document.getElementsByClassName('form-check-input'); [].forEach.call(formCheckBoxes, function (el) { el.checked = false; }); } // math function round(num) { var m = Number((Math.abs(num) * 100).toPrecision(15)); return Math.round(m) / 100 * Math.sign(num); } function getHalfWayPoint(start,end){ let sLatLng = new google.maps.LatLng(start.lat, start.lng); let eLatLng = new google.maps.LatLng(end.lat, end.lng); return google.maps.geometry.spherical.interpolate(sLatLng, eLatLng, 0.5); } function getBoundsPoints(){ let ne = map.getBounds().getNorthEast(); let sw = map.getBounds().getSouthWest(); let nw = new google.maps.LatLng(ne.lat(), sw.lng()); let se = new google.maps.LatLng(sw.lat(), ne.lng()); let midN = google.maps.geometry.spherical.interpolate(nw, ne, 0.5); let midS = google.maps.geometry.spherical.interpolate(sw, se, 0.5); let midW = google.maps.geometry.spherical.interpolate(nw, sw, 0.5); let midE = google.maps.geometry.spherical.interpolate(ne, se, 0.5); let labelAnchor = google.maps.geometry.spherical.interpolate(nw, ne, 0.8); return { ne : ne, sw : sw, nw : nw, se : se, midN : midN, midS : midS, midW : midW, midE : midE, labelAnchor : labelAnchor } } // formatting function constructMarkerLabel(obj, chart){ let isLoop = false; if(obj.type == 'Route'){ // determine if the route is a loop isLoop = obj.isLoop() ? true : false; } let shareURL = ''; let shareURLEnd = ''; let button1text = ((obj.type != 'Route')||(obj.type == 'Route' && isLoop)) ? 'copy' : '1'; // info label let mString = `<center><img src="./img/info.svg"></center> <div class="row"> <div class="col"> <ul class="list-group list-group-flush">`; // name mString += `<li class="list-group-item"><b>${obj.name}</b></li>`; // type mString += `<li class="list-group-item">Type: ${obj.type}</li>`; // level mString += `<li class="list-group-item">Level: ${obj.level}</li>` if(obj.type == 'Route'){ // distance mString += `<li class="list-group-item">ca. ${obj.distance}km`; if(!isLoop){ mString += ` one way (${round(obj.distance * 2)}km total)`; // share url(s) for routes shareURLEnd = `https://www.google.com/maps/search/?api=1&query=${obj.coords[obj.coords.length-1].lat}%2C${obj.coords[obj.coords.length-1].lng}`; } mString += '</li>'; shareURL = `https://www.google.com/maps/search/?api=1&query=${obj.coords[0].lat}%2C${obj.coords[0].lng}`; } else{ // spot share url shareURL =`https://www.google.com/maps/search/?api=1&query=${obj.lat}%2C${obj.lng}` } // surface options if(obj.surfacetype != null){ let conditions = obj.surfacetype.split(','); mString += `<li class="list-group-item">Surface: `; conditions.forEach(c =>{ mString += `<span class="badge bg-info">${c}</span>`; }); mString += `</li>`; } //copy coordinates mString += `<li class="list-group-item">Copy coordinates `; mString += `<input hidden type="text" class="form-control" value=${shareURL} id="share_url" readonly> <button type="button" class="btn btn-primary btn-sm" id="url-button-addon" name="route_start" onclick="copyUrl(this)">${button1text}</button>`; if(obj.type == 'Route' && !isLoop){ // mString += `Start point 2`; mString += `<input hidden type="text" class="form-control" value=${shareURLEnd} id="share_url_end" readonly > <button type="button" class="btn btn-primary btn-sm" id="url-button-addon-end" name="route_end" onclick="copyUrl(this)">2</button>`; } mString += `</li>`; // elevation container if(obj.type == 'Route' && chart != null){ mString+= `<li class="list-group-item"> Elevation Profile <div class="elevation_containers">${chart}</div></li>`; } mString += `</ul>`; mString += `</div></div>`; return mString; } function copyUrl(e){ let urlLbl = null; if(e.name == 'route_start'){ urlLbl = document.getElementById("share_url"); } else{ urlLbl = document.getElementById("share_url_end"); } // Select the text field urlLbl.select(); urlLbl.setSelectionRange(0, 99999); // For mobile devices // Copy the text inside the text field document.execCommand("copy"); // Alert the copied text alert("Copied the text: " + urlLbl.value); } function drawChart(route) { let data = google.visualization.arrayToDataTable(route.elevations); // get highest & lowest elevation for chart scale let highestElevation = null; let lowestElevation = null; for(let i=1; i<route.elevations.length; i++){ let e = route.elevations[i]; if(highestElevation == null || e[1] > highestElevation){ highestElevation = e[1]; } if(lowestElevation == null || e[1] < lowestElevation){ lowestElevation = e[1]; } } // chart options let options = { curveType: 'function', legend: 'none', width:300, height:200, chartArea: {left:10,top:0, bottom:0,'width': '100%', 'height': '80%'}, viewWindowMode:'explicit', viewWindow:{min:lowestElevation-10}, vAxis: { title: 'Elevation', viewWindowMode : 'explicit', textPosition: 'in', viewWindow:{ min: lowestElevation-10, max: highestElevation+10 } }, hAxis: { textPosition: 'none' }, }; let chart = new google.visualization.LineChart(elevationContainer); chart.draw(data, options); }
/* * @Author: Dat Dev * @Date: 2016-04-24 09:13:20 * @Last Modified by: Stefan Wirth * @Last Modified time: 2016-04-24 09:50:06 */ 'use strict'; module.exports = function(websocketServer) { return function(bot, message, next) { if (message.bot_id !== 'B137AQPPY') { return next(); } var text = message.attachments[0] .pretext .replace('<', '') .replace('>', '') .replace('|', ' '); var payload = JSON.stringify({ type: 'github', data: { content: text }, col:'1', row:'1', sizex:'2', sizey:'1' }); websocketServer.clients.forEach(function(client) { client.send(payload); }); next(); } }
(function(){ /** * Module * * Description */ var app = angular.module('app.config', []); app.factory('config', [function(){ return { baseUrl:'http://129.222.72.112:8080/Belbin/rest' //baseUrl:'http://localhost:8080/Belbin/rest' }; }]); })();
Vue.component('mytabbar', { props: ['active'], data: function () { return {} }, template: '<van-tabbar v-model="active">\n' + ' <van-tabbar-item url="index.html" icon="home-o">新闻</van-tabbar-item>\n' + ' <van-tabbar-item url="search.html" icon="search">搜索</van-tabbar-item>\n' + ' <van-tabbar-item url="weather.html" icon="calender-o">天气</van-tabbar-item>\n' + ' <van-tabbar-item url="uesr.html" icon="user-circle-o">我</van-tabbar-item>\n' + ' </van-tabbar>' })
import { actions } from './actions'; export const getSetAvengers = (data) => { return { data, type: actions.SET_AVENGERS } } export const getSetAvengerToFavorite = (item) => { return { item, type: actions.SET_FAVORITES } }
import React from "react"; import propTypes from "prop-types"; import styles from "./index.css"; import { images } from "./images"; import HandleLines from "../SlotsLines/Lines"; import Coin from "../../assets/icons/SlotsIcons/coin2.svg"; import BlueCoin from "../../assets/icons/SlotsIcons/bluecoin2.svg"; import Club from "../../assets/icons/SlotsIcons/club2.svg"; import Spade from "../../assets/icons/SlotsIcons/spade2.svg"; import Heart from "../../assets/icons/SlotsIcons/heart2.svg"; import Octagon from "../../assets/icons/SlotsIcons/octagon2.svg"; import DogJS from "../../assets/icons/SlotsIcons/dog2.svg"; import Quadrilateral from "../../assets/icons/SlotsIcons/quadrilateral2.svg"; import Diamond from "../../assets/icons/SlotsIcons/diamond2.svg"; import Triangle from "../../assets/icons/SlotsIcons/triangle2.svg"; import Pentagon from "../../assets/icons/SlotsIcons/pentagon2.svg"; import Beetle from "../../assets/icons/SlotsIcons/beetle2.svg"; import Esfinge from "../../assets/icons/SlotsIcons/esfinge2.svg"; class SlotsGame extends React.Component { selectNumber = num => { switch (num) { case 0: return BlueCoin; case 1: return Coin; case 2: return Club; case 3: return Spade; case 4: return Quadrilateral; case 5: return Heart; case 6: return Octagon; case 7: return DogJS; case 8: return Diamond; case 9: return Triangle; case 10: return Pentagon; case 11: return Beetle; case 12: return Esfinge; default: break; } }; render() { const { testBol, line, testArray, result, resultFirstColumn, resultSecondColumn, resultThirstColumn, resultFourthColumn, resultFiveColumn, insertIndex, winAmount, multiplier } = this.props; return ( <div className={styles.containerInit}> <div className={styles.rowContainer}> <div className={styles.spinnerContainer}> <div className={styles.lineTest}> {line === true ? ( <HandleLines arrayResult={testArray[0]} insertion1={insertIndex[0]} insertion2={insertIndex[1]} insertion3={insertIndex[2]} insertion4={insertIndex[3]} insertion5={insertIndex[4]} /> ) : null} </div> {testBol[0] || testBol[1] || testBol[2] || testBol[4] || testBol[3] ? ( <div className={styles.backgroundTransparence} /> ) : null} {result ? ( <div className={styles.resultCard}> <div className={styles.columnContainer}> <p className={styles.resultCardText}>{multiplier}x</p> <p className={styles.resultCardText}>{winAmount}</p> </div> </div> ) : null} <div id="columnItem" className={styles.columnSpinner}> {resultFirstColumn.map((num, index) => { return index === insertIndex[0] ? ( <object type="image/svg+xml" data={this.selectNumber(num)} className={styles.icon} > svg-animation </object> ) : ( <img src={images[num]} alt="" className={styles.iconStatic} /> ); })} </div> <div className={styles.separatedLine} /> <div id="columnItem2" className={styles.columnSpinner}> {resultSecondColumn.map((num, index) => { return index === insertIndex[1] ? ( <object type="image/svg+xml" data={this.selectNumber(num)} className={styles.icon} > svg-animation </object> ) : ( <img src={images[num]} alt="" className={styles.iconStatic} /> ); })} </div> <div className={styles.separatedLine} /> <div id="columnItem3" className={styles.columnSpinner}> {resultThirstColumn.map((num, index) => { return index === insertIndex[2] ? ( <object type="image/svg+xml" data={this.selectNumber(num)} className={styles.icon} > svg-animation </object> ) : ( <img src={images[num]} alt="" className={styles.iconStatic} /> ); })} </div> <div className={styles.separatedLine} /> <div id="columnItem4" className={styles.columnSpinner}> {resultFourthColumn.map((num, index) => { return index === insertIndex[3] ? ( <object type="image/svg+xml" data={this.selectNumber(num)} className={styles.icon} > svg-animation </object> ) : ( <img src={images[num]} alt="" className={styles.iconStatic} /> ); })} </div> <div className={styles.separatedLine} /> <div id="columnItem5" className={styles.columnSpinner}> {resultFiveColumn.map((num, index) => { return index === insertIndex[4] ? ( <object type="image/svg+xml" data={this.selectNumber(num)} className={styles.icon} > svg-animation </object> ) : ( <img src={images[num]} alt="" className={styles.iconStatic} /> ); })} </div> </div> </div> </div> ); } } SlotsGame.propTypes = { testBol: propTypes.bool.isRequired, line: propTypes.bool.isRequired, testArray: propTypes.arrayOf(propTypes.number).isRequired, result: propTypes.bool.isRequired, resultFirstColumn: propTypes.arrayOf(propTypes.number).isRequired, resultSecondColumn: propTypes.arrayOf(propTypes.number).isRequired, resultThirstColumn: propTypes.arrayOf(propTypes.number).isRequired, resultFourthColumn: propTypes.arrayOf(propTypes.number).isRequired, resultFiveColumn: propTypes.arrayOf(propTypes.number).isRequired, insertIndex: propTypes.arrayOf(propTypes.number).isRequired, winAmount: propTypes.string.isRequired, multiplier: propTypes.string.isRequired }; export default SlotsGame;
import React, { Component } from 'react'; import { StyleSheet, Text, View, Button } from 'react-native'; export default class App extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; this.baseState = this.state; } // initialState() { // return { // count: 0 // }; // } // state = this.initialState(); changeCount = () => { this.setState(prevState => ({ count: prevState.count + 1 })); }; resetState = () => { this.setState(this.baseState); // this.setState(this.initialState); }; render() { const me = { name: 'Rex', age: 28, interest: ['Programming', 'Workout'], property: { appearance: 'Normal', character: 'Mild' }, func: function() { alert('This is an alert!'); } }; return ( <View style={styles.container}> <Text>Hello world RN!</Text> <Text>Count:{this.state.count}</Text> <Button title="changeCount" onPress={this.changeCount} /> <Button title="resetState" onPress={this.resetState} /> <People {...me} /> </View> ); } } const People = props => { return ( <View> <Text>Name: {props.name}</Text> <Text>Age: {props.age}</Text> <Text>Interest: {props.interest[0]}</Text> <Text>Character: {props.property.character}</Text> <Text onPress={props.func}>Function</Text> </View> ); }; // class People extends Component { // render() { // const { name, age, interest, property, func } = this.props; // return ( // <View> // <Text>Name: {name}</Text> // <Text>Age: {age}</Text> // <Text>Interest: {interest[0]}</Text> // <Text>Character: {property.character}</Text> // <Text onPress={func}>Function</Text> // </View> // ); // } // } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' } });
const Zone = require('../models/zone.model'); module.exports = { async create(req, res) { try { const { body } = req; const zone = await Zone.create(body); res.status(200).json({ message: 'Zone created successfully', zone }); } catch (error) { res.status(400).json({ message: 'Zone could not be created', error }); } }, async list(req, res) { try { const { query } = req; const zones = await Zone.find(query); res.status(200).json({ message: `${zones.length} zones found`, zones }); } catch (error) { res.status(400).json({ message: 'Zones could not be found', error }); } }, async update(req, res) { try { const { body } = req; const zoneID = body.zoneID; const zoneUpdate = await Zone.findByIdAndUpdate(zoneID, body, { new: true, }); res.status(200).json({ message: 'Zone updated', zoneUpdate }); } catch (error) { res.status(400).json({ message: 'Zone could not be updated', error }); } }, async destroy(req, res) { try { const { body } = req; const zoneID = body.zoneID; const zoneDelete = await Zone.findByIdAndDelete(zoneID); res.status(200).json({ message: 'Zone deleted', zoneDelete }); } catch (error) { res.status(400).json({ message: 'Zone could not be deleted', error }); } }, };
/* eslint-disable no-unused-vars */ /** npm packages */ import React, { useEffect, useState } from 'react'; import { bool } from 'prop-types'; import { getFirebaseToken } from '../../helpers/firebase'; // import propTypes from 'prop-types'; /** components */ import HomePageContainerDesktop from './HomePageContainerDesktop'; function HomePageContainer({ isMobile }) { const [firebaseToken, setFirebaseToken] = useState(false); const [notificationData, setNotificationData] = useState({ title: '', body: '', }); const [isDisplayNotif, setIsDisplayNotif] = useState(false); console.log({ firebaseToken, notificationData }); useEffect(() => { getFirebaseToken(getNotificationData); }, []); /** * Get notification data * @param {String} token | Firebase Token * @param {Object} notifData | Notification Payload Data */ function getNotificationData(token, notifData) { setFirebaseToken(token); if (notifData) { setIsDisplayNotif(true); if (notifData.data) { setNotificationData(notifData.data); } } } const props = { firebaseToken, isDisplayNotif, setIsDisplayNotif, notificationData, }; if (isMobile) { return <HomePageContainerDesktop {...props} />; } return <HomePageContainerDesktop {...props} />; } HomePageContainer.propTypes = { isMobile: bool.isRequired, }; export default HomePageContainer;
$('input[name=radiogroup]:radio').click( function() { if ($(this).val() == 'admin') { $('html,body').animate({ scrollTop : $('body').offset().top }, 2000); $('#v-podaci').fadeOut(500); $('#vet-podaci').fadeOut(500); $("#save").fadeIn(400).fadeOut(400).fadeIn(400).fadeOut(400) .fadeIn(400).fadeOut(400).fadeIn(400); } else if ($(this).val() == 'owner') { $('#vet-podaci').fadeOut(); $('#v-podaci').css('opacity', 0).slideDown('slow').animate({ opacity : 1 }, { queue : false, duration : 'slow' }); $('html,body').animate({ scrollTop : $('#v-podaci').offset().top }, 2600); } else if ($(this).val() == 'vet') { $('#v-podaci').fadeOut(); $('#vet-podaci').css('opacity', 0).slideDown('slow').animate({ opacity : 1 }, { queue : false, duration : 'slow' }); $('html,body').animate({ scrollTop : $('#vet-podaci').offset().top }, 2600); } });
function z(n){ function a(n){ return (n === 0) ? 1 : (4 * n - 2) * a(n - 1) / (n + 1); } return a(n)/2; } console.log(z(7));
const DB_URL = 'mongodb://localhost:27017/lazy'; export default DB_URL;
(function () { $('.tenant-change-component a') .click(function (e) { e.preventDefault(); abp.ajax({ url: abp.appPath + 'Account/TenantChangeModal', type: 'POST', dataType: 'html', success: function (content) { $('#TenantChangeModal div.modal-content').html(content); }, error: function (e) { } }); }); })();
import "../css/popup.css";
"use strict"; require([__dirname + "/../low.js", __dirname + "/document.js", __dirname + "/tools.js"], function (low, doc, tools) { /* Sets up a swipe-back touch gesture on the given page. * Invokes the given callback on swiping back. * Provide a null callback to disable swipe-back. */ function setOnSwipe(page, callback) { page .off("touchstart") .off("touchmove") .off("touchend"); if (! callback) { return; } page.on("touchstart", function (ev) { var backIndicator = $( low.tag("div") .style("position", "fixed") .style("top", "0") .style("bottom", "0") .style("left", "8px") .style("font-size", "10vh") .content( low.tag("span").class("sh-fw-icon sh-icon-arrow_back") .style("line-height", "100vh") .style("padding", "0.10em") .style("background-color", "var(--color-primary)") .style("color", "var(--color-primary-background)") ) .html() ); this.swipeContext = { beginX: ev.originalEvent.touches[0].screenX, beginY: ev.originalEvent.touches[0].screenY, status: 0, scrollTop: 0, backIndicator: backIndicator }; }); page.on("touchmove", function (ev) { var dx = ev.originalEvent.touches[0].screenX - this.swipeContext.beginX; var dy = ev.originalEvent.touches[0].screenY - this.swipeContext.beginY; var pos = dx - 16; var fullWidth = $(this).width(); var swipeThreshold = fullWidth * 0.20; switch (this.swipeContext.status) { case 0: // initiated if (pos > 0) { var angle = Math.atan(dy / dx); if (Math.abs(angle) > Math.PI / 4) { this.swipeContext.status = 3; } else { var scrollTop = $(document).scrollTop(); low.pageFreeze(page, scrollTop); var pages = $(".sh-page"); if (pages.length > 1) { var prevPage = $(pages[pages.length - 2]); prevPage.removeClass("sh-hidden"); } this.swipeContext.scrollTop = scrollTop; this.swipeContext.status = 1; } } break; case 1: // swiping page.css("left", Math.max(0, Math.min(fullWidth, pos)) + "px") .css("right", -Math.max(0, Math.min(fullWidth, pos)) + "px"); page.find("> header").css("left", Math.max(0, Math.min(fullWidth, pos)) + "px") .css("right", -Math.max(0, Math.min(fullWidth, pos)) + "px"); if (dx > swipeThreshold) { $("body").append(this.swipeContext.backIndicator); this.swipeContext.status = 2; } break; case 2: // activated page.css("left", Math.max(0, Math.min(fullWidth, pos)) + "px") .css("right", -Math.max(0, Math.min(fullWidth, pos)) + "px"); page.find("> header").css("left", Math.max(0, Math.min(fullWidth, pos)) + "px") .css("right", -Math.max(0, Math.min(fullWidth, pos)) + "px"); if (dx < swipeThreshold) { this.swipeContext.backIndicator.remove(); this.swipeContext.status = 1; } break; case 3: // aborted break; } }); page.on("touchend", function (ev) { function resetPage() { page.css("left", "0").css("right", "0") } function resetHeader() { page.find("> header").css("left", "0").css("right", "0") } function finish() { low.pageUnfreeze(page); if (swipeContext.status === 2) { callback(); } var left = page.css("left"); setTimeout(function () { if (page.css("left") === left) { resetPage(); resetHeader(); } }, 500); } var swipeContext = this.swipeContext; var fullWidth = $(this).width(); this.swipeContext.backIndicator.remove(); if (swipeContext.status === 1) { page.animate({ left: "0", right: "0" }, 300, resetPage); page.find("> header").animate({ left: "0", right: "0" }, 300, resetHeader); } else if (swipeContext.status === 2) { page.animate({ left: fullWidth + "px", right: -fullWidth + "px" }, 300, finish); page.find("> header").animate({ left: fullWidth + "px", right: -fullWidth + "px" }, 300); } }); } /* Element representing a page on the UI page stack. */ exports.Page = function Page() { tools.defineProperties(this, { header: { set: setHeader, get: header }, footer: { set: setFooter, get: footer }, left: { set: setLeft, get: left }, right: { set: setRight, get: right }, script: { set: setScript, get: script }, onSwipeBack: { set: setOnSwipeBack, get: onSwipeBack }, onClosed: { set: setOnClosed, get: onClosed }, width: { get: width }, height: { get: height }, active: { get: active } }); var that = this; var m_header = null; var m_footer = null; var m_left = null; var m_right = null; var m_onSwipeBack = null; var m_onClosed = null; var m_width = 0; var m_height = 0; var m_isActive = false; var m_document = new doc.Document(); m_document.onWindowWidthChanged = function () { that.updateGeometry(); }; m_document.onWindowHeightChanged = function () { that.updateGeometry(); }; var m_page = $( low.tag("div").class("sh-page sh-hidden") .content( low.tag("section") .style("position", "relative") ) .html() ); m_page .on("visible", function () { console.log("page became active"); m_isActive = true; that.activeChanged(); that.updateGeometry(); }) .on("hidden", function () { m_isActive = false; that.activeChanged(); }); function setHeader(header) { if (m_header) { m_header.get().detach(); } m_page.append(header.get()); m_header = header; that.updateGeometry(); } function header() { return m_header; } function setFooter(footer) { if (m_footer) { m_footer.get().detach(); } m_page.append(footer.get()); m_footer = footer; that.updateGeometry(); } function footer() { return m_footer; } function setLeft(left) { if (m_left) { m_left.get().detach(); } m_page.append(left.get()); m_left = left; that.updateGeometry(); } function left() { return m_left; } function setRight(right) { if (m_right) { m_right.get().detach(); } m_page.append(right.get()); m_right = right; that.updateGeometry(); } function right() { return m_right; } function setScript(uri) { m_page.append($( low.tag("script").attr("src", uri) .html() )); } function script() { return ""; } function setOnSwipeBack(callback) { setOnSwipe(m_page, callback); m_onSwipeBack = callback; } function onSwipeBack() { return m_onSwipeBack; } function setOnClosed(callback) { m_onClosed = callback; } function onClosed() { return m_onClosed; } function width() { return m_width; } function height() { return m_height; } function active() { return m_isActive; } this.discard = function () { m_document.discard(); }; this.get = function () { return m_page; }; this.add = function (child) { m_page.find("> section").append(child.get()); that.updateGeometry(); }; this.clear = function () { m_page.find("> section").html(""); that.updateGeometry(); } /* Pushes this page onto the page stack. */ this.push = function (callback) { function cb() { that.updateGeometry(); if (callback) { callback(); } } $("body").append(m_page); that.updateGeometry(); low.pagePush(m_page, cb, $(".sh-page").length === 1); }; /* Pops this page off the page stack. */ this.pop = function (callback) { low.pagePop(function () { m_page.detach(); if (callback) { callback(); } if (m_onClosed) { m_onClosed(); } }); }; /* Updates the page geometry. */ this.updateGeometry = function () { if (! m_isActive) { return; } var headerHeight = m_header ? m_header.get().height() : 0; m_page.find("> section").css("padding-top", headerHeight + "px"); m_page.find("> section").css("padding-bottom", (!! m_footer ? m_footer.get().height() : 0) + "px"); m_page.find("> section").css("padding-left", (!! m_left ? m_left.get().width() : 0) + "px"); m_page.find("> section").css("padding-right", (!! m_right ? m_right.get().width() : 0) + "px"); if (m_left) { m_left.get().css("margin-top", headerHeight + "px"); } if (m_right) { //m_right.get().css("margin-top", headerHeight + "px"); } var newWidth = m_page.find("> section").width(); var newHeight = Math.max(m_page.find("> section").height(), m_document.windowHeight - headerHeight); if (newWidth !== m_width) { m_width = newWidth; that.widthChanged(); } if (newHeight !== m_height) { m_height = newHeight; that.heightChanged(); } } }; });
import decode from './decode.js'; import encode from './encode.js'; export default /* glsl */` // This shader requires the following #DEFINEs: // // PROCESS_FUNC - must be one of reproject, prefilter // DECODE_FUNC - must be one of decodeRGBM, decodeRGBE, decodeGamma or decodeLinear // ENCODE_FUNC - must be one of encodeRGBM, encodeRGBE, encideGamma or encodeLinear // SOURCE_FUNC - must be one of sampleCubemap, sampleEquirect, sampleOctahedral // TARGET_FUNC - must be one of getDirectionCubemap, getDirectionEquirect, getDirectionOctahedral // // When filtering: // NUM_SAMPLES - number of samples // NUM_SAMPLES_SQRT - sqrt of number of samples varying vec2 vUv0; // source #ifdef CUBEMAP_SOURCE uniform samplerCube sourceCube; #else uniform sampler2D sourceTex; #endif #ifdef USE_SAMPLES_TEX // samples uniform sampler2D samplesTex; uniform vec2 samplesTexInverseSize; #endif // params: // x - target cubemap face 0..6 // y - specular power (when prefiltering) // z - source cubemap seam scale (0 to disable) // w - target cubemap size for seam calc (0 to disable) uniform vec4 params; // params2: // x - target image total pixels // y - source cubemap size uniform vec2 params2; float targetFace() { return params.x; } float specularPower() { return params.y; } float sourceCubeSeamScale() { return params.z; } float targetCubeSeamScale() { return params.w; } float targetTotalPixels() { return params2.x; } float sourceTotalPixels() { return params2.y; } float PI = 3.141592653589793; float saturate(float x) { return clamp(x, 0.0, 1.0); } ${decode} ${encode} //-- supported projections vec3 modifySeams(vec3 dir, float scale) { vec3 adir = abs(dir); float M = max(max(adir.x, adir.y), adir.z); return dir / M * vec3( adir.x == M ? 1.0 : scale, adir.y == M ? 1.0 : scale, adir.z == M ? 1.0 : scale ); } vec2 toSpherical(vec3 dir) { return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y)); } vec3 fromSpherical(vec2 uv) { return vec3(cos(uv.y) * sin(uv.x), sin(uv.y), cos(uv.y) * cos(uv.x)); } vec3 getDirectionEquirect() { return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5)); } // octahedral code, based on http://jcgt.org/published/0003/02/01 // "Survey of Efficient Representations for Independent Unit Vectors" by Cigolle, Donow, Evangelakos, Mara, McGuire, Meyer float signNotZero(float k){ return(k >= 0.0) ? 1.0 : -1.0; } vec2 signNotZero(vec2 v) { return vec2(signNotZero(v.x), signNotZero(v.y)); } // Returns a unit vector. Argument o is an octahedral vector packed via octEncode, on the [-1, +1] square vec3 octDecode(vec2 o) { vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y); if (v.y < 0.0) { v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz); } return normalize(v); } vec3 getDirectionOctahedral() { return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0); } // Assumes that v is a unit vector. The result is an octahedral vector on the [-1, +1] square vec2 octEncode(in vec3 v) { float l1norm = abs(v.x) + abs(v.y) + abs(v.z); vec2 result = v.xz * (1.0 / l1norm); if (v.y < 0.0) { result = (1.0 - abs(result.yx)) * signNotZero(result.xy); } return result; } ///////////////////////////////////////////////////////////////////// #ifdef CUBEMAP_SOURCE vec4 sampleCubemap(vec3 dir) { return textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale())); } vec4 sampleCubemap(vec2 sph) { return sampleCubemap(fromSpherical(sph)); } vec4 sampleCubemap(vec3 dir, float mipLevel) { return textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel); } vec4 sampleCubemap(vec2 sph, float mipLevel) { return sampleCubemap(fromSpherical(sph), mipLevel); } #else vec4 sampleEquirect(vec2 sph) { vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5; return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y)); } vec4 sampleEquirect(vec3 dir) { return sampleEquirect(toSpherical(dir)); } vec4 sampleEquirect(vec2 sph, float mipLevel) { vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5; return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel); } vec4 sampleEquirect(vec3 dir, float mipLevel) { return sampleEquirect(toSpherical(dir), mipLevel); } vec4 sampleOctahedral(vec3 dir) { vec2 uv = octEncode(dir) * 0.5 + 0.5; return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y)); } vec4 sampleOctahedral(vec2 sph) { return sampleOctahedral(fromSpherical(sph)); } vec4 sampleOctahedral(vec3 dir, float mipLevel) { vec2 uv = octEncode(dir) * 0.5 + 0.5; return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel); } vec4 sampleOctahedral(vec2 sph, float mipLevel) { return sampleOctahedral(fromSpherical(sph), mipLevel); } #endif vec3 getDirectionCubemap() { vec2 st = vUv0 * 2.0 - 1.0; float face = targetFace(); vec3 vec; if (face == 0.0) { vec = vec3(1, -st.y, -st.x); } else if (face == 1.0) { vec = vec3(-1, -st.y, st.x); } else if (face == 2.0) { vec = vec3(st.x, 1, st.y); } else if (face == 3.0) { vec = vec3(st.x, -1, -st.y); } else if (face == 4.0) { vec = vec3(st.x, -st.y, 1); } else { vec = vec3(-st.x, -st.y, -1); } return normalize(modifySeams(vec, 1.0 / (1.0 - targetCubeSeamScale()))); } mat3 matrixFromVector(vec3 n) { // frisvad float a = 1.0 / (1.0 + n.z); float b = -n.x * n.y * a; vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x); vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y); return mat3(b1, b2, n); } mat3 matrixFromVectorSlow(vec3 n) { vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0); vec3 x = normalize(cross(up, n)); vec3 y = cross(n, x); return mat3(x, y, n); } vec4 reproject() { if (NUM_SAMPLES <= 1) { // single sample return ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC()))); } else { // multi sample vec3 t = TARGET_FUNC(); vec3 tu = dFdx(t); vec3 tv = dFdy(t); vec3 result = vec3(0.0); for (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) { for (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) { result += DECODE_FUNC(SOURCE_FUNC(normalize(t + tu * (u / NUM_SAMPLES_SQRT - 0.5) + tv * (v / NUM_SAMPLES_SQRT - 0.5)))); } } return ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT)); } } vec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0); #ifdef USE_SAMPLES_TEX void unpackSample(int i, out vec3 L, out float mipLevel) { float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x; float v = (floor(u) + 0.5) * samplesTexInverseSize.y; vec4 raw; raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x; raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x; raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x; raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); L.xyz = raw.xyz * 2.0 - 1.0; mipLevel = raw.w * 8.0; } // convolve an environment given pre-generated samples vec4 prefilterSamples() { // construct vector space given target direction mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC()); vec3 L; float mipLevel; vec3 result = vec3(0.0); float totalWeight = 0.0; for (int i = 0; i < NUM_SAMPLES; ++i) { unpackSample(i, L, mipLevel); result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z; totalWeight += L.z; } return ENCODE_FUNC(result / totalWeight); } // unweighted version of prefilterSamples vec4 prefilterSamplesUnweighted() { // construct vector space given target direction mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC()); vec3 L; float mipLevel; vec3 result = vec3(0.0); float totalWeight = 0.0; for (int i = 0; i < NUM_SAMPLES; ++i) { unpackSample(i, L, mipLevel); result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)); } return ENCODE_FUNC(result / float(NUM_SAMPLES)); } #endif void main(void) { gl_FragColor = PROCESS_FUNC(); } `;
//kediter配置 var editor; KindEditor.ready(function(K) { editor = K.create('textarea[name="content"]', { allowFileManager : true, newlineTag:"p" //,designMode:false }); }); function ClearLink(){ var bd=$(window.frames["tsloveme"].document).find("body"); var bdinner=bd.html(); bdinner=bdinner.replace(/(\<a[^\>]+\>)|(\<\/a\>)/igm,""); bd.html(bdinner); /*tds.each(function() { if($(this).html().test(/\<\s*a\s+[^\"|^\']*\>/ig)){ alert(11); } });*/ } function AddLink(str){ var bd=$(window.frames["tsloveme"].document).find("body"); var bdinner=bd.html(); //wap链接: $("#WAPlink").find("tr").each(function() { var a=$(this).find("td").eq(0).html(); var b=$(this).find("td").eq(1).html(); var c=$(this).find("td").eq(2).html(); var reg1=new RegExp("([^\>]*"+a+"[^\<]*)","gm"); switch(str){ case "wap": var reg2='<a href="http://wap.wyn88.com/Hotel/HotelDetails?hotelcode='+b+'">$1</a>'; break; default: var reg2='<a href="http://www.wyn88.com/resv/hotel_'+c+'.html">$1</a>'; } if(reg1.test(bdinner)){ bdinner=bdinner.replace(reg1,reg2) } }); //bdinner=bdinner.replace(/(\<a[^\>]+\>)|(\<\/a\>)/igm,""); bd.html(bdinner); } $(".linkType a").eq(1).click(function(){ ClearLink("wap"); AddLink(); }) $(".linkType a").eq(0).click(function(){ ClearLink("www"); AddLink(); }) }); //对象继承 Object.extend = function(destination,source){ for(var property in source){ destination[property] = source[property] } return destination; }
/* * discontinueParametersService * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. * */ 'use strict'; /** * Manages communication between SinglePluPanel, the PluDirective and the Maintenance UPC component * * @author s753601 * @since 2.13.0 */ (function(){ angular.module('productMaintenanceUiApp').service('imageInfoService', imageInfoService); imageInfoService.$inject = ['$rootScope']; /** * Constructs the singlePluPanelService. * * @param $rootScope The Angular scope representing this application. * @returns */ function imageInfoService($rootScope){ var self = this; self.entityId=null; return{ setEntityId:function (entityId) { self.entityId=entityId; }, getEntityId: function () { return self.entityId; } } } })();
var Foo = (function () { function Foo(value) { this.prop = value; } return Foo; })(); exports.Foo = Foo;
test("regex.js -> validate_email", 3, function () { var input = 'mostafa.safwat.1@gmail.com'; var res = validate_email(input); equal(res.is_valid, true, "mostafa.safwat.1@gmail.com Passed"); input = 'abc'; res = validate_email(input); equal(res.is_valid, false, "abc not Passed"); input = ''; res = validate_email(input); equal(res.is_valid, false, "'' Not Passed"); }); test("regex.js -> validate_num16_hyphen4", 2, function () { var input = '0123456789123456'; var res = validate_num16_hyphen4(input); equal(res.is_valid, true, "0123456789123456 Passed"); input = '0123-4567-8912-3456'; res = validate_num16_hyphen4(input); equal(res.is_valid, true, "0123-4567-8912-3456 Passed"); }); test("regex.js -> validate_age", 5, function () { var input = '30'; var res = validate_age(input); equal(res.is_valid, true, "30 Passed"); input = '30.0'; res = validate_age(input); equal(res.is_valid, true, "30.0 Passed"); input = '30,0'; res = validate_age(input); equal(res.is_valid, true, "30,0 Passed"); input = ''; res = validate_age(input); equal(res.is_valid, true, "'' Passed"); input = '30-0'; res = validate_age(input); equal(res.is_valid, false, "30-0 Not Passed"); });
// Strict Mode On (엄격모드) "use strict"; "use warning"; /** * @author Lazuli */ var HeroLevelUpPopup = new function() { var INSTANCE = this; var listener; var frameCnt = 0; var focus = 0; var state = 0; var levelupAtk = 0; var priceGold = 0; var priceGem = 0; var priceStone = 0; var isApply = false;; var back; var arrow_upgrade; var bar_stone = []; var btn_cancel_off; var btn_cancel_on; var btn_gem_off; var btn_gem_on; var btn_gold_off; var btn_gold_on; var btn_retry_off; var btn_retry_on; var btn_upgrade_off; var btn_upgrade_on; var btn_ok_off; var btn_ok_on; var use_stone; var effect_upgrade; var icon = []; var tag_att; var tag_gem; var tag_normal; var upgrade_fail; var upgrade_success; var wsNumFont; var loading_back; var loadingbar; var star; var slot; /////////////// var heroImg; var heroData; var isFail; var iconStr = ["icon_upgradestone_black", "icon_upgradestone_blue", "icon_upgradestone_red"]; var barStr = ["bar_stonered", "bar_stoneblue", "bar_stoneblack"]; var stoneStr = ["BLACK_STONE", "BLUE_STONE", "RED_STONE"]; INSTANCE.setResource = function(onload) { loadingbar = []; bar_stone = []; icon = []; effect_upgrade = []; var imgParam = [ [back = new Image(), ROOT_IMG + "inventory/upgrade/back" + EXT_PNG], [arrow_upgrade = new Image(), ROOT_IMG + "inventory/upgrade/arrow_upgrade" + EXT_PNG], [btn_cancel_off = new Image(), ROOT_IMG + "inventory/upgrade/btn_cancel_off" + EXT_PNG], [btn_cancel_on = new Image(), ROOT_IMG + "inventory/upgrade/btn_cancel_on" + EXT_PNG], [btn_gem_off = new Image(), ROOT_IMG + "inventory/upgrade/btn_gem_off" + EXT_PNG], [btn_gem_on = new Image(), ROOT_IMG + "inventory/upgrade/btn_gem_on" + EXT_PNG], [btn_gold_off = new Image(), ROOT_IMG + "inventory/upgrade/btn_gold_off" + EXT_PNG], [btn_gold_on = new Image(), ROOT_IMG + "inventory/upgrade/btn_gold_on" + EXT_PNG], [btn_retry_off = new Image(), ROOT_IMG + "inventory/upgrade/btn_retry_off" + EXT_PNG], [btn_retry_on = new Image(), ROOT_IMG + "inventory/upgrade/btn_retry_on" + EXT_PNG], [btn_upgrade_off = new Image(), ROOT_IMG + "inventory/upgrade/btn_upgrade_off" + EXT_PNG], [btn_upgrade_on = new Image(), ROOT_IMG + "inventory/upgrade/btn_upgrade_on" + EXT_PNG], [btn_ok_off = new Image(), ROOT_IMG + "inventory/upgrade/btn_ok_off" + EXT_PNG], [btn_ok_on = new Image(), ROOT_IMG + "inventory/upgrade/btn_ok_on" + EXT_PNG], [use_stone = new Image(), ROOT_IMG + "inventory/upgrade/use_stone" + EXT_PNG], [effect_upgrade = [], HTool.getURLs(ROOT_IMG, "summon/effect_", EXT_PNG, 4)], // [effect_upgrade = new Image(), ROOT_IMG + "inventory/upgrade/effect_upgrade" + EXT_PNG], [tag_att = new Image(), ROOT_IMG + "inventory/upgrade/tag_att" + EXT_PNG], [tag_gem = new Image(), ROOT_IMG + "inventory/upgrade/tag_gem" + EXT_PNG], [tag_normal = new Image(), ROOT_IMG + "inventory/upgrade/tag_normal" + EXT_PNG], [upgrade_fail = new Image(), ROOT_IMG + "inventory/upgrade/upgrade_fail" + EXT_PNG], [upgrade_success = new Image(), ROOT_IMG+ "inventory/upgrade/upgrade_success" + EXT_PNG], [loading_back = new Image(), ROOT_IMG + "inventory/loadingbar_back" + EXT_PNG], [loadingbar = [], HTool.getURLs(ROOT_IMG, "inventory/loadingbar_", EXT_PNG, 2)], [star = new Image(), ROOT_IMG + "etc/star" + EXT_PNG], [slot = new Image(), ROOT_IMG + "inventory/slot" + EXT_PNG] ]; for (var i = 0; i < iconStr.length; i++) { imgParam.push([icon[i] = new Image(), ROOT_IMG + "inventory/upgrade/" + iconStr[i] + EXT_PNG]); } for (var i = 0; i < barStr.length; i++) { imgParam.push([bar_stone[i] = new Image(), ROOT_IMG + "inventory/upgrade/" + barStr[i] + EXT_PNG]); } ResourceMgr.makeImageList(imgParam, function() { imgParam = null; wsNumFont = PlayResManager.getMoneyMap().get("wsNumFont"); onload(); }, function(err) { onload(); appMgr.openDisconnectPopup("HeroLevelUpPopup setResource Fail", this); }); }; INSTANCE.setHeroData = function(_data, _img) { heroData = _data; heroImg = _img; levelupAtk = heroData.getAttack() + Math.floor(heroData.getAttack() * heroData.getAttackInc() / 100); switch (heroData.getExp()) { case 1: priceGold = 5000; priceGem = 10; priceStone = 30; break; case 2: priceGold = 12500; priceGem = 25; priceStone = 90; break; case 3: priceGold = 31250; priceGem = 63; priceStone = 270; break; case 4: priceGold = 78125; priceGem = 156; priceStone = 810; break; case 5: priceGold = 195313; priceGem = 391; priceStone = 2430; break; } }; INSTANCE.clear = function() { back = null; arrow_upgrade = null; bar_stone = null; btn_cancel_off = null; btn_cancel_on = null; btn_gem_off = null; btn_gem_on = null; btn_gold_off = null; btn_gold_on = null; btn_retry_off = null; btn_retry_on = null;; btn_upgrade_off = null; btn_upgrade_on = null; btn_ok_off = null; btn_ok_on = null; use_stone = null; effect_upgrade = null; icon = null; tag_att = null; tag_gem = null; tag_normal = null; upgrade_fail = null; upgrade_success = null; slot = null; wsNumFont = null; loading_back = null; loadingbar = null; star = null; heroData = null; heroImg = null; }; var levelup = function() { if (isApply) return; isApply = true; isFail = false; if (levelupRate(heroData.getExp())) { PopupMgr.openPopup(POPUP.POP_WAITING); NetManager.Req_HeroLevelUp(heroData, 1, "GOLD", priceGold, stoneStr[heroData.getAttr()], priceStone, function(response) { if (NetManager.isSuccess(response)) { QuestManager.questUpdt(4, function() { focus = 0; state = 3; frameCnt = 0; isApply = false; PopupMgr.closePopup(POPUP.POP_WAITING); }); } else { appMgr.openDisconnectPopup("Netmanager Fail", this); } }); } else { PopupMgr.openPopup(POPUP.POP_WAITING); NetManager.Req_HeroLevelUp(heroData, 0, "GOLD", priceGold, stoneStr[heroData.getAttr()], priceStone, function(response) { if (NetManager.isSuccess(response)) { QuestManager.questUpdt(4, function() { focus = 0; state = 3; frameCnt = 0; isApply = false; isFail = true; PopupMgr.closePopup(POPUP.POP_WAITING); }); } else { appMgr.openDisconnectPopup("Netmanager Fail", this); } }); } }; var levelupGem = function() { if (isApply) return; isApply = true; PopupMgr.openPopup(POPUP.POP_WAITING); NetManager.Req_HeroLevelUp(heroData, 1, "GEM", priceGem, stoneStr[heroData.getAttr()], priceStone, function(response) { if (NetManager.isSuccess(response)) { QuestManager.questUpdt(4, function() { focus = 0; state = 4; frameCnt = 0; isApply = false; PopupMgr.closePopup(POPUP.POP_WAITING); }); } else { appMgr.openDisconnectPopup("Netmanager Fail", this); } }); }; var lackCheck = function(_code) { var str; var code = _code; var remainAmount; if (code == "GOLD") { remainAmount = ItemManager.checkPrice(code, priceGold); str = "골드가"; } else if (code == "GEM") { remainAmount = ItemManager.checkPrice(code, priceGem); str = "보석이"; } if (remainAmount < 0) { PopupMgr.openPopup(appMgr.getMessage2BtnPopup(str + " 부족합니다.|충전하러 이동 하시겠습니까?"), function (code, data) { if (data == ("0")) { PopupMgr.closeAllPopup(); appMgr.changeLayer(SCENE.SC_SHOP, false, "shop"); } else { PopupMgr.closePopup(POPUP.POP_MSG_2BTN); } }); return false; } return true; }; var lackCheckStone = function(_code) { var str; var code = _code; var remainAmount; if (code == "RED_STONE") { remainAmount = ItemManager.checkPrice(code, priceStone); str = "레드스톤이"; } else if (code == "BLUE_STONE") { remainAmount = ItemManager.checkPrice(code, priceStone); str = "블루스톤이"; } else if (code == "BLACK_STONE") { remainAmount = ItemManager.checkPrice(code, priceStone); str = "블랙스톤이"; } console.error("remainAmount >> " + remainAmount); if (remainAmount < 0) { PopupMgr.openPopup(appMgr.getMessage0BtnPopup(str + " 부족하여 강화 할수 없습니다."), null, 1500); return false; } return true; }; var levelupRate = function(level) { var rate = Math.floor(Math.random() * 100); switch (level) { case 1: if (rate < 100) return true; break; case 2: if (rate < 40) return true; break; case 3: if (rate < 16) return true; break; case 4: if (rate < 6) return true; break; case 5: if (rate < 3) return true; break; } return false; }; var levelupRender = function(g) { g.drawImage(back, 300, 118); g.drawImage(slot, 415, 215); g.drawImage(heroImg, 423, 222); for (var i = 0; i < heroData.getExp(); i++) { g.drawImage(star, 471 + (i * 18) - (heroData.getExp() * 9), 311); } g.drawImage(tag_att, 425, 353); g.setFont(FONT_22); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, heroData.getAttack(), 525, 372, HTextRender.RIGHT); g.drawImage(arrow_upgrade, 557, 227); g.drawImage(slot, 746, 215); g.drawImage(heroImg, 754, 220); for (var i = 0; i < (heroData.getExp() + 1); i++) { g.drawImage(star, 802 + (i * 18) - ((heroData.getExp() + 1) * 9), 311); } g.drawImage(tag_att, 756, 353); g.setFont(FONT_22); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, levelupAtk, 856, 372, HTextRender.RIGHT); g.drawImage(use_stone, 558, 219); g.drawImage(icon[heroData.getAttr()], 572, 252); g.setFont(FONT_28); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, priceStone, 666, 280, HTextRender.CENTER); g.setFont(FONT_22); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, "히어로를 강화하시겠습니까?", 640, 464, HTextRender.CENTER); g.drawImage(btn_gold_off, 401, 499); g.drawImage(btn_gem_off, 561, 499); g.drawImage(btn_cancel_off, 721, 499); g.setFont(FONT_26); g.setColor(COLOR_YELLOW); switch (focus) { case 0: g.drawImage(btn_gold_on, 401, 499); switch (heroData.getExp()) { case 1: HTextRender.oriRender(g, "강화확률 100%", 638, 356, HTextRender.CENTER); break; case 2: HTextRender.oriRender(g, "강화확률 40%", 638, 356, HTextRender.CENTER); break; case 3: HTextRender.oriRender(g, "강화확률 16%", 638, 356, HTextRender.CENTER); break; case 4: HTextRender.oriRender(g, "강화확률 6%", 638, 356, HTextRender.CENTER); break; case 5: HTextRender.oriRender(g, "강화확률 3%", 638, 356, HTextRender.CENTER); break; } break; case 1: g.drawImage(btn_gem_on, 561, 499); HTextRender.oriRender(g, "강화확률 100%", 638, 356, HTextRender.CENTER); break; case 2: g.drawImage(btn_cancel_on, 721, 499); switch (heroData.getExp()) { case 1: HTextRender.oriRender(g, "강화확률 100%", 638, 356, HTextRender.CENTER); break; case 2: HTextRender.oriRender(g, "강화확률 40%", 638, 356, HTextRender.CENTER); break; case 3: HTextRender.oriRender(g, "강화확률 16%", 638, 356, HTextRender.CENTER); break; case 4: HTextRender.oriRender(g, "강화확률 6%", 638, 356, HTextRender.CENTER); break; case 5: HTextRender.oriRender(g, "강화확률 3%", 638, 356, HTextRender.CENTER); break; } break; } g.drawImage(tag_normal, 434, 551); g.drawImage(tag_gem, 594, 551); g.setFont(FONT_24); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, priceGold, 499, 539, HTextRender.CENTER); HTextRender.oriRender(g, priceGem, 659, 539, HTextRender.CENTER); // for (var i = 0; i < bar_stone.length; i++) { // g.drawImage(bar_stone[i], 443 + (i * 135), 646); // } // g.setFont(FONT_20); // g.setColor(COLOR_WHITE); // HTextRender.oriRender(g, itemMgr.getRedStoneAmount(), 525, 672, HTextRender.CENTER); // HTextRender.oriRender(g, itemMgr.getBlueStoneAmount(), 660, 672, HTextRender.CENTER); // HTextRender.oriRender(g, itemMgr.getBlackStoneAmount(), 794, 672, HTextRender.CENTER); uiDrawMgr.renderMoney(g); }; var levelupSuccess = function(g) { g.save(); g.transform(1, 0.5, -0.5, 1, 640, 285); // g.translate(477, 210); g.rotate(frameCnt * Math.PI / 180); g.drawImage(effect_upgrade[heroData.getGrade()], -Math.floor(effect_upgrade[1].width / 2), -Math.floor(effect_upgrade[1].height / 2)); g.restore(); g.drawImage(upgrade_success, 505, 96); g.drawImage(slot, 581, 226); g.drawImage(heroImg, 589, 233); g.drawImage(tag_att, 591, 364); for (var i = 0; i < heroData.getExp() + 1; i++) { g.drawImage(star, 637 + (i * 18) - ((heroData.getExp() + 1) * 9), 321); } g.setFont(FONT_22); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, levelupAtk, 691, 383, HTextRender.RIGHT); HTextRender.oriRender(g, "강화에 성공하였습니다.", 640, 471, HTextRender.CENTER); g.drawImage(btn_ok_on, 561, 544); }; var levelupFail = function(g) { g.drawImage(upgrade_fail, 505, 96); g.drawImage(slot, 581, 226); g.drawImage(heroImg, 589, 233); g.drawImage(tag_att, 591, 364); for (var i = 0; i < heroData.getExp(); i++) { g.drawImage(star, 637 + (i * 18) - ((heroData.getExp()) * 9), 321); } g.setFont(FONT_22); g.setColor(COLOR_WHITE); HTextRender.oriRender(g, heroData.getAttack(), 691, 383, HTextRender.RIGHT); HTextRender.oriRender(g, "강화에 실패하였습니다.", 640, 455, HTextRender.CENTER); HTextRender.oriRender(g, "다시 도전하시겠습니까?", 640, 487, HTextRender.CENTER); g.drawImage(btn_retry_off, 481, 544); g.drawImage(btn_cancel_off, 641, 544); if (focus == 0) { g.drawImage(btn_retry_on, 481, 544); } else if (focus == 1) { g.drawImage(btn_cancel_on, 641, 544); } }; var levelupLoading = function(g) { g.drawImage(loading_back, 395, 339); g.drawImage(loadingbar[0], 402, 346, frameCnt, 29); }; var levelupEnterKeyAction = function(_focus) { switch (_focus) { case 0: if (lackCheck("GOLD") && lackCheckStone(stoneStr[heroData.getAttr()])) { levelup(); } break; case 1: if (lackCheck("GEM") && lackCheckStone(stoneStr[heroData.getAttr()])) { levelupGem(); } break; case 2: PopupMgr.closePopup(POPUP.POP_HEROLEVELUP); break; } }; var levelupSuccessEnterKeyAction = function(_focus) { if (listener) listener(INSTANCE, focus + ""); }; var levelupFailEnterKeyAction = function(_focus) { switch (_focus) { case 0: state = 0; focus = 0; break; case 1: PopupMgr.closePopup(POPUP.POP_HEROLEVELUP); break; } }; return { toString: function() { return "HeroLevelUpPopup"; }, init: function(onload, callback) { frameCnt = 0; focus = 0; state = 0; isFail = false; isApply = false; listener = callback; onload(); }, start: function() { }, run: function() { if (state == 3) { frameCnt += 45; if (frameCnt >= 450) { frameCnt = 456; if (isFail) { state = 2; appMgr.stopSound(); appMgr.playNetSound(ROOT_SOUND + "upgradeFail" + EXT_SOUND); } else { state = 1; appMgr.stopSound(); appMgr.playNetSound(ROOT_SOUND + "upgradeSuccess" + EXT_SOUND); } } } else if (state == 4) { frameCnt += 45; if (frameCnt >= 450) { frameCnt = 456; state = 1; appMgr.stopSound(); appMgr.playNetSound(ROOT_SOUND + "upgradeSuccess" + EXT_SOUND); } } else { frameCnt++; } UIMgr.repaint(); }, paint: function() { switch (state) { case 0: levelupRender(g); break; case 1: levelupSuccess(g); break; case 2: levelupFail(g); break; case 3: case 4: levelupLoading(g); break; } }, stop: function() { appMgr.loopNetSound(ROOT_SOUND + "title" + EXT_MP3); }, onKeyPressed: function(key) { switch(key) { case KEY_ENTER : switch (state) { case 0: levelupEnterKeyAction(focus); break; case 1: levelupSuccessEnterKeyAction(focus); break; case 2: levelupFailEnterKeyAction(focus); break; } break; case KEY_LEFT: switch (state) { case 0: focus = HTool.getIndex(focus, -1, 3); break; case 1: break; case 2: focus = HTool.getIndex(focus, -1, 2); break; } break; case KEY_RIGHT: switch (state) { case 0: focus = HTool.getIndex(focus, 1, 3); break; case 1: break; case 2: focus = HTool.getIndex(focus, 1, 2); break; } break; case KEY_PREV: case KEY_PC_F4: levelupSuccessEnterKeyAction(focus); // PopupMgr.closePopup(POPUP.POP_HEROLEVELUP); break; } UIMgr.repaint(); }, onKeyReleased: function(key) { switch(key) { case KEY_ENTER : break; } }, getInstance: function() { return INSTANCE; } }; };
const express = require('express'); const path = require('path'); const eApp = express(); eApp.use(express.static(path.join(__dirname, 'public'))); eApp.get('/', (req,res)=>{ res.status(200).sendFile(path.join(__dirname, './views/home.html')); }) eApp.get('/users', (req,res)=>{ res.status(200).sendFile(path.join(__dirname, './views/users.html')); }) eApp.get((req,res)=>{ res.status(404).redirect('/'); }) eApp.listen(3000);
/* signals.js JavaScript API for Signals Requires: Modernizr-2.6.2, sjcl */ !(function (window, navigator, Modernizr, webrtc, jsbn) { // Test the browser first ... function log (line) { console.log(line); } if(!(Modernizr.localstorage && webrtc(window, navigator, log))) { return; // here redirect ... } // LocalStorage and WebRTC supported, let's roll with scope declarations var CURVE = jsbn.ec.curve("secp256r1"); // Private functions first ... function pass() {} function getURIParts(uri) { var m = uri.match(/^(http|https):\/\/([^\/:]+)(:[^\/]+)?(.+)$/); return { protocol: m[1], host: m[2], port: (m[3] || ":80"), path: (m[4] || "/") }; } function getWSParts(uri) { var m = uri.match(/^(ws|wss):\/\/([^\/:]+)(:[^\/]+)?\/sockets\/(.+)$/); return { protocol: m[1], host: m[2], port: (m[3] || ":80"), key: m[4] }; } function localSet(collection, key, string) { return window.localStorage.setItem(["Signals", collection, key].join("/"), string); } function localGet(collection, key) { return window.localStorage.getItem(["Signals", collection, key].join("/")); } function localSetJSON(collection, key, value) { var s = JSON.stringify(value); return localSet(collection, key, s); } function localGetJSON(collection, key) { return JSON.parse(localGet(collection, key)); // in effect ...||"null")) } // Then prototypes ... // Session function Session(key) { this.id = key; var json = localGetJSON("Sessions", key); if (json) { this.privateKeys = json.privateKeys; this.publicKey = json.publicKey; this.sharedSecret = json.sharedSecret; } else { this.privateKeys = jsbn.ec.generate(CURVE); this.publicKey = null; } this.challenge = jsbn.ec.random(CURVE).toString(); } Session.prototype.store = function() { localSetJSON("Sessions", this.id, this); } Session.prototype.identify = function (publicKey) { var x = publicKey[0], y = publicKey[1]; this.publicKey = publicKey; this.sharedSecret = jsbn.ec.computeKey(CURVE, this.privateKeys.v, x, y); this.store(); } Session.prototype.sign = function(challenge) { return jsbn.hmac(this.sharedSecret, challenge); } Session.prototype.verify = function (signature) { return this.sign(this.challenge) == signature; } Session.prototype.isIdentified = function () { return this.publicKey != null; } Session.prototype.authenticate = function (message) { if (this.verify(message.signature)) { return {"signature": this.sign(message.challenge)}; } else { return "unauthorized"; } } function Socket(uri) { uri = getWSParts(uri); this.session = new Session(uri.key); this.baseURI = uri.protocol + "://" + uri.host + uri.port + "/sockets/"; this.ws = null; } Socket.prototype.toString = function() { return this.baseURI; } Socket.prototype.log = function(line) { log(this.toString() + " " + line) } Socket.prototype.connect = function(signaling) { var ws, self=this; function socket_open() { self.ws = ws; if (self.session.isIdentified()) { ws.send(JSON.stringify({ "challenge": self.session.challenge })); ws.onmessage = socket_authenticate; } else { var P = self.session.privateKeys; ws.send(JSON.stringify({ "publicKey": [P.x, P.y] })); ws.onmessage = socket_identify; } } function socket_exception(e) { self.log(e); ws.onmessage = pass; ws.close(); } function socket_identify(evt) { try { signaling.onConnect(self); self.session.identify(JSON.parse(evt.data).publicKey); ws.onmessage = socket_authorized; signaling.onReady(self); } catch (e) { socket_exception(e) } } function socket_authenticate(evt) { try { signaling.onConnect(self); var req = JSON.parse(evt.data), res = self.session.authenticate(req); if (res == "unauthorized") { signaling.onUnauthorized(self); ws.onmessage = pass; ws.close(); } else { ws.send(JSON.stringify(res)); ws.onmessage = socket_authorized; signaling.onReady(self); } } catch (e) { socket_exception(e); } } function socket_authorized(evt) { try { var message = JSON.parse(evt.data); } catch (e) { message = {"error": e.toString()}; } try { signaling.onSignal(self, message); } catch (e) { socket_exception(e); } } function socket_reconnect() { socket_close(); self.connect(); } function socket_close() { signaling.onDisconnect(self); signaling = self.ws = ws = null; } ws = new WebSocket(this.baseURI+this.session.id); ws.onclose = socket_close; ws.onopen = socket_open; return this; } Socket.prototype.isConnected = function() { return this.ws !== null; } // function Address(name) { this.name = name; this.sessions = []; this.calls = []; } function PeerConnection(address, session) { this.address = address; this.session = session; } PeerConnection.prototype.onOffer = function (signal) {} PeerConnection.prototype.onAnswer = function (signal) {} PeerConnection.prototype.onConnect = function () {} PeerConnection.prototype.onPlay = function () {} PeerConnection.prototype.onHold = function () {} PeerConnection.prototype.onDisconnect = function () {} // Signals function Signals() { var keys = localGetJSON("Collections", "Sessions") || [], sessions = this.sessions = {}; keys.map(function(key){ sessions[key] = true; }); this.sockets = localGetJSON("Collections", "Sockets") || {}; this.installation = localGet("Signals", "installation"); this.localStream = null; this.calls = {}; } Signals.prototype.openSession = function(key) { var session; if (this.sessions[key]) { session = new Session(key); } else { session = new Session(key); session.store(); localSetJSON("Collections", "Sessions", Object.keys(this.sessions)); } return session; } Signals.prototype.openSocket = function(uri) { var socket = new Socket(uri); if (!this.sockets[socket.baseURI]) { this.sockets[socket.baseURI] = uri; localSetJSON("Signals", "sockets", this.sockets); } return socket.connect(this); } Signals.prototype.onError = function(socket, error) { socket.log(error); // alert the user. } Signals.prototype.onDisconnect = function(socket) { socket.log("disconnected"); // alert the user, reconnect. } Signals.prototype.onConnect = function(socket) { socket.log("connected"); // alert the user. } Signals.prototype.onReady = function(socket) { socket.log("ready"); // alert the user. } Signals.prototype.onSignal = function(socket, message) { socket.log(JSON.stringify(message)); // dispatch offers and answers. } Signals.prototype.call = function(address, session) { var call = this.calls[address] = new PeerConnection(address, session); return call; } function signals_install(key) { var session = new Session(key), uriParts = getURIParts(window.document.baseURI), sockets = {}; localSet("Signals","installation", key); localSetJSON("Collections", "Sessions", [key]); session.store(); sockets[uriParts.host+uriParts.port] = key; localSetJSON("Signals", "sockets", sockets); return session; } function signals_open(key) { // the main entry point var session, s = new Signals(); if (s.installation == null) { session = signals_install(key); s.installation = key; } else { session = s.sessions[s.installation]; } // session.connect(); return s; } function signals_clean() { var key = localGet("Signals","installation"); localStorage.removeItem("Signals/Collections/Sessions"); localStorage.removeItem("Signals/Signals/Sockets"); localStorage.removeItem("Signals/Signals/installation"); localStorage.removeItem("Signals/Sessions/" + key); // localStorage.removeItem("Signals/Sockets/" + key); } function signals_post(path, name, from, message) { var xhr = new XMLHttpRequest(), json = JSON.stringify(message), uri = path+"/"+name+"/"+from; xhr.open("POST", uri, true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.send(json); xhr.onreadystatechange = function(evt) { if(xhr.readyState==4) { (log||onresponse)(xhr.status); } }; // console.log("POST "+uri+" "+ json.length.toString() + " chars"); console.log(json); } // tests window.signals = { version: "0.0.1", open: signals_open, clean: signals_clean, post: signals_post }; })(window, navigator, Modernizr, webrtc, jsbn);
function enemyHit(enemy,bullet){ for(var i=0; i<explosionDensity; i++) { var p = createSprite(bullet.position.x, bullet.position.y,4,4); p.setSpeed(random(3,5), random(360)); p.friction = 0.95; p.life = 15; } var loudness = 1 enemyHitSound.amp(loudness); enemyHitSound.play(); enemy.remove(); bullet.remove(); score++; if (score == 30){ gameState = 'countDown1'; levelOneSong.stop(); levelTwoSong.loop(); } if (score == 50){ gameState = 'countDown2'; levelTwoSong.stop() levelThreeSong.loop() } if (score > 90 ) { gameState = 'win'; levelThreeSong.stop(); winSong.loop(); } } function heroHit(enemy,hero){ heroHealth--; heroHitSound.play(); if(heroHealth <= 0){ gameState = 'lose'; loseSong.loop(); levelOneSong.stop(); levelTwoSong.stop(); levelThreeSong.stop(); } enemy.remove(); hero.shapeColor=('red'); }
var express = require('express'); var fs = require('fs'); var app = express(); // -req(request) es la peticion al servidor // -res(response) es la respuesta que entrega el servidor // -next le dice a node que cuando se ejecute siga ocn la siguiente instruccion // =========================================================== // GET IMAGEN MEDICO // =========================================================== app.get('/:tipo/:img', (req, res, next) => { // tiene 3 parametros; 1) el request y 2) el parametro y 3) el callback(es una funcion) var tipo = req.params.tipo; var img = req.params.img; var path = `./uploads/${ tipo }/${ img }`; // variable para verificar si la imagen existe y asi poder colocar una por defecto si no fs.exists( path, existe => { // recibe un path y un callback booleano (existe) if( !existe ) { path = './assets/no-img.jpg'; } res.sendfile( path ); }); } ); module.exports = app;
(function (ko, $p, toastr) { ko.components.register('add-organiser', { viewModel: function (params) { var organiserService = new $p.OrganiserService(params.eventId); var me = this; me.email = ko.observable(); me.submit = function (model, event) { if (!$p.checkValidity(me)) { return; } var $btn = $(event.target); $btn.loadBtn(); organiserService.addOrganiser(me.email()) .success(function (r) { if (r.errors) { return; } me.email(null); if (params.onSuccess) { params.onSuccess(r); } }); } me.cancel = function () { me.email(null); if (params.onCancel) { params.onCancel(); } } me.validator = ko.validatedObservable({ email: me.email.extend({ required: true, email: true, maxLength: 100, mustNotEqual: { params: params.ownerEmail, message: 'This email is already the owner' } }) }); }, template: { path: $p.baseUrl + 'Scripts/app/events/organisers/add-organiser.html' } }); })(ko, $paramount, toastr);
import React, { PureComponent } from "react"; import Link from "gatsby-link"; import cx from "classnames"; import "../layouts/css/fcss.css"; import "../layouts/css/page.css"; import { connect } from "react-redux"; class FormInput extends PureComponent { constructor(props) { super(props); } render() { const inputClass = cx({ 'input-wrap': true, 'input-wrap--error': this.props.hasError }) return ( <div className={inputClass}> <div className="input-label t-sans t-upper f-11 ls-1"> <span>{this.props.labelTitle}</span> </div> <input onChange={(e) => this.props.setFieldValue(e.target.value) } type={this.props.type} /> </div> ); } } export default FormInput;
import React, { Component } from 'react' import { connect } from 'react-redux' import { changeFilter } from '../actions/search' import { Modal, Header, Body, Footer } from 'bypass/ui/modal' import { ColumnLayout, Layout } from 'bypass/ui/layout' import { Button } from 'bypass/ui/button' import { DateInput } from 'bypass/ui/input' import { Text } from 'bypass/ui/text' class Period extends Component { static defaultProps: { value: { from: {}, to: {}, } } onChangeFrom = from => { const { value, onChange } = this.props onChange({ ...value, from }) } onChangeTo = to => { const { value, onChange } = this.props onChange({ ...value, to }) } render() { const { value, onClose } = this.props return ( <Modal onClose={onClose}> <Header> <Text size={19}> {__i18n('SEARCH.ASIDE.PERIOD')} </Text> </Header> <Body alignCenter> <ColumnLayout justify='center' align='center'> <Layout> <DateInput value={value.from} onChange={this.onChangeFrom} /> </Layout> <Layout basis='8px' /> <Layout> &minus; </Layout> <Layout basis='8px' /> <Layout> <DateInput value={value.to} onChange={this.onChangeTo} /> </Layout> </ColumnLayout> </Body> <Footer alignCenter> <Button onClick={onClose}> {__i18n('LANG.BUTTONS.SAVE')} </Button> </Footer> </Modal> ) } } export default connect( state => ({ value: state.cards.search.getIn(['search', 'dates']).toJS(), }), dispatch => ({ onChange: value => { dispatch(changeFilter('dates', value)) }, }) )(Period)
var randomHex = function (len) { var maxlen = 8, min = Math.pow(16, Math.min(len, maxlen) - 1), max = Math.pow(16, Math.min(len, maxlen)) - 1, n = Math.floor(Math.random() * (max-min+1)) + min, r = n.toString() while (r.length < len) { r = r + randomHex(len - maxlen) } return r } for (let i = 1; i < 50; i++) { console.log(randomHex(24)); }
/** * Created by Administrator on 2016/12/28. */ /* 定义类 */ var TYPE_FIELD = 0; var TYPE_NUMBER = 1; var TYPE_LINE_DIVIDER = 2; var TYPE_CURLY_L = 3; var TYPE_CURLY_R = 4; var TYPE_BRACKET_L = 6; var TYPE_BRACKET_R = 7; var TYPE_OPERATOR = 8; var TYPE_SENTENCES = 11; var TYPE_SENTENCE = 12; var TYPE_EXPRESSION = 13; var TYPE_DEFINITION = 14; var OPERATOR_L_EVALUATE = 0; var OPERATOR_L_PRINT = 1; var OPERATOR_D_ASSIGNMENT = 2; var OPERATOR_D_PLUS = 3; // 这里提供利用类似于KMP的算法优化命令解析的可能性 但我先不implement. var CONDITION_STATUS_VALID = 0; var CONDITION_STATUS_INCREASE_EXACT_NUMBER = 1; var CONDITION_STATUS_SHIFT_EXACT_NUMBER = 2; var Condition_Status = function(code, number) { this.code = code; this.number = number; }; var Token = function(type) { this.type = type; }; var Rule = function (condition, operation) { this.condition = condition; this.operation = operation; }; var Interpreter = function (scope) { this.scope = scope; this.rules = []; this.add_rule = function(condition, operation) { var rule = new Rule(condition, operation); this.rules.push(rule); return rule; }; this.interpret_forever = function(token_list) { var old_token_list = token_list; while (true) { var new_token_list = this.interpret_once(old_token_list); if (new_token_list) { old_token_list = new_token_list; } else { return old_token_list; } } }; this.interpret_once = function(token_list) { for (var i = this.rules.length - 1; i >= 0; i--) { var rule = this.rules[i]; var st = 0; var ed = 1; while (ed <= token_list.length) { var son_list = token_list.slice(st, ed); var status = rule.condition(son_list); /* if (i == 0) { console.log("Result: ", son_list, status); } */ if (status.code == CONDITION_STATUS_VALID) { var prefix = token_list.slice(0, st); var midfix = rule.operation(son_list); var suffix = token_list.slice(ed, token_list.length); var new_token_list = prefix.concat(midfix).concat(suffix); /* console.log("Success: ", i); console.log("Old_tot: ", token_list); console.log("Old_son: ", son_list); console.log("New_son: ", midfix); console.log("New_tot: ", new_token_list); */ return new_token_list; } if (status.code == CONDITION_STATUS_INCREASE_EXACT_NUMBER) { ed = ed + status.number; } if (status.code == CONDITION_STATUS_SHIFT_EXACT_NUMBER) { st = st + status.number; ed = st + 1; } } } return false; }; }; var Translator = function (scope) { this.scope = scope; this.break = function(str) { return str.split(" "); }; this.simple_translate = function(string_list) { var token_list = []; for (i in string_list) { var string = string_list[i]; var token; if (isNaN(string)) { if (this.scope.field_table[string]) { token = this.scope.field_table[string]; } else { token = new Token(TYPE_FIELD); token.name = string; token.evaluator = function () { return 0; }; this.scope.field_table[string] = token; } } else { token = new Token(TYPE_FIELD); token.evaluator = function() { var number = parseInt(string); return function(){ return number; } }(); } token_list.push(token); } return token_list; }; }; var Scope = function (parent_scope) { this.parent_scope = parent_scope; this.field_table = {}; this.interpreter = new Interpreter(this); this.translator = new Translator(this); }; /* token_list_type_check 并不是所有的Rule都需要这个东西 如果你想的话Rule的condition可以有很多or起来 然后在Rule里面给不同情况对应不同operation 能手动更好的优化 然而这样用这么多条Rule还有他妈什么意义 我本来就是为了图方便 还有 这里可以用KMP优化但是我懒得写 :p */ var token_list_type_check = function(token_list, type_list) { if (token_list[0].type != type_list[0]) { return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); } if (token_list.length < type_list.length) { return new Condition_Status(CONDITION_STATUS_INCREASE_EXACT_NUMBER, type_list.length - token_list.length); } for (var i in token_list) { if (token_list[i].type != type_list[i]) { return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); } } return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); }; var root_scope_init = function(scope) { var interpreter = scope.interpreter; // Print interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_OPERATOR, TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[0].operator == OPERATOR_L_PRINT) { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { console.log(token_list[1].evaluator()); return [token_list[1]]; }); /* // Assignment interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD, TYPE_OPERATOR, TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[1].operator == OPERATOR_D_ASSIGNMENT) { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { interpreter.add_rule(function(son_token_list) { var check = token_list_type_check(son_token_list, [TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (son_token_list[0].name == token_list[0].name) { return new Condition_Status(CONDITION_STATUS_VALID, son_token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function (son_token_list) { var new_token = new Token(TYPE_FIELD); new_token.evaluator = token_list[2].evaluator; return [new_token]; }); return [token_list[0]]; }); */ // Assignment interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD, TYPE_OPERATOR, TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[1].operator == OPERATOR_D_ASSIGNMENT) { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { token_list[0].evaluator = token_list[2].evaluator; return [token_list[0]]; }); // Plus interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD, TYPE_OPERATOR, TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[1].operator == OPERATOR_D_PLUS) { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { var new_token = new Token(TYPE_FIELD); new_token.evaluator = function() { return token_list[0].evaluator() + token_list[2].evaluator(); }; return [new_token]; }); // Evaluate interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_OPERATOR, TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[0].operator == OPERATOR_L_EVALUATE) { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { var new_token = new Token(TYPE_FIELD); var value = token_list[1].evaluator(); new_token.evaluator = function() { var value_in = value; return function() { return value_in; } }(); return [new_token]; }); // Assignment String interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[0].name == "BUILTIN_ASSIGNMENT") { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { var new_token = new Token(TYPE_OPERATOR); new_token.operator = OPERATOR_D_ASSIGNMENT; return [new_token]; }); // Assignment Evaluate interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[0].name == "BUILTIN_EVALUATE") { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { var new_token = new Token(TYPE_OPERATOR); new_token.operator = OPERATOR_L_EVALUATE; return [new_token]; }); // Assignment Plus interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[0].name == "BUILTIN_PLUS") { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { var new_token = new Token(TYPE_OPERATOR); new_token.operator = OPERATOR_D_PLUS; return [new_token]; }); // Assignment Print interpreter.add_rule(function(token_list) { var check = token_list_type_check(token_list, [TYPE_FIELD]); if (check.code != CONDITION_STATUS_VALID) { return check; } if (token_list[0].name == "BUILTIN_PRINT") { return new Condition_Status(CONDITION_STATUS_VALID, token_list.length); } return new Condition_Status(CONDITION_STATUS_SHIFT_EXACT_NUMBER, 1); }, function(token_list) { var new_token = new Token(TYPE_OPERATOR); new_token.operator = OPERATOR_L_PRINT; return [new_token]; }); }; var scope = new Scope(undefined); root_scope_init(scope); // var text = "BUILTIN_PRINT a BUILTIN_ASSIGNMENT 5"; var test = function(text) { scope.interpreter.interpret_forever(scope.translator.simple_translate(scope.translator.break(text))); }; test("b BUILTIN_ASSIGNMENT 10"); // b = 10 test("c BUILTIN_ASSIGNMENT 20"); // c = 20 test("a BUILTIN_ASSIGNMENT b BUILTIN_PLUS c"); // a = b + c test("BUILTIN_PRINT a"); // print(a) expected: 30 test("b BUILTIN_ASSIGNMENT 30"); // b = 30 test("c BUILTIN_ASSIGNMENT 40"); // c = 40 test("BUILTIN_PRINT a"); // print(a) expected: 70 test("b BUILTIN_ASSIGNMENT 50"); // b = 50 test("c BUILTIN_ASSIGNMENT 60"); // b = 60 test("a BUILTIN_ASSIGNMENT BUILTIN_EVALUATE b BUILTIN_PLUS BUILTIN_EVALUATE c"); // a = @b + @c test("BUILTIN_PRINT a"); // print(a) expected: 110 test("b BUILTIN_ASSIGNMENT 70"); // b = 70 test("c BUILTIN_ASSIGNMENT 80"); // c = 80 test("BUILTIN_PRINT a"); // print(a) expected: 110
declare export default string
describe('E2E tests', () => { var fixtures; var fixture; var obj; var config; var editorName = 'panel-fixture'; beforeAll(() => { fixtures = $('<div id="#fixtures"></div>').appendTo('body'); }); beforeEach(() => { obj = grapesjs; config = { container: '#' + editorName, storageManager: { autoload: 0, type: 'none' } }; fixture = $('<div id="' + editorName + '"></div>'); fixture.empty().appendTo(fixtures); }); afterEach(() => { obj = null; config = null; fixture.remove(); }); afterAll(() => { //fixture.remove(); }); test('Command is correctly executed on button click', () => { var commandId = 'command-test'; config.commands = { defaults: [ { id: commandId, run(ed, caller) { ed.testValue = 'testValue'; caller.set('active', false); } } ] }; config.panels = { defaults: [ { id: 'toolbar-test', buttons: [ { id: 'button-test', className: 'fa fa-smile-o', command: commandId } ] } ] }; var editor = obj.init(config); editor.testValue = ''; var button = editor.Panels.getButton('toolbar-test', 'button-test'); button.set('active', 1); expect(editor.testValue).toEqual('testValue'); expect(button.get('active')).toEqual(false); }); });
'use strict'; const Module = require('../../utils/Module'); const DiscordRPC = require('discord-rpc'); class Discord extends Module { constructor(BetterTwitchApp) { super('discord'); this.BetterTwitchApp = BetterTwitchApp; this.RPC = new DiscordRPC.Client({ transport: 'ipc' }); this.__clientId = '483350908684599296'; this.__last_channel = null; this.init(); } render() { if(this.ready) { const TwitchPlayer = this.BetterTwitchApp.Twitch.getVideoPlayer(); const TwitchChat = this.BetterTwitchApp.Twitch.getChatController(); if((TwitchPlayer !== null && TwitchPlayer.getPlaybackState().match('playing')) && TwitchPlayer.isLive()) { let channel = TwitchPlayer.getChannelName(); let chatName = channel; if(TwitchChat != null) chatName = TwitchChat.props.channelDisplayName; let isHost = !(TwitchChat.props.channelLogin.toLowerCase() === channel.toLowerCase()); let status = 'Watching: '+ channel; if(channel && this.__last_channel !== TwitchPlayer.getChannelName()) { let twitchUrl = `twitch.tv/${((channel.length > 14)?(channel.substr(11)+'...'):channel)}`; let activity = { details: ((isHost)?status:undefined), state: ((isHost)?`Hosted by ${chatName}`:status), startTimestamp: new Date(), largeImageKey: channel, largeImageText: twitchUrl, smallImageKey: 'icon', smallImageText: 'BetterTwitchApp' }; this.setActivity(activity); this.__last_channel = channel; } } else this.RPC.clearActivity().then(() => { this.__last_channel = null; }); } } setActivity(activity) { if(this.ready) this.RPC.setActivity(activity).then((data) => { if(!data.assets['large_image']) { activity.largeImageKey = 'default'; this.setActivity(activity); } }); } init() { if(this.__renderer) return; DiscordRPC.register(this.__clientId); this.RPC.on('ready', () => { this.ready = true; }); this.__renderer = setInterval(() => { this.render(); }, 5000); this.RPC.login({ clientId: this.__clientId }); } } module.exports = Discord;
/** * Created by Administrator on 2016/12/28. */ var Component = require("../component"); var init= function(order_move) { order_move.on_start = function () { order_move.started = true; var mover = order_move.character.get_component(Component.MOVER); mover.moving_aim = order_move.primary_aim; }; // It false, the order will be terminated. order_move.on_update = function (delta_time) { if (!order_move.started) { order_move.on_start(); } var mover = order_move.character.get_component(Component.MOVER); if (mover.moving_aim == order_move.primary_aim) { return true; } else { return false; } }; }; module.exports = { init:init };
export const ADD_ITEM = 'ADD_ITEM'; export const REMOVE_ITEM = 'REMOVE_ITEM'; export const GET_CART_LENGTH = 'GET_CART_LENGTH'; export const addItem = (id) => { return { type: ADD_ITEM, id } } export const removeItem = (obj) => { return { type: REMOVE_ITEM, obj } } export const getCartLength = () => { return { type: GET_CART_LENGTH } }
import React from 'react'; class WelcomeMessage extends React.Component { constructor(props) { super(props); this.state = { name: "Nandha"}; this.refreshMessage(); } refreshMessage() { let date = new Date(); if (date.getHours() < 12){ this.setState({greeting: "Good Morning, "}) } else if (date.getHours() < 18){ this.setState({greeting: "Good Afternoon, "}) } else { this.setState({greeting: "Good Evening, "}) } } render() { return ( <div className="title"> <h1>{this.state.greeting}{this.state.name}</h1> </div> ); } componentDidMount() { this.refreshMessage() this.message = setInterval(() =>{ this.refreshMessage() }, 100000) } componentWillUnmount() { clearInterval(this.message) } } export default WelcomeMessage;
import * as types from '../actions/actionTypes'; import initialState from './initialState'; export default function courseReducer(state = initialState.courses,action){ switch(action.type) { case types.LOAD_COURSES_SUCCESS: // state.push(action.course); // return state; // state is immutaable so we cant use above code return action.courses; default: return state; } }
//SERVER ROUTES export const USER_SERVER = 'https://vast-cliffs-99081.herokuapp.com/api/users'; //export const USER_SERVER = 'http://localhost:5000/api/users'; export const INSURANCE_SERVER = 'https://stark-island-15004.herokuapp.com/api/insurance'; //export const INSURANCE_SERVER = 'http://localhost:5000/api/insurance';
// insertion sort function insertion_sort(lst){ l = lst.length; var temp,i,j; for(i=0;i<l-1;i++){ for(j=i+1;j>0;j--){ if (lst[j] >= lst[j-1]) break; else{ temp = lst[j-1]; lst[j-1] = lst[j]; lst[j] = temp; } } } return lst; } var myArray = [3, 2, 4, 5, 1]; console.log(insertion_sort(myArray));
import Immutable from "immutable"; import loadProductListInit from "./load-product-list-init"; let routing = {}; const productListInit = loadProductListInit(); export default Immutable.fromJS({ productListInit, routing });
// require dependencies var express = require('express'); var path = require('path'); var root = __dirname; var port = process.env.PORT || 8000; var app = express(); // get files from client, Skeleton-2.0.4, and bower_components app.use(express.static(path.join(root, './client'))); app.use(express.static(path.join(root, './client/Skeleton-2.0.4'))); app.use(express.static(path.join(root, './bower_components'))); app.listen(port, function () { console.log('running'); })
const express = require("express"); const authController = require("../controllers/authController"); const cartController = require("../controllers/cartController"); const router = express.Router(); router.get("/", authController.protect, cartController.getCart); router.route("/:id").delete(authController.protect, cartController.deleteCart); router.post("/add-to-cart", authController.protect, cartController.addToCart); router.post( "/subtract", authController.protect, cartController.subtractQuantityFromCart ); // // router // // .route("/") // // // .get(authController.protect, cartController.getCart) // // .post( // // authController.protect, // // // cartController.setTourUserIds, // // cartController.addToCart // // ); // router.route("/").post(authController.protect, cartController.addToCart); // // router.route("/:id").get(cartController.getCart); module.exports = router;
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, Dimensions, TouchableOpacity, } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import Month from '../constants/month'; import SubBlock from './SubBlock'; import WeatherInfo from './WeatherInfo'; import styles from '../styles/MainStyle'; const { width } = Dimensions.get('window'); const weatherIcon = (data, month) => { const { af, rain } = data[month]; af.replace(/[^\d.]/g, ''); rain.replace(/[^\d.]/g, ''); let name; if (Boolean(af) > 14) name = 'md-snow'; else if (rain > 100) name = 'ios-rainy'; else name = 'ios-sunny'; return <Ionicons name={name} size={width * 0.25} color="#db9864" />; }; const renderWeatherInfo = (data, weather, month) => ( <View style={styles.Main}> <View style={styles.MainBlock}> <View style={styles.MainBlockHeader}> {weatherIcon(data, month)} <View style={styles.MainBlockHeaderTitleContainer}> <Text style={styles.MainBlockHeaderTitle}> {weather.yyyy} </Text> <Text style={styles.MainBlockHeaderTitle}>{Month[month]}</Text> </View> </View> <WeatherInfo index={1} title="MAXIMUM TEMPERATURE:" text={weather.tmax} /> <WeatherInfo index={1} title="MINIMUM TEMPERATURE:" text={weather.tmin} /> </View> <SubBlock index={1} iconName="ios-sunny" title="Sunny hours" text={weather.sun.replace(/[^\d.]/g, '')} /> <SubBlock index={2} iconName="ios-rainy" title="Precipitation level" text={weather.rain.replace(/[^\d.]/g, '')} /> <SubBlock index={3} iconName="md-snow" title="Frosty days" text={weather.af.replace(/[^\d.]/g, '')} /> </View> ); const WeatherCard = ({ data, month, setMonth, }) => { const weather = data[month]; return weather ? renderWeatherInfo(data, weather, month) : ( <View style={styles.NoMonth}> <Text style={styles.NoMonthTitle} > {'There are no data for this month\nselect a month'} </Text> <View style={styles.NoMonthItem}> {Object.keys(data).map(item => ( <TouchableOpacity key={item} onPress={() => setMonth(item - 1)}> <Text style={styles.NoMonthItemText} > {item} </Text> </TouchableOpacity> ))} </View> </View> ); }; WeatherCard.propTypes = { data: PropTypes.objectOf( PropTypes.shape({ af: PropTypes.string, rain: PropTypes.string, yyyy: PropTypes.string, tmax: PropTypes.string, tmin: PropTypes.string, sun: PropTypes.string, }), ).isRequired, setMonth: PropTypes.func.isRequired, month: PropTypes.arrayOf(PropTypes.string), }; WeatherCard.defaultProps = { month: null, }; export default WeatherCard;
require('../styles/friendbot-widget.scss'); import {Inject} from "interstellar-core"; @Inject("$scope", "interstellar-core.Config", "interstellar-sessions.Sessions", "interstellar-network.Server") class FriendbotWidgetController { constructor($scope, Config, Sessions, Server) { if (!Sessions.hasDefault()) { console.error('Active session is required by this widget.'); return; } this.$scope = $scope; this.Config = Config; this.Server = Server; this.session = Sessions.default; } friendbot() { this.Server.friendbot(this.session.getAddress(), { amount: this.Config.get('modules.<%= name %>.amount') }).then(() => { this.$scope.$apply(); }) } } module.exports = function(mod) { mod.controller("FriendbotWidgetController", FriendbotWidgetController); };
import React, { useEffect, useState } from 'react'; import { useParams } from 'react-router-dom'; import ReactStars from 'react-stars'; import { getByIdBook } from '../service/api'; import notFavoritedIcon from '../assets/icons/notFavoritedIcon.png'; import favoritedIcon from '../assets/icons/FavoritedIcon.png'; // import BooksContext from '../context/BooksContext'; const DetailsBook = () => { const [data, setData] = useState([]); const [isFavorite, setIsFavorite] = useState(false); const [rating, setRating] = useState(''); const [loading, setLoading] = useState(true); const { bookId } = useParams(); useEffect(() => { (async () => { try { const response = await getByIdBook(bookId); console.log(Object.keys(response)); setData(response); setLoading(false); } catch (err) { console.error('Algo deu errado', err); } })(); }, []); const ratingChanged = (newRating) => { setRating(newRating); }; const handleFavorite = (event) => { event.preventDefault(); setIsFavorite(!isFavorite); }; if (loading) return <p>Loading...</p>; return ( <section className="container-detail"> <div className="container-main"> <div className="content-main"> <img src={data.volumeInfo.imageLinks.thumbnail} alt={data.volumeInfo.title} /> <span>{data.volumeInfo.pageCount} pages</span> </div> <div className="content-second"> <h3>{data.volumeInfo.title}</h3> <span> by {data.volumeInfo.authors ? data.volumeInfo.authors[0] : data.volumeInfo.publisher} </span> <ReactStars count={5} onChange={ratingChanged} size={32} color2="#ffd700" /> <span className="rating">{`Rating: ${rating}`}</span> <div className="content-btns"> <button className="btn-buy" type="button"> BUY </button> <button className="btn-icons" type="button" onClick={handleFavorite}> <img src={isFavorite ? favoritedIcon : notFavoritedIcon} alt="Heart Icon" /> </button> </div> </div> </div> <article className="resume-article"> <p>{data.volumeInfo.description}</p> </article> </section> ); }; export default DetailsBook;
define(['SocialNetView', 'text!templates/invitation/invitation.html' ,'views/menu/invitations'], function(SocialNetView, contactTemplate, InvitationsMenuView) { var contactView = SocialNetView.extend({ ok : false, total : 0, addbutton : false, removeButton: false, status:'', tagName: 'div', events: { "click .btnadd" : "addContact", "click .btnfollow" : "sendInvitation", "click .btnfollowcancel" : "cancelInvitation" }, initialize: function(options) { this.model.bind('change',this.render,this); }, addContact: function(event){ var contactId = $(event.currentTarget).attr('id').replace('bfa-',''); $.post('/accounts/me/contact', { contactId: contactId }, function onSuccess() { var btnadd= $('#bfa-'+contactId).text('Pendiente').attr('disabled','disabled'); }, function onError() { } ); }, sendInvitation: function(event) { var contactId = $(event.currentTarget).attr('id').replace('bf-',''); $.post('/accounts/me/sendinvitation', { contactId: contactId }, function onSuccess() { var btnadd= $('#bf-'+contactId).text('Pendiente').attr('disabled','disabled'); }, function onError() { } ); }, cancelInvitation: function(event) { var contactId = $(event.currentTarget).attr('id').replace('bfc-',''); $.ajax({ url: '/accounts/me/removeinvitation', type: 'DELETE', data: { contactId: contactId }}).done(function onSuccess() { }).fail(function onError() { }); }, render: function() { if(this.model.get('photoUrlSmall')!=undefined){ this.$el.html(_.template(contactTemplate,{model:this.model.toJSON(),addButton:this.addButton,status:this.options.status})); } return this; } }); return contactView; });
var CookieManager = (function() { 'use strict'; function _setCookieValue(key) { $.cookie(key, $('#' + key).val()); } function _getCookieValue(key) { return $.cookie(key); } function _bindCookieValue(key) { $('#' + key).val($.cookie(key)); } return { SetCookieValue: _setCookieValue, GetCookieValue: _getCookieValue, BindCookieValue: _bindCookieValue } })();
define(function(require){ 'use strict' /* ================================= Most of the code on this page is extracted from: img-touch-canvas - v0.1 http://github.com/rombdn/img-touch-canvas (c) 2013 Romain BEAUDON This code may be freely distributed under the MIT License ================================= */ var Pinch = function(options) { if( !options || !options.canvasId || !options.path) { throw 'ImgZoom constructor: missing arguments canvas or path'; } this.canvas = document.getElementById(options.canvasId); this.canvas.width = options.width; this.canvas.height = options.height; this.context = this.canvas.getContext('2d'); this.zoomPos = {x:this.canvas.width/2,y:this.canvas.height/2}; this.position = { x: 0, y: 0 }; this.scale = 0.5; this.imgTexture = new Image(); $(this.imgTexture).on('load', function (){ this.update(); }.bind(this)) this.imgTexture.src = options.path; this.lastZoomScale = null; this.lastX = null; this.lastY = null; this.init = false; this.update(); }; Pinch.prototype = { reset: function(){ this.clear(); this.zoomPos = {x:this.canvas.width/2,y:this.canvas.height/2}; this.position = { x: 0, y: 0 }; this.scale = 0.5; this.lastZoomScale = null; this.lastX = null; this.lastY = null; this.init = false; }, updatefn:[], clear: function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }, update: function() { if(!this.init) { if(this.imgTexture.width) { var scaleRatio = null; scaleRatio = (this.canvas.clientHeight - 100) / this.imgTexture.height; this.initialScale = scaleRatio; this.scale = scaleRatio; this.position.x = (this.canvas.width - this.imgTexture.width*this.scale)/2; this.position.y = (this.canvas.height - this.imgTexture.height*this.scale)/2; this.init = true; } } this.clear(); this.context.save(); var transX = this.position.x ; var transY = this.position.y ; for(var i = 0; i < this.updatefn.length; i++){ this.updatefn[i](); } this.context.drawImage( this.imgTexture, this.position.x, this.position.y, this.scale * this.imgTexture.width, this.scale * this.imgTexture.height); this.context.restore(); }, gesturePinchZoom: function(event) { var zoom = false; if( event.originalEvent.targetTouches.length >= 2 ) { var p1 = event.originalEvent.targetTouches[0]; var p2 = event.originalEvent.targetTouches[1]; var zoomScale = Math.sqrt(Math.pow(p2.clientX - p1.clientX, 2) + Math.pow(p2.clientY - p1.clientY, 2)); //euclidian distance this.zoomPos.x = (p1.clientX + (p2.clientX-p1.clientX)/2); this.zoomPos.y = (p1.clientY + (p2.clientY-p1.clientY)/2); if( this.lastZoomScale ) { zoom = zoomScale - this.lastZoomScale; } this.lastZoomScale = zoomScale; } return zoom; }, doZoom: function(zoom, force) { if(!zoom) return; //new scale var currentScale = this.scale; var newScale = (typeof force == 'undefined') ? Math.min(2, this.scale + zoom/100) : Math.min(2, Math.max(zoom, 0.24)); console.log(newScale); //some helpers var deltaScale = newScale - currentScale; var currentWidth = (this.imgTexture.width * this.scale); var currentHeight = (this.imgTexture.height * this.scale); var deltaWidth = this.imgTexture.width*deltaScale; var deltaHeight = this.imgTexture.height*deltaScale; //by default scale doesnt change position and only add/remove pixel to right and bottom //so we must move the image to the left to keep the image centered //ex: coefX and coefY = 0.5 when image is centered <=> move image to the left 0.5x pixels added to the right var canvasmiddleX = this.canvas.clientWidth / 2; var canvasmiddleY = this.canvas.clientHeight / 2; var xonmap = (-this.position.x) + canvasmiddleX; var yonmap = (-this.position.y) + canvasmiddleY; var coefX = -xonmap / (currentWidth); var coefY = -yonmap / (currentHeight); var newPosX = this.position.x + deltaWidth*coefX; var newPosY = this.position.y + deltaHeight*coefY; //edges cases var newWidth = currentWidth + deltaWidth; var newHeight = currentHeight + deltaHeight; if( newWidth < this.canvas.clientWidth ){ newPosX = (this.canvas.width - newWidth)/2 }; if( newHeight < this.canvas.clientHeight-100 ) return; if( newPosY > 50 ) { newPosY = 50; } if( newPosY + newHeight < this.canvas.clientHeight ) { newPosY = (this.canvas.clientHeight - newHeight)/2; } //finally affectations this.scale = newScale; this.prevScale = currentScale; this.position.x = newPosX; this.position.y = newPosY; this.update(); }, doMove: function(relativeX, relativeY) { console.log(this.lastX , this.lastY); if(this.lastX && this.lastY) { console.log('up'); var deltaX = relativeX - this.lastX; var deltaY = relativeY - this.lastY; var currentWidth = (this.imgTexture.width * this.scale); var currentHeight = (this.imgTexture.height * this.scale); this.position.x += deltaX; this.position.y += deltaY; if( currentWidth < this.canvas.width ) { this.position.x = (this.canvas.width - currentWidth)/2; } if( this.position.y > 50 ) { this.position.y = 50; } else if( this.position.y + currentHeight < this.canvas.clientHeight-50 ) { this.position.y = this.canvas.clientHeight- 50 - currentHeight; } } this.lastX = relativeX; this.lastY = relativeY; this.update(); }, touchstart: function (e){ this.lastX = null; this.lastY = null; this.lastZoomScale = null; }, touchmove:function (e){ e.preventDefault(); if(e.originalEvent.targetTouches.length == 2) { //pinch this.doZoom(this.gesturePinchZoom(e)); } else if(e.originalEvent.targetTouches.length == 1) { var relativeX = e.originalEvent.targetTouches[0].clientX; var relativeY = e.originalEvent.targetTouches[0].clientY ; this.doMove(relativeX, relativeY); } } }; return Pinch; });
import React from 'react'; import './Characters.css'; function Characters(props){ return( <div className="card"> <div className="content-container"> <div className="card-content"> <h2>{props.starchar.name}</h2> <h4>Gender: {props.starchar.gender}</h4> <h4>Height: {props.starchar.height}</h4> <h4>Mass: {props.starchar.mass}</h4> <h4>Hair Color: {props.starchar.hair_color}</h4> <h4>Birth Year: {props.starchar.birth_year}</h4> </div> </div> </div> ) } export default Characters;
import React from 'react' import styles from './styles' import {getCaptionFromEdges} from './helpers' const Image = (props) => { const {data} = props return ( <img src={data.display_url} style={styles} alt={getCaptionFromEdges(data.edge_media_to_caption)} /> ) } export default Image
import React, { Component } from 'react'; import logo from './logo.svg'; import { Wrapper, Header, Logo, Title, Intro } from './component'; export default class App extends Component { render() { return ( <Wrapper> <Header> <Logo src={logo} alt={'logo'} /> <Title>Welcome to React</Title> </Header> <Intro> To get started, edit <code>src/App.js</code> and save to reload. </Intro> </Wrapper> ); } }
import React from 'react'; import styled from 'styled-components'; const SubmitElm = styled.input` display: block; width: 10rem; margin: 0.5rem; padding: 0.5rem; /* border: none; */ `; const SubmitBtn = () => { return ( <SubmitElm type='submit' aria-label='submit form' /> ) }; export default SubmitBtn;
import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useHistory, useParams } from "react-router-dom"; // import action import { layDanhSachPhim } from "../../actions/movies"; import { layDanhSachPhimTheoTen } from "../../actions/moviesSearch"; import { pageTitleChange } from "../../actions/pageTitle"; import { toggleMenu } from "../../actions/toggleMenu"; // import component import IsLoading from "../../components/IsLoading"; //import khac import PhanTrangAppLayout from "../../components/PhanTrangAppLayout"; export default function Search() { const dispatch = useDispatch(); let { keyword } = useParams(); const history = useHistory(); const { danhSachPhim } = useSelector((state) => state.danhSachPhim); const { moviesSearch, isLoading, error } = useSelector( (state) => state.moviesSearch ); //Được chạy mỗi khi load trang này useEffect(() => { //load danh sach phim dispatch(layDanhSachPhim()); }, []); // set active page useEffect(() => { dispatch( pageTitleChange({ activePage: 3, pageTitle: "", }) ); }, []); //close submenu o man hinh nho useEffect(() => { dispatch(toggleMenu("close")); }, []); useEffect(() => { dispatch(layDanhSachPhimTheoTen(keyword)); }, [keyword]); //chuyen den trang chi tiet phim nguoi dung chon phim truc tiep tren list autocomplete useEffect(() => { if (moviesSearch.length === 1 && keyword === moviesSearch[0].tenPhim) { history.push("/movie/" + moviesSearch[0].maPhim); } }, [moviesSearch]); return isLoading ? ( <IsLoading /> ) : error ? ( <div>{error}</div> ) : ( <div> <PhanTrangAppLayout danhSachPhim={moviesSearch} link={"/search/" + keyword} title="KẾT QUẢ TÌM KIẾM" /> </div> ); }
console.log("#S addCloth.js");
towers = [[3,2,1],[],[]]; function isValidMove(start,end){ if(towers[start].length === 0){ console.log('im at 1st block'); return false; }else if(towers[end].length === 0){ console.log('im at 2nd block'); return true; }else if(towers[end][towers[end].length-1] < towers[start][towers[start].length-1]){ console.log('im at 3rd block'); return false; }else{ console.log('im at 4th block'); return true; } } console.log(isValidMove(1,2));
// For an introduction to the Page Control template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232511 (function () { "use strict"; var session = malfiGlobals.session[malfiGlobals.invokedDiv]; var resultArray = malfiGlobals.defaultViews[malfiGlobals.invokedDiv]; malfiGlobals.displayedItemsArray.splice(0, malfiGlobals.displayedItemsArray.length); //½½½½½½½½½½!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //!!!!!!!!!! //TODO: TEKSTI JSONISTA?? en tiä toimiiko ku en voi testata lol //Populate displayedItemsArray with getObjectChildren function's results if (resultArray !== null && resultArray !== undefined) { resultArray.forEach(function (element, index, resultArray) { malfiGlobals.displayedItemsArray.push(resultArray[index]); }); listViewNamespace.itemList._data = WinJS.Binding.as(malfiGlobals.displayedItemsArray); for (var loop = 0; loop < resultArray.length; loop++) { listViewNamespace.itemList.setAt(loop, resultArray[loop]); }; }; WinJS.UI.Pages.define("/pages/listviewpage/listview.html", { // This function is called whenever a user navigates to this page. It // populates the page elements with the app's data. ready: function (element, options) { // TODO: turha?? vai ei??????????? // Jos halutaan tarkistaa, onko configuration.json muuttunut /*var denyAccess if (malfiGlobals.currentLocation.name !== "Views") { denyAccess = true for (var i = 0; i < malfiGlobals.defaultViews[malfiGlobals.invokedDiv].length; i++) { if (malfiGlobals.defaultViews[malfiGlobals.invokedDiv][i].name === malfiGlobals.currentPath[1]) { denyAccess = false; } } } if (denyAccess === true) { malfiGlobals.currentLocation.id = "defaultViews"; malfiGlobals.currentLocation.name = "Views"; malfiGlobals.currentLocation.type = "defaultFolder"; malfiGlobals.currentLocation.objectTypeId = "defaultFolder"; }*/ if (malfiGlobals.companyLogo[malfiGlobals.invokedDiv].name) { document.getElementById("companyLogoDiv").style.display = "inline"; document.getElementById("companyLogoImg").src = "ms-appdata:///temp/" + malfiGlobals.companyLogo[malfiGlobals.invokedDiv].name; } else { document.getElementById("companyLogoDiv").style.display = "none"; } document.getElementById("companyLogoDiv").style.marginLeft = "10px"; document.getElementById("companyLogoDiv").style.marginTop = "10px"; document.getElementById('basicListview').style.visibility = "hidden"; document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById("basicListview").addEventListener("iteminvoked", menuSwitchHandler, false); document.getElementById("allSitesButton").addEventListener("click", openMainAllSitesHandler); document.getElementById("mySitesButton").addEventListener("click", openMainMySitesHandler); document.getElementById("favoriteSitesButton").addEventListener("click", openMainFavoriteSitesHandler); if (malfiGlobals.currentLocation.name === "My Sites" || malfiGlobals.currentLocation.name === "Sites") { document.getElementById("siteButtons").style.display === "inline"; } else { document.getElementById("siteButtons").style.display === "none"; } if (malfiGlobals.currentLocation.name === "Views") { var def = $.Deferred(); var defaultViewsArray = []; if (Windows.Storage.ApplicationData.current.localSettings.values.defaultViews !== undefined) { defaultViewsArray = JSON.parse(Windows.Storage.ApplicationData.current.localSettings.values["defaultViews"]) }; malfiGlobals.session[malfiGlobals.invokedDiv].getMobileConfiguration(def); def.done(function (arg) { var override = false; var array = []; if (arg.rootMenu["com.alfresco.activities"].visible === true) { array.push({ name: 'Activities', id: 'activities', objectTypeId: 'defaultFolder' }); } if (arg.rootMenu["com.alfresco.favorites"].visible === true) { array.push({ name: 'Favorites', id: 'favorites', objectTypeId: 'defaultFolder' }); } if (arg.rootMenu["com.alfresco.repository"].visible === true) { array.push({ name: 'Repository', id: 'repository', objectTypeId: 'defaultFolder' }); } if (arg.rootMenu["com.alfresco.repository.shared"].visible === true) { array.push({ name: 'Shared Files', id: 'sharedFiles', objectTypeId: 'defaultFolder' }); } if (arg.rootMenu["com.alfresco.repository.userhome"].visible === true) { array.push({ name: 'My Files', id: 'myFiles', objectTypeId: 'defaultFolder' }); } if (arg.rootMenu["com.alfresco.sites"].visible === true) { array.push({ name: 'Sites', id: 'sites', objectTypeId: 'defaultFolder' }); } if (arg.rootMenu["com.alfresco.tasks"].visible === true) { array.push({ name: 'My Tasks', id: 'tasks', objectTypeId: 'defaultFolder' }); } if (defaultViewsArray[malfiGlobals.invokedDiv] !== null && defaultViewsArray[malfiGlobals.invokedDiv] !== undefined) { defaultViewsArray[malfiGlobals.invokedDiv].forEach(function (element, index, defaultViewsArray) { var check = 0; for (var i = 0; i < array.length; i++) { if (element.id === array[i].id) { check++; } else if (i === array.length - 1 && check === 0) { override = true; } if (check === 2) { override = true; } } }) if (override === true) { malfiGlobals.defaultViews[malfiGlobals.invokedDiv] = array; } else { malfiGlobals.defaultViews[malfiGlobals.invokedDiv] = defaultViewsArray[malfiGlobals.invokedDiv]; } } else if (defaultViewsArray[malfiGlobals.invokedDiv] && defaultViewsArray[malfiGlobals.invokedDiv].length === 0) { malfiGlobals.defaultViews[malfiGlobals.invokedDiv] = defaultViewsArray[malfiGlobals.invokedDiv]; } else { malfiGlobals.defaultViews[malfiGlobals.invokedDiv] = array; } goOn(); }) def.fail(function (arg) { if (defaultViewsArray.length > 0) { malfiGlobals.defaultViews[malfiGlobals.invokedDiv] = defaultViewsArray[malfiGlobals.invokedDiv]; } else { malfiGlobals.defaultViews[malfiGlobals.invokedDiv] = malfiGlobals.allDefaultViews } goOn(); }) } else { goOn(); } function goOn() { malfiGlobals.defaultViews[malfiGlobals.invokedDiv].sort(function (a, b) { var nameA = a.name.toLowerCase(), nameB = b.name.toLowerCase() if (nameA < nameB) //sort string ascending return -1 if (nameA > nameB) return 1 return 0 //default return value (no sorting) }) var history = WinJS.Navigation.history; if (document.getElementById("locationPath") === null) { var locationPath = document.createElement("div"); locationPath.setAttribute("id", "locationPath"); locationPath.setAttribute("style", "margin-top: 0%; margin-left: 10px; margin-right: 10px; width: 100%; height: auto; overflow-x: auto; white-space: nowrap; -ms-overflow-style: none"); document.getElementById("listViewHeader").appendChild(locationPath) } if (document.getElementById("path0") === null) { for (var i = 0; i < malfiGlobals.currentPath.path.length; i++) { var locationPath = document.getElementById("locationPath"); var fillerDiv = document.createElement("div"); var div = document.createElement("div"); div.setAttribute("id", "path" + i); div.setAttribute("class", "pathdiv"); div.setAttribute("style", "display: inline-block"); div.addEventListener("click", clickPathItem) var par = document.createElement("p"); par.setAttribute("id", "par" + i); if (i === 0) { par.innerText = malfiGlobals.currentPath.path[i]; } else { par.innerText = ">" + malfiGlobals.currentPath.path[i]; } par.setAttribute("class", "pathPar"); par.setAttribute("style", "font-size: 30px; padding: 0px 0px 0px 5px;"); div.appendChild(par); locationPath.appendChild(div); if (i === malfiGlobals.currentPath.path.length - 1) { fillerDiv.setAttribute("style", "width: 10%; display: inline-block"); fillerDiv.setAttribute("id", "fillerDiv"); locationPath.appendChild(fillerDiv) locationPath.scrollLeft = locationPath.scrollWidth; } } } if (malfiGlobals.currentLocation.name === "Favorites") { displayFavorites(); } else if (malfiGlobals.currentLocation.id !== 'defaultViews') { var defer = $.Deferred(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; window.toggleButtons(true); var filter = ""; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(malfiGlobals.currentLocation.id, filter, defer); defer.done(function (resultArray) { renderNewItems(resultArray, false); }); defer.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }); } else if (malfiGlobals.currentLocation.id === 'defaultViews') { displayDefaultViews(); }; document.getElementById("basicListview").winControl.itemDataSource = listViewNamespace.itemList.dataSource; var appbar = document.querySelector("#defaultAppbar").winControl; if (appbar) { appbar.showOnlyCommands(["cmdHome", "cmdUploadToFolder", "cmdSettings", "cmdSearch", "cmdNewFolder", "cmdOperations", "cmdAbout"]); } } }, unload: function () { // : Respond to navigations away from this page. // TODO: loading in progress ja buttonit tähän?=?!?! }, updateLayout: function (element) { /// <param name="element" domElement="true" /> // : Respond to changes in layout. } }); //Handles navigating up and down the folder tree of a repository window.menuSwitchHandler = function (event) { window.toggleButtons(true); malfiGlobals.loadingInProgress = true; if (document.getElementById("addFolder").style.display === 'inline') { document.getElementById("addFolder").style.display = 'none'; } // Phone's back button was pressed if (event === 'back') { // If in repository root folder, move up to the default views list if (malfiGlobals.currentLocation.id === malfiGlobals.rootFolder[malfiGlobals.invokedDiv]) { displayDefaultViews(); } else if (malfiGlobals.currentLocation.type === 'F:st:site' && (malfiGlobals.currentPath.path[1] === "My Sites" || malfiGlobals.currentPath.path[1] === "All Sites" || malfiGlobals.currentPath.path[1] === "Favorite Sites")) { malfiGlobals.currentPath.path.pop(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; document.getElementById("locationPath").removeChild(document.getElementById("path" + malfiGlobals.currentPath.history)); malfiGlobals.currentPath.history-- document.getElementById("siteButtons").style.display = "inline" switch (malfiGlobals.currentPath.path[1]) { case "My Sites": openMainMySitesHandler(); break; case "All Sites": openMainAllSitesHandler(); break; case "Favorite Sites": openMainFavoriteSitesHandler(); break; } } else if (malfiGlobals.currentPath.path[malfiGlobals.currentPath.history - 1] === "Favorites") { malfiGlobals.currentPath.path.pop(); document.getElementById("locationPath").removeChild(document.getElementById("path" + malfiGlobals.currentPath.history)); malfiGlobals.currentPath.history--; displayFavorites(); } else if (malfiGlobals.currentLocation.type === 'defaultSitesFolder') { document.getElementById("siteButtons").style.display = "none"; displayDefaultViews(); } // If in the default views list, navigate back to home page else if (malfiGlobals.currentLocation.id === 'defaultViews') { WinJS.Navigation.navigate("/pages/home/home.html"); } // If in the favorited documents list, move up to the default views list else if (malfiGlobals.currentLocation.name === 'Favorites' && WinJS.Navigation.location === "/pages/listviewpage/listview.html") { displayDefaultViews(); } else if ((malfiGlobals.currentLocation.name === malfiGlobals.activeUser || malfiGlobals.currentLocation.name === "My Files") && malfiGlobals.currentPath.history < 2 && WinJS.Navigation.location === "/pages/listviewpage/listview.html") { displayDefaultViews(); } else if (malfiGlobals.currentLocation.name === 'Shared Files' && WinJS.Navigation.location === "/pages/listviewpage/listview.html" || malfiGlobals.currentLocation.name === "Shared" && malfiGlobals.currentPath.history < 2 && WinJS.Navigation.location === "/pages/listviewpage/listview.html") { displayDefaultViews(); } else if (malfiGlobals.currentLocation.name === 'Sites' && WinJS.Navigation.location === "/pages/listviewpage/listview.html" && malfiGlobals.currentLocation.type !== "F:st:sites") { displayDefaultViews(); } // Otherwise just navigate up the repository folder tree else { var defer1 = $.Deferred(); var filter = "cmis:objectTypeId, cmis:name, cmis:objectId"; malfiGlobals.session[malfiGlobals.invokedDiv].navigateUp(malfiGlobals.currentLocation.id, filter, defer1); defer1.done(function (result) { malfiGlobals.currentLocation.id = result.objectId; malfiGlobals.currentLocation.name = result.name; malfiGlobals.currentLocation.type = result.objectTypeId; //document.getElementById('thisLocation').innerHTML = result.name; document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; window.toggleButtons(true); var defer2 = $.Deferred(); var filter = ''; //filters: name, objectId, typeId, cmis:contentStream malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(result.objectId, filter, defer2); defer2.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) }); defer2.done(function (resultArray) { malfiGlobals.currentPath.path.pop(); document.getElementById("locationPath").removeChild(document.getElementById("path" + malfiGlobals.currentPath.history)); malfiGlobals.currentPath.history--; renderNewItems(resultArray, true); }); }); defer1.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }) } } // An item of the list was invoked else { malfiGlobals.gridView = false; var invokedIndexTest = event.detail.itemIndex; // If invoked item is one of the default views items, act accordingly if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectTypeId === "defaultFolder") { // Activities was invoked, navigate to activities.html if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.name === 'Activities') { WinJS.Navigation.navigate("/pages/activities/activities.html"); } // Repositories was invoked, populate listview with items from repo's root folder else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.name === 'Repository') { var defer = $.Deferred(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; window.toggleButtons(true); var filter = ""; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(malfiGlobals.rootFolder[malfiGlobals.invokedDiv], filter, defer); defer.done(function (resultArray) { malfiGlobals.currentLocation.id = malfiGlobals.rootFolder[malfiGlobals.invokedDiv]; malfiGlobals.currentLocation.name = 'Repository'; malfiGlobals.currentLocation.type = 'cmis:folder'; malfiGlobals.currentPath.path.push("Repository"); renderNewItems(resultArray, false); currentLocationPath(); }); defer.fail(function () { malfiGlobals.loadingInProgress = false; var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) window.toggleButtons(false); }) } // My files was invoked, populate listview with user's personal files in repo else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.id === 'myFiles') { malfiGlobals.currentLocation.path = '/User Homes/' + malfiGlobals.activeUser; malfiGlobals.currentLocation.name = "My Files"; var def = $.Deferred(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectByPath(malfiGlobals.currentLocation.path, def, ''); def.done(function (id) { var def2 = $.Deferred(); malfiGlobals.currentLocation.id = id.objectId; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(id.objectId, '', def2) def2.done(function (resultArray) { malfiGlobals.currentLocation.name = 'My Files'; malfiGlobals.currentLocation.type = 'defaultFolder'; malfiGlobals.currentPath.path.push("My Files"); renderNewItems(resultArray); currentLocationPath(); }) def2.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }) }); def.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }) } // Shared files was invoked, populate listview with a list of shared files in repo else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.id === 'sharedFiles') { var path = '/Shared/'; var def = $.Deferred(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectByPath(path, def, ''); def.done(function (id) { var def2 = $.Deferred(); malfiGlobals.currentLocation.id = id.objectId; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(id.objectId, '', def2) def2.done(function (resultArray) { malfiGlobals.currentLocation.name = 'Shared Files'; malfiGlobals.currentLocation.type = 'defaultFolder'; malfiGlobals.currentPath.path.push("Shared"); currentLocationPath(); renderNewItems(resultArray); }) def2.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }); }); def.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }) } // Sites was invoked, populate listview with folders for all sites, fav sites and user's sites else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.id === 'sites') { document.getElementById("allSitesButtonString").innerText = malfiGlobals.strings[malfiGlobals.invokedDiv].listview.allSitesButton; document.getElementById("favoriteSitesButtonString").innerText = malfiGlobals.strings[malfiGlobals.invokedDiv].listview.favoriteSitesButton; document.getElementById("mySitesButtonString").innerText = malfiGlobals.strings[malfiGlobals.invokedDiv].listview.mySitesButton; malfiGlobals.currentLocation.name = 'Sites'; malfiGlobals.currentLocation.id = 'sites'; malfiGlobals.currentLocation.type = 'defaultSitesFolder'; document.getElementById("siteButtons").style.display = "inline"; openMainMySitesHandler(); } // Favorites was invoked, populate listview with the document's the user has favorited else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.id === 'favorites') { displayFavorites(); } else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.id === 'tasks') { window.toggleButtons(true); malfiGlobals.loadingInProgress = true WinJS.Navigation.navigate("/pages/tasks/tasks.html"); } } else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectTypeId === "site" || document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectTypeId === "F:st:site") { var def = $.Deferred(); malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectId, '', def) def.done(function (resultArray) { var pathString = undefined; if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.name.length > 10) { pathString = document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.name.slice(0, 20) + "..."; } else { pathString = document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.name } malfiGlobals.currentPath.path.push(pathString); currentLocationPath(); document.getElementById("siteButtons").style.display = "none" malfiGlobals.currentLocation.id = document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectId; malfiGlobals.currentLocation.name = document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.name; malfiGlobals.currentLocation.type = document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectTypeId; renderNewItems(resultArray, false); }) def.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) displayDefaultViews(); }) } // Invoked item was a folder in a repository else if (document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectTypeId === "cmis:folder" || document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[invokedIndexTest]].data.objectTypeId === "F:st:sites") { var defer = $.Deferred(); var invokedIndex = event.detail.itemIndex; document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; window.toggleButtons(true); var nextFolderId = document.getElementById('basicListview').winControl.itemDataSource._list._keyMap[document.getElementById('basicListview').winControl.itemDataSource._list._keys[invokedIndex]].data.objectId; var filter = ''; malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(nextFolderId, filter, defer); defer.done(function (resultArray) { malfiGlobals.currentLocation.id = document.getElementById('basicListview').winControl.itemDataSource._list._keyMap[document.getElementById('basicListview').winControl.itemDataSource._list._keys[invokedIndex]].data.objectId; malfiGlobals.currentLocation.name = document.getElementById('basicListview').winControl.itemDataSource._list._keyMap[document.getElementById('basicListview').winControl.itemDataSource._list._keys[invokedIndex]].data.name malfiGlobals.currentLocation.type = document.getElementById('basicListview').winControl.itemDataSource._list._keyMap[document.getElementById('basicListview').winControl.itemDataSource._list._keys[invokedIndex]].data.objectTypeId; renderNewItems(resultArray, true); if (malfiGlobals.currentLocation.name.length > 10) { malfiGlobals.currentPath.path.push(malfiGlobals.currentLocation.name.slice(0, 20) + "...") } else { malfiGlobals.currentPath.path.push(malfiGlobals.currentLocation.name); } currentLocationPath(); }); defer.fail(function () { malfiGlobals.loadingInProgress = false; var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) window.toggleButtons(false); }) } // If invoked item is a document, navigate to inspectFile.html with item's details else { var invokedItem = document.getElementById("basicListview").winControl.itemDataSource._list._keyMap[document.getElementById("basicListview").winControl.itemDataSource._list._keys[event.detail.itemIndex]].data if (invokedItem.id !== "emptiness") { WinJS.Navigation.navigate("/pages/inspectFile/inspectFile.html", invokedItem); } else { malfiGlobals.loadingInProgress = false; window.toggleButtons(false); } } } }; // Lists current user's favorited documents function displayFavorites() { var defer = $.Deferred(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; window.toggleButtons(true); malfiGlobals.session[malfiGlobals.invokedDiv].getFavorites(malfiGlobals.activeUser, defer, {}, []); malfiGlobals.currentLocation.id = ''; malfiGlobals.currentLocation.name = 'Favorites'; malfiGlobals.currentLocation.type = 'defaultFolder'; defer.done(function (unparsedArray) { var _listview = document.getElementById("basicListview").winControl; WinJS.UI.setOptions(_listview, { layout: { type: WinJS.UI.ListLayout } }); var _dataSource = _listview.itemDataSource; resultArray = []; var obj = {} unparsedArray.forEach(function (element, index, unparsedArray) { obj = {}; // Favorite sites won't be listed in the favorites folder if (unparsedArray[index].target.folder !== undefined) { obj.name = unparsedArray[index].target.folder.name; obj.objectId = unparsedArray[index].target.folder.id; obj.objectTypeId = "cmis:folder"; resultArray.push(obj); } else if (!unparsedArray[index].target.site) { obj.name = unparsedArray[index].target.file.name; obj.id = unparsedArray[index].target.file.id; resultArray.push(obj); } }) _dataSource.beginEdits(); for (var i = 0; i < _listview._selection._selected._itemsCount; i++) { _dataSource.remove(_dataSource._list._keys[0]); } resultArray.forEach(function (element, index, resultArray) { _dataSource.insertAtEnd(null, resultArray[index]); }); _dataSource.endEdits(); var defdef = $.Deferred(); if (resultArray.length === 0) { defdef.resolve(); } for (var loop = 0; loop < resultArray.length; loop++) { listViewNamespace.itemList.setAt(loop, resultArray[loop]); if (loop === resultArray.length - 1) { defdef.resolve(); } } defdef.done(function () { if (malfiGlobals.currentPath.path[malfiGlobals.currentPath.history] !== "Favorites") { malfiGlobals.currentPath.path.push("Favorites"); currentLocationPath(); } document.getElementById('loadingProgress').style.visibility = "hidden"; basicListview.winControl.itemDataSource = listViewNamespace.itemList.dataSource; if (malfiGlobals.currentPath.backSteps > 1) { malfiGlobals.currentPath.backSteps-- menuSwitchHandler('back'); var locationPath = document.getElementById("locationPath") locationPath.scrollLeft = locationPath.scrollWidth; } else { window.toggleButtons(false); document.getElementById('basicListview').style.visibility = "visible"; malfiGlobals.loadingInProgress = false; } }); defdef.fail(function () { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) }) }); defer.fail(function (errObj) { window.toggleButtons(false); var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) }) } function openMainFavoriteSitesHandler() { var sitesDef = $.Deferred(); var parsedArray = []; document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; malfiGlobals.session[malfiGlobals.invokedDiv].getFavorites(malfiGlobals.activeUser, sitesDef); sitesDef.done(function (resultArray) { if (malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "All Sites" || malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "Favorite Sites" || malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "My Sites") { malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] = "Favorite Sites"; document.getElementById("par" + malfiGlobals.currentPath.history).innerText = ">Favorite Sites" } else { if (malfiGlobals.currentLocation.name.length > 10) { malfiGLobals.currentPath.path.puah(malfiGlobals.currentLocation.name.slice(0, 20)) } else { malfiGlobals.currentPath.path.push(malfiGlobals.currentLocation.name) } currentLocationPath(); } if (malfiGlobals.currentPath.path[1] === "All Sites" || malfiGlobals.currentPath.path[1] === "Favorite Sites" || malfiGlobals.currentPath.path[1] === "My Sites") { malfiGlobals.currentLocation.name = 'Favorite Sites'; malfiGlobals.currentLocation.id = 'sites'; malfiGlobals.currentLocation.type = 'defaultSitesFolder'; } else { malfiGlobals.currentLocation.id = result.objectId; malfiGlobals.currentLocation.name = result.name; malfiGlobals.currentLocation.type = result.objectTypeId; } resultArray.forEach(function (element, index, array) { //If the favorite is a site if (element.target.site) { //Make a folder-like object out of the site for listview to use parsedArray.push({ name: element.target.site.title, description: [element.target.site.description], objectId: element.target.site.guid, objectTypeId: 'F:st:site', baseTypeId: 'cmis:folder' }); } }); renderNewItems(parsedArray, false); }); sitesDef.fail(function (jqXHR, textStatus, errorThrown) { var msg = new Windows.UI.Popups.MessageDialog("Error: " + arguments[0].status + " - " + arguments[0].statusText) malfiGlobals.popupQueue.showSync(msg) }); } function openMainMySitesHandler() { var sitesDef = $.Deferred(); document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; malfiGlobals.session[malfiGlobals.invokedDiv].getMemberships(malfiGlobals.activeUser, sitesDef); sitesDef.done(function (resultArray) { if (malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "All Sites" || malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "My Sites" || malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "Favorite Sites") { malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] = "My Sites"; document.getElementById("par" + malfiGlobals.currentPath.history).innerText = ">My Sites" } else { malfiGlobals.currentPath.path.push("My Sites") currentLocationPath(); } if (malfiGlobals.currentPath.path[1] === "All Sites" || malfiGlobals.currentPath.path[1] === "Favorite Sites" || malfiGlobals.currentPath.path[1] === "My Sites") { malfiGlobals.currentLocation.name = 'All Sites'; malfiGlobals.currentLocation.id = 'sites'; malfiGlobals.currentLocation.type = 'defaultSitesFolder'; } else { malfiGlobals.currentLocation.id = result.objectId; malfiGlobals.currentLocation.name = result.name; malfiGlobals.currentLocation.type = result.objectTypeId; } var parsedArray = [] resultArray.forEach(function (element, index) { parsedArray.push({ name: element.site.title, description: [element.site.description], objectId: element.site.guid, objectTypeId: 'F:st:site', baseTypeId: 'cmis:folder' }); }) renderNewItems(parsedArray, false); }) sitesDef.fail(function (jqXHR, textStatus, errorThrown) { // TODO: ERRORMSG }); } function openMainAllSitesHandler() { var sitesDef = $.Deferred(); var parsedArray = []; document.getElementById('loadingProgress').style.visibility = "visible"; document.getElementById('basicListview').style.visibility = "hidden"; malfiGlobals.session[malfiGlobals.invokedDiv].getSites(sitesDef); sitesDef.done(function (resultArray) { if (malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "My Sites" || malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "All Sites" || malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] === "Favorite Sites") { malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1] = "All Sites"; document.getElementById("par" + malfiGlobals.currentPath.history).innerText = ">All Sites" } else { malfiGlobals.currentPath.path.push("All Sites") currentLocationPath(); } if (malfiGlobals.currentPath.path[1] === "All Sites" || malfiGlobals.currentPath.path[1] === "Favorite Sites" || malfiGlobals.currentPath.path[1] === "My Sites") { malfiGlobals.currentLocation.name = 'Favorite Sites'; malfiGlobals.currentLocation.id = 'sites'; malfiGlobals.currentLocation.type = 'defaultSitesFolder'; } else { malfiGlobals.currentLocation.id = result.objectId; malfiGlobals.currentLocation.name = result.name; malfiGlobals.currentLocation.type = result.objectTypeId; } resultArray.forEach(function (element, index, array) { //Make a folder-like object out of the site for listview to use parsedArray.push({ name: element.title, description: [element.description], objectId: element.guid, objectTypeId: 'F:st:site', baseTypeId: 'cmis:folder' }); }); renderNewItems(parsedArray, false); }); sitesDef.fail(function (jqXHR, textStatus, errorThrown) { // TODO: ERRORMSG }); } // Renders current user's default views function displayDefaultViews() { var resultArray = malfiGlobals.defaultViews[malfiGlobals.invokedDiv]; malfiGlobals.currentLocation.id = 'defaultViews'; malfiGlobals.currentLocation.name = 'Views'; malfiGlobals.currentLocation.type = 'defaultFolder'; malfiGlobals.currentPath.path = []; malfiGlobals.currentPath.path.push("Views"); malfiGlobals.currentPath.history = 0; if (document.getElementById("locationPath") !== null) { document.getElementById("locationPath").innerHTML = ""; } var div = document.createElement("div"); div.setAttribute("id", "path0"); div.setAttribute("class", "pathdiv"); div.setAttribute("style", "display: inline-block; height: auto; width: auto"); div.addEventListener("click", clickPathItem) var par = document.createElement("p"); par.setAttribute("id", "par0"); par.innerText = malfiGlobals.currentPath.path[0]; par.setAttribute("class", "pathPar"); par.setAttribute("style", "font-size: 30px; padding: 0px 0px 0px 5px;"); div.appendChild(par); document.getElementById("locationPath").appendChild(div) malfiGlobals.gridView = true; var listview = document.getElementById("basicListview").winControl; WinJS.UI.setOptions(listview, { layout: { type: WinJS.UI.GridLayout, orientation: WinJS.UI.Orientation.vertical, maximumRowsOrColumns: 3 } }) renderNewItems(resultArray, false); } function currentLocationPath() { var locationPath = document.getElementById("locationPath"); var fillerDiv = document.getElementById("fillerDiv"); if (fillerDiv !== null) { locationPath.removeChild(document.getElementById("fillerDiv")); } malfiGlobals.currentPath.history++ var div = document.createElement("div"); div.setAttribute("id", "path" + malfiGlobals.currentPath.history); div.setAttribute("class", "pathdiv"); div.setAttribute("style", "display: inline-block"); div.addEventListener("click", clickPathItem) var par = document.createElement("p"); par.setAttribute("id", "par" + malfiGlobals.currentPath.history); par.innerText = ">" + malfiGlobals.currentPath.path[malfiGlobals.currentPath.path.length - 1]; par.setAttribute("class", "pathPar"); par.setAttribute("style", "font-size: 30px; padding: 0px 0px 0px 5px;"); div.appendChild(par); locationPath.appendChild(div) fillerDiv = document.createElement("div"); fillerDiv.setAttribute("style", "width: 10%; display: inline-block"); fillerDiv.setAttribute("id", "fillerDiv"); locationPath.appendChild(fillerDiv) locationPath.scrollLeft = locationPath.scrollWidth; } // Renders the new items getObjectChildren has fetched function renderNewItems(resultArray, bool) { if (malfiGlobals.gridView === false) { var listview = document.getElementById("basicListview").winControl; WinJS.UI.setOptions(listview, { layout: { type: WinJS.UI.ListLayout } }) } if (malfiGlobals.currentLocation.name !== "Views") { resultArray.sort(function (a, b) { var nameA = a.baseTypeId.toLowerCase(), nameB = b.baseTypeId.toLowerCase() if (nameA < nameB) //sort string ascending return 1 if (nameA > nameB) return -1 return 0 //default return value (no sorting) }) } var _listview = document.getElementById("basicListview").winControl; var _dataSource = _listview.itemDataSource; _dataSource.beginEdits(); if (listViewNamespace.itemList._keys === null) { var arr = []; for (var i in listViewNamespace.itemList._keyMap) { arr.push(i); } listViewNamespace.itemList._keys = arr; } for (var i = 0; i < _listview._selection._selected._itemsCount; i++) { _dataSource.remove(_dataSource._list._keys[0]); } if (bool === true) { malfiGlobals.displayedItemsArray.splice(0, malfiGlobals.displayedItemsArray.length); } if (resultArray !== undefined) { resultArray.forEach(function (element, index, resultArray) { _dataSource.insertAtEnd(null, element); }); _dataSource.endEdits(); var defdef = $.Deferred(); if (resultArray.length === 0) { renderNewItems([{ name: 'No files found', id: 'emptiness', objectTypeId: 'icon' }]) defdef.resolve(); } for (var loop = 0; loop < resultArray.length; loop++) { listViewNamespace.itemList.setAt(loop, resultArray[loop]); if (loop === resultArray.length - 1) { defdef.resolve(); } } defdef.done(function () { if (malfiGlobals.currentPath.backSteps > 1) { malfiGlobals.currentPath.backSteps-- menuSwitchHandler('back'); var locationPath = document.getElementById("locationPath") locationPath.scrollLeft = locationPath.scrollWidth; window.toggleButtons(false); } else { var locationPath = document.getElementById("locationPath") locationPath.scrollLeft = locationPath.scrollWidth; locationPath.draggable = true document.getElementById('loadingProgress').style.visibility = "hidden"; basicListview.winControl.itemDataSource = listViewNamespace.itemList.dataSource; document.getElementById('basicListview').style.visibility = "visible"; window.toggleButtons(false); malfiGlobals.loadingInProgress = false; } }); } } window.rerenderCurrentFolder = function () { var def = $.Deferred(); malfiGlobals.session[malfiGlobals.invokedDiv].getObjectChildren(malfiGlobals.currentLocation.id, '', def); def.done(function (resultArray) { var _listview = document.getElementById("basicListview").winControl; var _dataSource = _listview.itemDataSource; _dataSource.beginEdits(); for (var i = 0; i < _listview._selection._selected._itemsCount; i++) { _dataSource.remove(_dataSource._list._keys[0]); } resultArray.forEach(function (element, index, resultArray) { _dataSource.insertAtEnd(null, resultArray[index]); }); _dataSource.endEdits(); var defdef = $.Deferred(); if (resultArray.length === 0) { defdef.resolve(); } for (var loop = 0; loop < resultArray.length; loop++) { listViewNamespace.itemList.setAt(loop, resultArray[loop]); if (loop === resultArray.length - 1) { defdef.resolve(); } } defdef.done(function () { document.getElementById('loadingProgress').style.visibility = "hidden"; basicListview.winControl.itemDataSource = listViewNamespace.itemList.dataSource; document.getElementById('basicListview').style.visibility = "visible"; window.toggleButtons(false); malfiGlobals.loadingInProgress = false; }); }) } function clickPathItem(eventObj) { if (malfiGlobals.loadingInProgress === false) { window.toggleButtons(true); malfiGlobals.loadingInProgress = true; malfiGlobals.currentPath.backSteps = malfiGlobals.currentPath.history - eventObj.currentTarget.id.slice(eventObj.currentTarget.id.length - 1, eventObj.currentTarget.id.length); if (malfiGlobals.currentPath.backSteps > 0) { menuSwitchHandler('back'); } else { window.toggleButtons(false); malfiGlobals.loadingInProgress = false; } } } function itemTemplateFunction(itemPromise) { return itemPromise.then(function (item) { if (malfiGlobals.gridView === false) { var div = document.createElement("div"); div.className = "mediumListIconTextItem"; div.setAttribute("style", "width: 100%"); var childDiv = document.createElement("div"); childDiv.className = "mediumListIconTextItem-Detail"; var title = document.createElement("h2"); if (item.data.objectTypeId === "F:st:sites" || item.data.objectTypeId === "F:st:site" || item.data.name === "Sites") { title.innerText = "\uE12B" + " " + item.data.name; } else if (item.data.baseTypeId === "cmis:folder" || item.data.name === "Repository" || item.data.objectTypeId === "cmis:folder") { title.innerText = "\uE188" + " " + item.data.name; } else if (item.data.name === "My Files") { title.innerText = "\uE13D" + " " + item.data.name; } else if (item.data.name === "Shared Files") { title.innerText = "\uE125" + " " + item.data.name; } else if (item.data.name === "Activities") { title.innerText = "\uE136" + " " + item.data.name; } else if (item.data.name === "My Tasks") { title.innerText = "\uE10B" + " " + item.data.name; } else if (item.data.name === "Favorites") { title.innerText = "\uE113" + " " + item.data.name; } else if (item.data.name === 'No files found') { title.innerText = item.data.name; } else { title.innerText = "\uE130" + " " + item.data.name; } title.setAttribute("style", "display: inline-block; padding: 0px 5px 5px 5px; white-space: nowrap; text-overflow: ellipsis; width: 100%; overflow: hidden;"); childDiv.appendChild(title); div.appendChild(childDiv); return div; } else { var div = document.createElement("div"); div.className = "mediumListIconTextItem"; div.setAttribute("style", "padding: 0px;"); var childDiv = document.createElement("div"); childDiv.className = "mediumListIconTextItem-Detail"; var iconColor = window.getComputedStyle(document.body).color; var borderColor = window.getComputedStyle(document.body).borderColor; childDiv.setAttribute("style", "width: 150px; height: 150px; overflow: hidden; border-width: 2px; border-color: " + borderColor + "; border-style: solid;") var icon = document.createElement("p"); icon.setAttribute("style", "color: " + iconColor + ";font-size: 112px; position:absolute; left: 5px; top: -120px;") if (item.data.objectTypeId === "F:st:sites" || item.data.objectTypeId === "F:st:site" || item.data.name === "Sites") { icon.innerText = "\uE12B"; icon.setAttribute("style", "color: " + iconColor + ";font-size: 112px; position:absolute; left: 5px; top: -120px;") } else if (item.data.baseTypeId === "cmis:folder" || item.data.name === "Repository") { icon.innerText = "\uE188"; } else if (item.data.name === "My Files") { icon.innerText = "\uE13D"; } else if (item.data.name === "Shared Files") { icon.innerText = "\uE125"; } else if (item.data.name === "Activities") { icon.innerText = "\uE136"; } else if (item.data.name === "My Tasks") { icon.innerText = "\uE10B"; } else if (item.data.name === "Favorites") { icon.innerText = "\uE113"; } else { icon.innerText = "\uE130"; } childDiv.appendChild(icon) var title = document.createElement("h3"); title.innerText = item.data.name; title.setAttribute("style", "position: absolute; bottom: 5px; left: 10px;") childDiv.appendChild(title); div.appendChild(childDiv); return div; } }); }; WinJS.Namespace.define("TemplatingExample", { itemTemplateFunction: itemTemplateFunction }); WinJS.Utilities.markSupportedForProcessing(TemplatingExample.itemTemplateFunction); })();
/*------------------- a player entity -------------------------------- */ game.PlayerEntity = me.ObjectEntity.extend({ /* ----- constructor ------ */ init: function(x, y, settings) { // call the constructor this.parent(x, y, settings); // set the default horizontal & vertical speed (accel vector) this.setVelocity(0.35, 0.35); this.setMaxVelocity(3.5, 3.5); this.setFriction(0.05, 0.05); // adjust the bounding box // lower half SNES-RPG style this.updateColRect(0, 32, 32, 32); // set the display to follow our position on both axis me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); }, /* ----- update the player pos ------ */ update: function() { if (me.input.isKeyPressed('left')) { // flip the sprite on horizontal axis this.flipX(true); // update the entity velocity this.vel.x -= this.accel.x * me.timer.tick; } else if (me.input.isKeyPressed('right')) { // unflip the sprite this.flipX(false); // update the entity velocity this.vel.x += this.accel.x * me.timer.tick; } else { this.vel.x = 0; } if (me.input.isKeyPressed('up')) { // TODO - show up sprite // update the entity velocity this.vel.y -= this.accel.y * me.timer.tick; } else if (me.input.isKeyPressed('down')) { // TODO - show down sprite // update the entity velocity this.vel.y += this.accel.y * me.timer.tick; } else { this.vel.y = 0; } /* if (me.input.isKeyPressed('jump')) { // make sure we are not already jumping or falling if (!this.jumping && !this.falling) { // set current vel to the maximum defined value // gravity will then do the rest this.vel.y = -this.maxVel.y * me.timer.tick; // set the jumping flag this.jumping = true; } } */ // check & update player movement this.updateMovement(); // update animation if necessary if (this.vel.x!=0 || this.vel.y!=0) { // update object animation this.parent(); return true; } // else inform the engine we did not perform // any update (e.g. position, animation) return false; } }); game.ChaserEntity = me.ObjectEntity.extend({ /* ----- constructor ------ */ target: null, myPath: [], dest: null, lastPos: {x: -1, y: -1}, pathAge: 0, init: function(x, y, settings) { // call the constructor this.parent(x, y, settings); // chase even when offscreen this.alwaysUpdate = true; // set the default horizontal & vertical speed (accel vector) this.setVelocity(0.25, 0.25); this.setMaxVelocity(3, 3); this.setFriction(0.05, 0.05); // adjust the bounding box // lower half SNES-RPG style console.log(this.collisionBox); this.updateColRect(0, 32, 32, 32); }, chessboard: function() { // return chessboard distance to target return Math.max( Math.abs(this.collisionBox.left - this.target.collisionBox.left), Math.abs(this.collisionBox.top - this.target.collisionBox.top)); }, /* ----- update the player pos ------ */ update: function() { var now = Date.now() this.updateColRect(0, 16, 16, 16); if (this.target == null) { // we should globally store this value this.target = me.game.getEntityByName('mainPlayer')[0]; } var cbdist = this.chessboard(); if (this.myPath.length < 1 || (cbdist >= 96 && this.pathAge+5000 < now)) { // not moving anywhere // friction takes over if (this.target != null) { this.myPath = me.astar.search(this.collisionBox.left,this.collisionBox.top,this.target.collisionBox.left,this.target.collisionBox.top); this.dest = this.myPath.pop(); this.pathAge = now; //console.log(this.dest); } } else { if (this.chessboard() < 96) { // just go for it this.dest = this.target; this.pathAge = now-5000; } else if (this.collisionBox.overlaps(this.dest.rect) && this.myPath.length > 0) { // TODO - do this with non constant, add some fuzz factor //console.log("Reached "+this.dest.pos.x+","+this.dest.pos.y); this.dest = this.myPath.pop(); } if (this.dest != null) { //console.log("@",this.collisionBox.pos.x,this.collisionBox.pos.y); //console.log("Moving toward ",this.dest.pos.x,this.dest.pos.y); // move based on next position var xdiff = this.dest.pos.x - this.collisionBox.left , ydiff = this.dest.pos.y - this.collisionBox.top; if (xdiff < -2) { this.vel.x -= this.accel.x * me.timer.tick; this.lastPos.x = this.left; } else if (xdiff > 2) { this.flipX(true); this.vel.x += this.accel.x * me.timer.tick; this.lastPos.x = this.left; } if (ydiff < -2) { this.vel.y -= this.accel.y * me.timer.tick; this.lastPos.y = this.collisionBox.pos.y; } else if (ydiff > 2) { this.vel.y += this.accel.y * me.timer.tick; this.lastPos.y = this.collisionBox.pos.y; } } } // check & update player movement this.updateMovement(); // update animation if necessary if (this.vel.x!=0 || this.vel.y!=0) { // update object animation this.parent(); return true; } // else inform the engine we did not perform // any update (e.g. position, animation) return false; }, draw: function(context) { // draw the sprite if defined if (this.renderable) { // translate the renderable position (relative to the entity) // and keeps it in the entity defined bounds // anyway to optimize this ? var x = ~~(this.pos.x + (this.anchorPoint.x * (this.width - this.renderable.width))); var y = ~~(this.pos.y + (this.anchorPoint.y * (this.height - this.renderable.height))); context.translate(x, y); this.renderable.draw(context); context.translate(-x, -y); } // draw dest rect debugAStar = true; if (debugAStar && this.dest) { if (this.dest && this.dest.rect) { this.dest.rect.draw(context, "green"); } for (var i = 0, ii = this.myPath.length; i < ii; i+=1) { if (this.myPath[i] && this.myPath[i].rect) { this.myPath[i].rect.draw(context, "red"); } } } } });
const schoolScheduleUI = require('./SchoolScheduleUI') const facultyUI = require('./FacultyUI') const studentUI = require('./StudentUI') const enrollmentUI = require('./EnrollmentUI') const personUI = require('./PersonUI') const schoolUI = require('./SchoolUI') const enrollmentScheduleUI = require('./EnrollmentScheduleUI') class ModuleHelper { allUI = []; constructor() { this.allUI.push(schoolScheduleUI) this.allUI.push(facultyUI) this.allUI.push(studentUI) this.allUI.push(enrollmentUI) this.allUI.push(personUI) this.allUI.push(schoolUI) this.allUI.push(enrollmentScheduleUI) } async getAutoComplete(request, callback) { let widgetFound = false; let widget = null; for (let ui of this.allUI) { const widgetName = request.params.widget; if (ui.constructor.name == widgetName) { widgetFound = true; widget = ui; break; } } if (widgetFound) { widget.getAutoComplete(request, callback) } else { throw new Error(`Widget not found [${request.query.widget}] `) } } async getAutoCompleteLabel(request, callback) { let widgetFound = false; let widget = null; for (let ui of this.allUI) { const widgetName = request.params.widget; if (ui.constructor.name == widgetName) { widgetFound = true; widget = ui; break; } } if (widgetFound) { widget.getAutoCompleteLabel(request, callback) } else { throw new Error(`Widget not found [${request.query.widget}] `) } } async getPWidget(request, callback) { let widgetFound = false; let widget = null; for (let ui of this.allUI) { const widgetName = request.query.widget; if (ui.constructor.name == widgetName) { widgetFound = true; widget = ui; break; } } if (widgetFound) { widget.getPWidget(request, callback) } else { throw new Error(`Widget not found [${request.query.widget}] `) } } async getWidget(request, callback) { let widgetFound = false; let widget = null; for (let ui of this.allUI) { const widgetName = request.params.widget; if (ui.constructor.name == widgetName) { widgetFound = true; widget = ui; break; } } if (widgetFound) { widget.getWidget(request, callback) } else { throw new Error(`Widget not found [${request.params.widget}] `) } } async getLeftMenu(user, callback) { let leftMenus = []; const roles = JSON.stringify(user.roles) if (roles.includes("SCHOOL STAFF")) { leftMenus.push(facultyUI.getLeftMenu(user)) leftMenus.push(studentUI.getLeftMenu(user)) leftMenus.push(schoolScheduleUI.getLeftMenu(user)) leftMenus.push(enrollmentUI.getLeftMenu(user)) } callback(leftMenus) } } const moduleHelper = new ModuleHelper(); module.exports = moduleHelper;
function setup() { createCanvas(600,600); noLoop(); angleMode(DEGREES); // Change the mode to DEGREES } // TODO weird edges can possibly be avoided if the entire pitch can be drawn rectangle by rectangle (instead entire 12 shapes) function pitchSegment(pitchVolsList, width, x, y, height) { // rectangles filled with different colors for each pitch (initialise a color scheme) colors = ['#c37263', '#e87d85', '#ff7b59', '#e59741', '#f4bf13', '#288c4e', '#be6075', '#52789b', '#76d5e4', '#95bca8', '#7a9597', '#6a6f80'] // fill transparency determined by pitch volume (need to setAlpha if color string is used) // width determined by segment duration; length of each will be sectionWidth/12 // height determined by total song length? for (let j = 0; j < pitchVolsList.length; j++){ c = color(colors[j]); c.setAlpha(255*(1-pitchVolsList[j])); stroke(c); fill(c); // how to make rectangles not overlapping? rect(x+j*width, y, width, height); } } function draw() { let paddingSide = 30; let x = 0; let y = 0; let t = 0; let cWidth = 600; let cHeight = 600; songDuration = track_duration; // because longer songs look nicer with very thin lines? (but this makes the print rather small) if (songDuration > 240) { var secondsPerRow = 2; } else{ var secondsPerRow = 3; } //const secondsPerRow = 1; const nRows = Math.ceil(songDuration/secondsPerRow); // think about how these 2 variables change dep on length of song, these should be more dynamic const pixelsPerSecond = (cHeight - 2*paddingSide )/secondsPerRow; const rowHeight = (cHeight - 2*paddingSide )/ nRows; let timeInRow = 0; //let totalTime = 0; console.log(pitch_segments.length); for (let i=0; i < pitch_segments.length; i++) { // segment width is proportional to duration segmentWidth = durations[i]*pixelsPerSecond; //console.log(`i: ${i}, duration: ${durations[i]}, totalTime: ${totalTime}`); pitchSegment(pitch_segments[i], segmentWidth/12, x+paddingSide, y+paddingSide, rowHeight); timeInRow += durations[i]; //totalTime += durations[i]; x = timeInRow*pixelsPerSecond; // need to figure out way to calculate border if (x > cWidth) { x = 0; timeInRow = 0; y += rowHeight; } } }
'use strict'; var javascirpt = require("../javaScirpt.js"); var grunt = require('grunt'); var path = require('path'); var fs = require("fs"); var runTest = function(jsFile, test) { var content = fs.readFileSync("tests/" + jsFile); var jsonContent = JSON.parse(content); for(var i in jsonContent.tests) { var codeblock = jsonContent.tests[i]; console.log("testing " + codeblock.description); var results = javascirpt.run(codeblock.original) test.equal(results.succeeded, true); test.equal(codeblock.transformed.replace(/\s+/g, " "), results.text.replace(/\s+/g, " ")); } test.done(); } exports.nodeunit = { keywords: function(test) { runTest("keywords.json", test); }, brackets: function(test) { runTest("brackets.json", test); }, varnames: function(test) { runTest("varnames.json", test); } }
import fetch from 'isomorphic-fetch'; import { API_PATH_PREFIX } from '../constants'; export const CHECKING_USERNAME_REMOTE = 'CHECKING_USERNAME_REMOTE'; export const VALIDATE_USERNAME = 'VALIDATE_USERNAME'; const BAD_USERNAME_MSG = 'Username must be between 4 and 15 chars, start with a letter and must consist of only letters, numbers and underscores.'; const checkingUsernameRemote = (username) => { return { type: CHECKING_USERNAME_REMOTE, value: username, validationState: 'warning' }; } const invalidResponse = (username) => { return { type: VALIDATE_USERNAME, validationMessage: BAD_USERNAME_MSG, value: username, validationState: 'error' }; } export const checkUsername = (username) => { if (username.match(/[a-z]+([a-z0-9_]){3,14}/) == null) { return (dispatch) => dispatch(invalidResponse(username)); } else { return (dispatch) => { dispatch(checkingUsernameRemote(username)); return fetch(`${API_PATH_PREFIX}/users/name/${username}`).then(response => dispatch(processRemoteResponse(response, username))); } } } const processRemoteResponse = (response, username) => { if (response.status == 400) { return { type: VALIDATE_USERNAME, validationMessage: BAD_USERNAME_MSG, value: username, validationState: 'error' }; } else if (response.status == 200) { return { type: VALIDATE_USERNAME, validationMessage: `${username} is already in use`, value: username, validationState: 'warning' }; } else { return { type: VALIDATE_USERNAME, validationMessage: 'Available!', value: username, validationState: 'success' }; } }
var Device = require("./models/device"); var DeviceManager = function(server) { this.server = server; this.config = server.config; this.devices = {}; } module.exports = DeviceManager; DeviceManager.prototype.start = function(){ var self = this; this.server.subscribe("device.hereiam", function(msg, env){ self.onDeviceLogin(msg,env); }); this.server.subscribe("device.goodbye", function(msg, env){ self.onDeviceLogout(msg,env); }); this.server.subscribe("device.reading", function(msg, env){ self.onDeviceReading(msg.deviceId,msg.command,msg.arguments); }); this.server.subscribe("device.command", function(msg, env){ self.onDeviceCommand(msg.deviceId,msg.command); }); self.server.log("Device Manager reporting for duty, friend"); } DeviceManager.prototype.onDeviceLogin = function(msg,env){ var maker = msg.arguments[0] , model = msg.arguments[1] , version = msg.arguments[2] this.loginDevice(msg.deviceId,maker,model,version); } DeviceManager.prototype.onDeviceLogout = function(msg,env){ this.logoutDevice(msg.deviceId); } DeviceManager.prototype.loginDevice = function(id,makerId,modelId,versionId){ var self = this; this.findOrCreateDevice(id, makerId, modelId, versionId, function(err, device){ if (err){ self.server.publish("error",err); } else { if (!device.version.id == versionId){ device.upgradeTo(version); } device.login(); self.server.log("Login: " + device.toString()); } }); } DeviceManager.prototype.logoutDevice = function(id) { var self = this; this.findDevice(id, function(err, device){ if (device) { device.logout(); self.server.log("Logout: " + device.toString()); } else { self.server.log("Logout: " + id + " (Unknown)"); } }); } DeviceManager.prototype.onDeviceReading = function(deviceId, commandId, args){ var self = this; this.findDevice(deviceId, function(err, device){ if (!device) { var err = "Received a reading from an unknown device:" + deviceId + ". The command was: " + commandId + " " + JSON.stringify(args); self.server.publish("error",{message:err, deviceId:deviceId, command:commandId, arguments:args}); } else { device.addReading(commandId, args); } }); } DeviceManager.prototype.onDeviceCommand = function(deviceId, commandData){ var self = this; this.findDevice(deviceId, function(err, device){ if (!device){ var err = "Received a command for an unknown device:" + deviceId + ". The command was:" + JSON.stringify(commandData); self.server.pubish("error",{message:err, deviceId:deviceId,commandData:commandData}); } else { device.sendCommand(commandData); } }); } DeviceManager.prototype.findOrCreateDevice = function(deviceId, makerId, modelId, versionId, callback){ var self = this; var deviceData = { id:deviceId, makerId:makerId, modelId:modelId, versionId:versionId }; this.server.database.findOrCreateDevice(this, deviceData, function(err, device){ if(!err) self.devices[deviceId] = device; callback(err, device); }); } DeviceManager.prototype.findDevice = function(deviceId, callback) { var self = this; var device = this.devices[deviceId]; if (!device){ this.server.database.findDevice(this, deviceId,function(err,device){ if (err){ this.server.publish("error",err); } else { self.devices[deviceId] = device; callback(err, device); } }); } else { callback(null, device); } }
import React from "react" import { ButtonGroup } from "@material-ui/core" import { StyledButton, RoundedAppBar } from "./styled" import Calendar from "../assets/svgs/calendar.svg" const AppBar = ({ value, onChange }) => { return ( <RoundedAppBar position="relative" elevation={0}> <ButtonGroup disableElevation variant="contained" border={0}> <StyledButton color="primary" startIcon={<img src={Calendar} alt="logo" />} > Today </StyledButton> <StyledButton variant="text" color="#999999" onClick={() => onChange(value.clone().subtract("1", "month"))} > {String.fromCharCode(171)} </StyledButton> <StyledButton variant="text" color="#999999" borderRadius={0} width="140px" > {value.format("MMMM")} {value.format("YYYY")} </StyledButton> <StyledButton variant="text" color="#999999" borderRadius={0} onClick={() => onChange(value.clone().add("1", "month"))} > {String.fromCharCode(187)} </StyledButton> </ButtonGroup> </RoundedAppBar> ) } export default AppBar
"use strict"; var LOADING = new (function() { var _isLoading = true; var _elem = null; this.isLoading = function () { return _isLoading; }; this.init = function () { _elem = document.getElementById("game-loading-overlay"); }; this.endLoading = function () { _isLoading = false; _elem.classList.add("game-loading-fading-out"); setTimeout(function() { _elem.style.display = "none"; }, 1000); }; })();
import CONSTANTS from '@/utils/interfaces/constants'; const REDUCER_KEY = 'MAMRelativeTest'; const API_PATH = 'mam'; const API_TYPE = 2; export const RESULT_KEY = { AP: 'ap', APR: 'apr', LOAD: 'load', PEAK_POWER: 'peakPwr', RELATIVE_POWER: 'relativePwr', RPM: 'rpm', TIME: 'time' }; export const LABELS = { [RESULT_KEY.AP]: 'МАМ, Вт', [RESULT_KEY.APR]: 'Относительная МАМ, Вт/кг', [RESULT_KEY.LOAD]: 'Нагрузка, кг', [RESULT_KEY.PEAK_POWER]: 'Мощность, Вт', [RESULT_KEY.RELATIVE_POWER]: 'Относительная мощность, Вт/кг', [RESULT_KEY.RPM]: 'Скорость, об/мин', [RESULT_KEY.TIME]: 'Время, мс' }; export default CONSTANTS(REDUCER_KEY, API_PATH, API_TYPE);
import React from 'react' import PropTypes from 'prop-types' import styles from './site-title.module.scss' function SiteTitle(props) { return ( <h1 className={styles.title}>{props.children}</h1> ) } SiteTitle.propTypes = { children: PropTypes.string.isRequired } SiteTitle.defaultProps = { children: 'Site Title Component' } export default SiteTitle
const dropDownReducer = (state = 'Dominic', action) => { switch (action.type) { case 'DROP_DOWN': default: return state; } } export default dropDownReducer;
import React from 'react'; import { Row, Col,Card, Button, Icon, Divider, Message, Form, Select, Input, Table, DatePicker, Cascader} from 'antd'; import {fetch} from '../../api/tools' import {provinces, cities} from '../../constants/Area' const FormItem = Form.Item; const Option = Select.Option; const columns = [ { title: '订单号', width: 100, dataIndex: 'orderId', key: 'orderId', fixed: 'left' }, { title: '合作商订单号 ', width: 100, dataIndex: 'thirdId', key: 'thirdId', fixed: 'left' }, { title: '客户名称', dataIndex: 'userName', key: '1' }, { title: '下单渠道 ', dataIndex: 'payDownChannel', key: '2' }, { title: '支付时间', dataIndex: 'payDate', key: '3' }, { title: '支付类型', dataIndex: 'payType', key: '4' }, { title: '车牌', dataIndex: 'carNumber', key: '5' }, { title: '违章状态', dataIndex: 'preOrderStatus', key: '6' }, { title: '违章时间', dataIndex: 'occurTime', key: '7' }, { title: '违章地点', dataIndex: 'location', key: '8' }, { title: '违章城市', dataIndex: 'locationName', key: '9' }, { title: '违章原因', dataIndex: 'reason', key: '10' }, { title: '扣分', dataIndex: 'degree', key: '11' }, { title: '罚金', dataIndex: 'fine', key: '12' }, { title: '代办费', dataIndex: 'poundage', key: '13' }, { title: '订单金额', dataIndex: 'amount', key: '14' }, { title: '订单优惠', dataIndex: 'disCount', key: '15' }, { title: '应付金额', dataIndex: 'customerPay', key: '16' }, { title: '退款', dataIndex: 'refundMoney', key: '17' }, { title: '退款时间', dataIndex: 'refundTime', key: '18' }, { title: '退款说明', dataIndex: 'refundRemark', key: '19' }, { title: '文书号', dataIndex: 'documentCode', key: '20' }, { title: '创建时间', dataIndex: 'createDate', key: '21' }, { title: '订单状态', dataIndex: 'status', key: '22' }, { title: '违章编号', dataIndex: 'historyID', key: '23' }, { title: '违章代码', key: 'operation', fixed: 'right', width: 100, }, ]; class OrderChecking extends React.Component { state = { activeIndex: 0, data:[], total:0, current: 1 }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { let beginDate = values.beginDate && values.beginDate.format('YYYY-MM-DD')||'' let endDate = values.endDate && values.endDate.format('YYYY-MM-DD')||'' this.setState({beginDate: beginDate, endDate: endDate, carNumber: values.carNumber, dateType: values.dateType, orderId: values.orderId, preOrderStatus: values.preOrderStatus}) this.fetchOrderList(1,beginDate, endDate, values.carNumber, values.dateType, values.orderId, values.preOrderStatus) } }); }; onChange = (value) =>{ // console.log(value); } componentDidMount(){ cities.forEach(city => { const matchProvince = provinces.filter( province => province.code === city.provinceCode )[0]; if (matchProvince) { matchProvince.children = matchProvince.children || []; matchProvince.children.push({ label: city.name, value: city.code, }); } }); const options = provinces.map(province => ({ label: province.name, value: province.code, children: province.children })); this.setState({options: options}) } // 获取违章订单明细 fetchOrderList(current, beginDate, endDate, carNumber='', dateType='', orderId='', preOrderStatus=''){ if(!beginDate){ Message.error('请选择开始日期') return } if(!endDate){ Message.error('请选择结束日期') return } fetch('get',`/usercenter/transaction/violation-order-detail-list?shopServiceId=${this.props.shopServiceId} &beginDate=${beginDate}&endDate=${endDate}&carNumber=${carNumber}&current=${current}&dateType=${dateType} &locationId=${this.state.locationId||''}&orderId=${orderId}&preOrderStatus=${preOrderStatus}&size=10`).then(res=>{ if(res.code == 0){ let list = res.data.records list.forEach((item)=>{ let preOrderStatus = item.preOrderStatus let status = item.status for( let i of orderType){ if(i.key == preOrderStatus){ item.preOrderStatus = i.name } if(i.key == status){ item.status = i.name } } }) this.setState({data: list, total: res.data.total, current: current}) } else{ res.msg ? Message.error(res.msg) : Message.error('查询错误') } }) } fetchMore = (page,pageSize) =>{ this.fetchOrderList(page.current, this.state.beginDate,this.state.endDate, this.state.carNumber, this.state.dateType, this.state.orderId,this.state.preOrderStatus) } onChange = (value) =>{ this.setState({locationId: value[1]}) } render() { const { getFieldDecorator} = this.props.form; return ( <div> <Form layout="inline" onSubmit={this.handleSubmit} > <FormItem> {getFieldDecorator('orderId', { rules: [], })( <Input style={{width: '150px'}} placeholder="请输入订单号" /> )} </FormItem> <FormItem> <Cascader options={this.state.options} expandTrigger="hover" onChange={this.onChange} style={{ width: 150 }} placeholder="请选择违章城市" /> {/*{getFieldDecorator('locationId', {*/} {/*rules: [],*/} {/*})(*/} {/*<Input style={{width: '150px'}} placeholder="请输入违章城市" maxLength={7} />*/} {/*)}*/} </FormItem> <FormItem> {getFieldDecorator('carNumber', { rules: [], })( <Input style={{width: '150px'}} placeholder="请输入车牌" maxLength={7} /> )} </FormItem> <FormItem> {getFieldDecorator('dateType', { rules: [], })( <Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择日期类型"> {dateType.map((item,index)=> <Option value={item.key} key={index}>{item.name}</Option> )} </Select> )} </FormItem> <FormItem> {getFieldDecorator('preOrderStatus', { rules: [], })( <Select dropdownMatchSelectWidth={false} allowClear={true} placeholder="请选择订单状态"> {orderType.map((item,index)=> <Option value={item.key} key={index}>{item.name}</Option> )} </Select> )} </FormItem> <FormItem> {getFieldDecorator('beginDate', { rules: [], })( <DatePicker placeholder={'请选择起始日期'}/> )} </FormItem> <FormItem> {getFieldDecorator('endDate', { rules: [], })( <DatePicker placeholder={'请选择结束日期'}/> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit" > 查询 </Button> </FormItem> </Form> <Table className='mt15' columns={columns} dataSource={this.state.data} scroll={{ x: 2600 }} pagination={{total: this.state.total, current: this.state.current}} onChange={(page,pageSize)=>{this.fetchMore(page,pageSize)}} /> </div> ); } } const dateType = [ {key:0,name:'订单日期'}, {key:1,name:'支付日期'}, {key:2,name:'完成日期'}, {key:3,name:'退款日期'}, {key:4,name:'主订单完成日期'}, ] const orderType = [ {key:'NeedPay',name:'待付款'}, {key:'Deleted',name:'已删除'}, {key:'Payed',name:'已付款'}, {key:'Proceccing',name:'正在办理'}, {key:'Drawbacked',name:'已退款'}, {key:'Finished',name:'已完成'}, ] export default Form.create()(OrderChecking);
describe("Tabset", function() { var originalHtml = null; beforeEach(function() { originalHtml = $("#fixture4").html(); }); afterEach(function() { $("#fixture4").html(originalHtml); }); describe("Creating a new tabset", function() { it("Hides all tab panels except for the first", function() { var container = $("#tabs"); var tabset = new kitty.Tabset(container); expect($("#panel1").hasClass("hide")).toBe(false); expect($("#panel2").hasClass("hide")).toBe(true); expect($("#panel3").hasClass("hide")).toBe(true); expect($("a[href$='#panel1']").hasClass("active")).toBe(true); }); }); describe("Activating a panel", function() { it("Hides the active panel and displays the new panel", function() { var container = $("#tabs"); var tabset = new kitty.Tabset(container); $("a[href$='#panel2']").trigger("click"); expect($("#panel1").hasClass("hide")).toBe(true); expect($("#panel2").hasClass("hide")).toBe(false); }); it("Highlights the tab link and unhighlights previously active link", function() { var container = $("#tabs"); var tabset = new kitty.Tabset(container); var link2 = $("a[href$='#panel2']"); var link3 = $("a[href$='#panel3']"); link2.click(); expect(link2.hasClass("active")).toBe(true); link3.click(); expect(link2.hasClass("active")).toBe(false); }); }); describe("Destroying a tabset", function() { it("Removes the events from the tab links", function() { var container = $("#tabs"); var tabset = new kitty.Tabset(container); tabset.destroy(); var link2 = $("a[href='#panel2']"); link2.click(); // inspecting DOM to see if event was fired, but could have spyOn(tabset, "handleLink_onClick") // and check if called instead expect(link2.hasClass("active")).toBe(false); }); it("Displays all the panels", function() { var container = $("#tabs"); var tabset = new kitty.Tabset(container); tabset.destroy(); expect($("#panel1").hasClass("hide")).toBe(false); expect($("#panel2").hasClass("hide")).toBe(false); expect($("#panel3").hasClass("hide")).toBe(false); }); }); });
var assert = require('assert'); var test = require('../../src/document_writer'); function run(i) { var DW = function() { test.DocumentWriter.apply(this, arguments); }; DW.prototype = Object.create(test.DocumentWriter.prototype); DW.prototype.constructor = DW; var dw = new DW(); var len = dw._doc.elements.paths.length; dw.path(i.corners, i.fill, i.stroke, i.strokeWidth); return dw._doc.elements.paths.length != len; } // TODO simplify it describe('document_writer', function() { describe('path', function() { it('should add path only if path is valid', function() { // valid assert.equal(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); // invalid corners assert.equal(false, run({ corners: null, fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.equal(false, run({ corners: [{x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.equal(false, run({ corners: [{x: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.equal(false, run({ corners: [{x: 1, y: 1}, {y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.equal(false, run({ corners: [null, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.equal(false, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, undefined], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); // invalid fill assert.equal(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: null, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {g: 1}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {b: 1}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 1 })); // invalid stroke assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: null, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 1}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 1}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {g: 1}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {b: 1}, strokeWidth: 1 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: 0 })); assert.deepEqual(true, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1, g: 2, b: 3}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: -3 })); // invalid fill + stroke assert.deepEqual(false, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1}, stroke: null, strokeWidth: 0 })); assert.deepEqual(false, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: {r: 1}, stroke: {r: 4, g: 5, b: 6}, strokeWidth: -2 })); assert.deepEqual(false, run({ corners: [{x: 1, y: 1}, {x: 2, y: 2}, {x: 1, y: 2}], fill: null, stroke: null, strokeWidth: -3 })); }); }); });
var app = getApp(); Page({ data: { addIsShow:false }, onLoad: function (options) { }, onShow: function () { var that = this; // 获取项目、班组 app.wxRequest("gongguan/api/wechat/getEmergencyContacts", {}, "post", function (res) { console.log("联系人列表:", res.data.data) if (res.data.code == 0) { that.setData({ perList:res.data.data }) } else { app.showLoading(res.data.msg, "none"); } }) }, onHide: function () { }, getName:function(e){ this.setData({ name:e.detail.value }) }, getPhone:function(e){ this.setData({ phone: e.detail.value }) }, getRelation: function (e) { this.setData({ relation: e.detail.value }) }, // 添加联系人页面显示 addShow:function(){ this.setData({ addIsShow:true }) wx.setNavigationBarTitle({ title: '新建联系人' }) }, // 确认 footerTap:function(){ var that = this; let name = that.data.name; let phone = that.data.phone; let relation = that.data.relation; app.wxRequest("gongguan/api/wechat/addEmergencyConstact", { name:name, phone:phone, relation: relation }, "post", function (res) { console.log("联系人列表:", res.data.data) if (res.data.code == 0) { if( res.data.data ){ wx.showToast({ title: '添加成功', icon: 'success', duration: 1000 }) that.setData({ addIsShow:false }) that.onShow(); } } else { app.showLoading(res.data.msg, "none"); } }) } })
import is from '../utils/is.js' import Node from './node.js' import Link from './link.js' class RhytonThree { constructor(cfg) { if (is.object(cfg)) { if (!cfg.el) { console.log('未设置画布容器'); return } this.el = cfg.el; if (is.object(cfg.camera)) { this.cameraCfg = cfg.camera; } this.initScene(); this.initCamera(); this.initRenderer(); this.initRaycaster(); this.initEvent(); this.initFloorPanel(); this.nodes = []; this.links = []; this.offset = new THREE.Vector3(); this.controls = new THREE.TrackballControls(this.camera); //旋转速度 this.controls.rotateSpeed = 1.0; //变焦速度 this.controls.zoomSpeed = 1.2; //平移速度 this.controls.panSpeed = 0.8; //是否不变焦 this.controls.noZoom = false; //是否不平移 this.controls.noPan = false; //可能是惯性 true没有惯性 this.controls.staticMoving = false; //动态阻尼系数 就是灵敏度 this.controls.dynamicDampingFactor = 0.3; var axes = new THREE.AxisHelper(100); this.scene.add(axes); } else { console.log('没有配置项'); } } //初始化场景 initScene() { this.scene = new THREE.Scene(); var directionalLight = new THREE.DirectionalLight( 0xffffff, 1 ); directionalLight.position.set(0,0,100); this.scene.add( directionalLight ); var ambiColor = "#0c0c0c"; var ambientLight = new THREE.AmbientLight(ambiColor);//设置颜色 this.scene.add(ambientLight); // this.scene.background = new THREE.Color( 0xf0fff0 ); } //初始化相机 initCamera() { if (!is.object(this.cameraCfg)) { this.camera = new THREE.PerspectiveCamera(70, document.querySelector(this.el).clientWidth / document.querySelector(this.el).clientHeight, 1, 10000); } else { var fov = this.cameraCfg.fov ? this.cameraCfg.fov : 70, ratio = this.cameraCfg.ratio ? this.cameraCfg.ratio : document.querySelector(this.el).clientWidth / document.querySelector(this.el).clientHeight, near = this.cameraCfg.near ? this.cameraCfg.near : 1, far = this.cameraCfg.far ? this.cameraCfg.far : 10000; this.camera = new THREE.PerspectiveCamera(fov, ratio, near, far); } this.camera.position.z = 100; this.camera.lookAt(new THREE.Vector3(0, 0, 0)); } //初始化渲染器 initRenderer() { var webGLRenderer = new THREE.WebGLRenderer({ antialias: true }); // webGLRenderer.setClearColor(new THREE.Color(0xEEEEEE, 1.0)); webGLRenderer.setSize(document.querySelector(this.el).clientWidth, document.querySelector(this.el).clientHeight); webGLRenderer.shadowMapEnabled = true; webGLRenderer.sortObjects = false; this.renderer = webGLRenderer; document.querySelector(this.el).appendChild(webGLRenderer.domElement); } //初始化raycaster initRaycaster() { this.raycaster = new THREE.Raycaster(); } initFloorPanel() { var plane = new THREE.Mesh(new THREE.PlaneGeometry(2000, 2000, 8, 8), new THREE.MeshBasicMaterial({ color: 0x000000, opacity: 0.01, transparent: true, wireframe: true })); plane.visible = true; this.plane = plane; this.scene.add(plane); } addNode(nodeInfo) { var node = new Node(nodeInfo).group; this.scene.add(node); this.nodes.push(node); } removeNode(node) { this.scene.remove(node); var index = this.nodes.indexOf(node); this.nodes.splice(index, 1); } removeAllNodes() { var childeren = this.scene.children.filter((v, i) => { return v.type === 'Group'; }); children.forEach((v, i) => { this.scene.remove(v) }) } addLink(linkInfo) { var link = new Link(linkInfo).link; this.scene.add(link); this.links.push(link); } removeLink(link) { this.scene.remove(link); var index = this.links.indexOf(link); this.links.splice(index, 1); } removeAllLinks() { var childeren = this.scene.children.filter((v, i) => { return v.type === 'link'; }); children.forEach((v, i) => { this.scene.remove(v) }) } initEvent() { this.mouse = new THREE.Vector2(); this.width = document.querySelector(this.el).clientWidth; this.height = document.querySelector(this.el).clientHeight; this.renderer.domElement.addEventListener('mousemove', this.onDocumentMouseMove.bind(this), false); this.renderer.domElement.addEventListener('mousedown', this.onDocumentMouseDown.bind(this), false); this.renderer.domElement.addEventListener('mouseup', this.onDocumentMouseUp.bind(this), false); } onDocumentMouseMove(e) { //阻止本来的默认事件,比如浏览器的默认右键事件是弹出浏览器的选项 e.preventDefault(); //mouse.x是指 鼠标的x到屏幕y轴的距离与屏幕宽的一半的比值 绝对值不超过1 //mouse.y是指 鼠标的y到屏幕x轴的距离与屏幕宽的一半的比值 绝对值不超过1 // //下面的矩形是显示器屏幕,三维空间坐标系的布局以及屏幕的二维坐标系 // // 鼠标是从 二维坐标系 // 这个点 .-------------------------------------------|-->鼠标x正半轴 // 开始算| 个 y / | // x,y | | / | // | | / | // | 三维坐标系| / | // | -------------------/-------------------->x| // | / | | // | / | | // | / | | // |__________Z_匕______|______________________| // | // 鼠标y \/ // 正半轴 var mouse = this.mouse, camera = this.camera, plane = this.plane, offset = this.offset; mouse.x = (e.clientX / window.innerWidth) * 2 - 1; mouse.y = - (e.clientY / window.innerHeight) * 2 + 1; //新建一个三维变换半单位向量 假设z方向就是0.5,这样我左右移的时候,还会有前后移的效果 var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5); //屏幕和场景转换工具根据照相机,把这个向量从屏幕转化为场景中的向量 // projector.unprojectVector( vector, camera ); vector.unproject(camera); //vector.sub( camera.position ).normalize()变换过后的向量vector减去相机的位置向量后标准化 //新建一条从相机的位置到vector向量的一道光线 var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); //是否有东西被选中 if (this.selected) { //有的话取到这条光线射到的物体所在水平面上所有相交元素的集合,所以这样就可以限制每次拖动距离不能超出水平面panel var intersects = raycaster.intersectObject(plane); //这个鼠标点中的点的位置减去偏移向量,新位置赋值给选中物体 if (intersects.length > 0) { this.selected.position.copy(intersects[0].point.sub(offset)); } this.updateLinks(); return; } //否则的话,光线和所有物体相交,返回相交的物体 var intersects = raycaster.intersectObjects(this.nodes, true); //如果有物体相交了 if (intersects.length > 0 && intersects[0].object.parent['_type'] === 'node') { //并且相交物体不是上一个相交物体 if (this.intersected != intersects[0].object.parent) { //将这个对象放到INTERSECTED中 this.intersected = intersects[0].object.parent; //改变水平面的位置 plane.position.copy(this.intersected.position); //并把水平面指向到相机的方向 plane.lookAt(camera.position); } //改变鼠标的样式 document.querySelector(this.el).style.cursor = 'pointer'; } else { //改变鼠标的样式 document.querySelector(this.el).style.cursor = 'auto'; } } onDocumentMouseDown(e) { //阻止本来的默认事件,比如浏览器的默认右键事件是弹出浏览器的选项 e.preventDefault(); var mouse = this.mouse, camera = this.camera, plane = this.plane, offset = this.offset; var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5); // projector.unprojectVector( vector, camera ); vector.unproject(camera); var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); var intersects = raycaster.intersectObjects(this.nodes, true); if (intersects.length > 0 && intersects[0].object.parent['_type'] === 'node') { //不能改变视角了 this.controls.enabled = false; //把选中的对象放到全局变量SELECTED中 this.selected = intersects[0].object.parent; //再和水平面相交 var intersects = raycaster.intersectObject(plane); //选中位置和水平面位置(物体中心)的偏移量 offset.copy(intersects[0].point).sub(plane.position); //改变鼠标的样式 document.querySelector(this.el).style.cursor = 'move'; } } onDocumentMouseUp(e) { e.preventDefault(); //又能改变视角了 this.controls.enabled = true; //如果有相交物体 if (this.intersected) { //把位置给水平面 this.plane.position.copy(this.intersected.position); //选中物体置空 this.selected = null; } //改变鼠标的样式 document.querySelector(this.el).style.cursor = 'auto'; } _convertTo3DCoordinate(clientX, clientY) { var mv = new THREE.Vector3( (clientX / window.innerWidth) * 2 - 1, -(clientY / window.innerHeight) * 2 + 1, 0.5); mv.unproject(this.camera); return mv; } _worldToPage(x, y, z) { var b = new THREE.Vector3(x, y, z).project(this.camera) var halfWidth = window.innerWidth / 2; var halfHeight = window.innerHeight / 2; var result = { x: Math.round(b.x * halfWidth + halfWidth), y: Math.round(-b.y * halfHeight + halfHeight) }; return result; } updateLinks() { var links = this.links, selected = this.selected, pos = this.selected.position, nid = this.selected.nid, relLinks, arrGeo; relLinks = links.filter((v, i) => { return (v.sourceId == nid || v.endId == nid) }) relLinks.forEach((v, i) => { if (v.sourceId == nid) { v.children[0].geometry.vertices[0] = new THREE.Vector3(selected.position.x, selected.position.y, selected.position.z); v.source = { x: pos.x, y: pos.y, z: pos.z } } else { v.children[0].geometry.vertices[1] = new THREE.Vector3(selected.position.x, selected.position.y, selected.position.z); v.end = { x: pos.x, y: pos.y, z: pos.z } } v.children[0].geometry.verticesNeedUpdate = true; var source = v.source, end = v.end; switch (v['_direction']) { case 'positive': case 'negative': var color = new THREE.Color(v.children[0].material.color.r, v.children[0].material.color.g, v.children[0].material.color.b); var arrowHelper = new THREE.ArrowHelper( new THREE.Vector3(-source.x+end.x,-source.y+end.y,-source.z+end.z).normalize(), new THREE.Vector3(source.x-(source.x-end.x)*2/4,source.y-(source.y-end.y)*2/4,source.z-(source.z-end.z)*2/4), 3, color,3,2 ); v.children[1] = arrowHelper; break; } }) } } export default RhytonThree
'use strict'; (function (){ angular .module("BookApp") .controller("GenreController",GenreController); function GenreController($scope, $rootScope, BookService, $routeParams, GoogleBookService) { $scope.searchBook = searchBook; $scope.renderBooks = renderBooks; function init() { var genre = $routeParams.genreName; if(genre) { searchBook(genre); } } init(); function searchBook(genre){ GoogleBookService.searchBookByGenre(genre) .success(renderBooks) } function renderBooks(response){ $scope.books = response.items; if($scope.books) { $scope.noBooks = false; } else { $scope.noBooks = true; } } } })();
import { Controller } from 'stimulus' export default class extends Controller { connect() { const attributeName = this.element.dataset.attribute const urlParts = document.location.pathname.split('/') const url = `/census/${urlParts[2]}/autocomplete?attribute=${attributeName}` $(this.element).autoComplete({ source: function(term, response) { $.getJSON(url, { term }, function(json) { response(json) }) } // onSelect: () => $(this).trigger('click') }) } disconnect() { $(this.element).autoComplete('destroy') } }
import React from 'react'; import { Helmet } from "react-helmet"; import contentAbout from '../content/contentAbout'; import MainHeader from '../components/MainHeader'; import NavBar from '../components/NavBar'; import Footer from '../components/Footer'; import FirstSteps from '../components/FirstSteps'; import OurGoals from '../components/OurGoals'; const AboutPage = () => { const { firstSteps, ourGoals } = contentAbout return ( <> <Helmet> <title>Kolekcja mody - O nas</title> </Helmet> <header> <NavBar /> <MainHeader title='O nas' /> </header> <main> <FirstSteps firstSteps={firstSteps} /> <OurGoals ourGoals={ourGoals} /> </main> <footer> <Footer /> </footer> </> ); } export default AboutPage;
const { Router } = require("express"); const { userController, transactionController, } = require("../controller/index"); const transactionModel = require("../models/transactionModel"); const transactionRouter = Router(); transactionRouter.get( "/listtransactions", userController.authorizeToken, userController.authorize, transactionController.validateListTransaction, transactionController.listTransactions ); transactionRouter.put( "/transaction", userController.authorizeToken, userController.authorize, transactionController.validateUserTransaction, transactionController.addUserTransaction ); module.exports = transactionRouter;
$(document).ready(() => { /** * PARALLAX */ let parallaxBox = $('body'); let parallaxIt = (e, target, movementX, movementY) => { let relX = e.pageX - parallaxBox.offset().left; let relY = e.pageY - parallaxBox.offset().top; gsap.to(target, 1, { x: (relX - parallaxBox.width() / 2) / parallaxBox.width() * movementX, y: (relY - parallaxBox.height() / 2) / parallaxBox.height() * movementY }); } parallaxBox.on('mousemove', (e) => { if (window.innerWidth > 1000) { parallaxIt(e, '#sun', 200, 100); } }); });
"use strict"; //Init global app let app = {}; //This is the app loader. It initiallizes all modules when the window onload event fires window.onload = function() { //Initialize the mouse so errors don't get thrown app.mouse = [0, 0]; //Initialize modules app.audio.init(); app.keys.init(); app.time.init(); app.file.init(); app.scrubber.init(); app.keybinds.init(); app.controls.init(); app.colorChanging.init(); app.image.init(); //Initialize main app.main.init(); //Bind mouse events after main //This requires that main be initialized first since it requires the canvas element to be set in the app state app.keys.bindMouse(); }
import React from "react"; import axios from 'axios'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/customInventoryTheme'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import ProductList from '../components/ProductList'; import ProductsListToolBar from '../components/ProductsListToolBar'; import ProductDetailView from '../components/ProductDetailView'; import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; import FlatButton from 'material-ui/FlatButton'; export default class Products extends React.Component { constructor(props) { super(props); this.state = {productSelected: { "meta": "", "su": 1, "hide_interaction_condition": {}, "available": 0, "oPrice": 0, "slug": "otc224435", "is_banned": false, "prescriptionRequired": false, "pId": 0, "mrp": 0, "hkpDrugCode": 0, "therapeuticClassName": null, "label": "", "pForm": "", "uPrice": 1890, "type": "OTC", "productsForBrand": null, "uip": 1, "packSize": "1 kit", "mfId": 0, "packForm": "", "generics": null, "name": "Please select a product", "discounted_price": null, "form": "", "drug_form": "", "id": 0, "packSizeLabel": "", "manufacturer": "", "pName": "", "imgUrl": "http://www.crocin.com/content/dam/global/panadol/en_IN/418x418/crocin-advance-medicine.png", "discountPerc": 0 }, products:[{ "meta": "", "su": 1, "hide_interaction_condition": {}, "available": 0, "oPrice": 1234, "slug": "otc224435", "is_banned": false, "prescriptionRequired": false, "pId": 0, "mrp": 0, "hkpDrugCode": 0, "therapeuticClassName": null, "label": "", "pForm": "", "uPrice": 1890, "type": "OTC", "productsForBrand": null, "uip": 1, "packSize": "1 kit", "mfId": 0, "packForm": "", "generics": null, "name": "This is a dummy product", "discounted_price": null, "form": "", "drug_form": "", "id": 4124324, "packSizeLabel": "", "manufacturer": "", "pName": "", "imgUrl": null, "discountPerc": 0 }] }; this.handleProductClick = this.handleProductClick.bind(this); this.handleSearch = this.handleSearch.bind(this); } handleSearch = (searchText) => { console.log("Everything is in place:"+searchText); var hostURLPrefix = ""; if(window.location.hostname == 'localhost') { hostURLPrefix = "http://"+ window.location.hostname + ":3001" } var url = hostURLPrefix + '/store01/products'; if(searchText) { url = hostURLPrefix + '/store01/product/'+searchText; } axios.get(url) .then(response => { console.log(response); this.setState({ products:response.data }); }) .catch(function (error) { console.log(error); }); } handleProductClick(productId) { this.setState({productSelected: productId}); } render() { const style = { prodOuter:{ padding:"20px", height:"calc( 100% - 40px )" }, prodList: { width:'calc( 50% - 4px)', float:'left', maxHeight:"calc( 100% - 60px)", hegiht:"calc( 100% - 60px)", overflowY:"auto", border: "1px solid rgb(224, 224, 224)" }, prodDetails: { width:'calc( 50% - 20px )', float:'left', paddingLeft:'20px', minHeight:"calc( 100% - 60px)", hegiht:"auto", paddingTop:"20px" } }; return ( <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> <div style={style.prodOuter}> <ProductsListToolBar onSearch={this.handleSearch}></ProductsListToolBar> <div style={style.prodList}> <ProductList products = {this.state.products} onProductClick={this.handleProductClick}></ProductList> </div> <div style={style.prodDetails}> <ProductDetailView product={this.state.productSelected}></ProductDetailView> </div> </div> </MuiThemeProvider> ); } }
import React,{useState,useEffect} from 'react' import './App.css'; import Header from './componets/Header'; import Users from './componets/Users'; function url(path){ return process.env.NODE_ENV === "development" ? `http://localhost:1422${path}` : path } function App() { const [data, setData] = useState([]) useEffect(() => { fetch(url("/api/users")) .then(res => res.json()) .then(apiData => setData(apiData)) },[data]) return ( <div className="App"> <Header/> <Users userData={data} url={url} /> </div> ); } export default App;
const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin').default; const { TsConfigPathsPlugin } = require('awesome-typescript-loader'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { entry: ['./src/index.tsx'], mode: 'development', output: { path: __dirname + '/../dist', filename: 'app.js', library: 'plusnewSimulateDomEvents', libraryTarget: "umd", }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], plugins: [new TsConfigPathsPlugin()], }, devtool: 'source-map', module: { rules: [ { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[local]--[hash:base64:5]', camelCase: true, } }, { loader: 'sass-loader', options: { sourceMap: true, sourceMapContents: false, modules: true, localIdentName: '[local]--[hash:base64:5]', }, }, ], }, { test: /\.tsx?$/, loader: 'awesome-typescript-loader', }, ] }, plugins: [ new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: [path.join(__dirname, '..', 'dist')], }), ], };
import { Quat } from '../../../core/math/quat.js'; import { ANIM_LAYER_ADDITIVE, ANIM_LAYER_OVERWRITE } from '../controller/constants.js'; import { AnimBlend } from './anim-blend.js'; import { math } from '../../../core/math/math.js'; /** * Used to store and update the value of an animation target. This combines the values of multiple * layer targets into a single value. * * @ignore */ class AnimTargetValue { static TYPE_QUAT = 'quaternion'; static TYPE_VEC3 = 'vector3'; static q1 = new Quat(); static q2 = new Quat(); static q3 = new Quat(); static quatArr = [0, 0, 0, 1]; static vecArr = [0, 0, 0]; static IDENTITY_QUAT_ARR = [0, 0, 0, 1]; /** * Create a new AnimTargetValue instance. * * @param {AnimComponent} component - The anim component this target value is associated with. * @param {string} type - The type of value stored, either quat or vec3. */ constructor(component, type) { this._component = component; this.mask = new Int8Array(component.layers.length); this.weights = new Float32Array(component.layers.length); this.totalWeight = 0; this.counter = 0; this.layerCounter = 0; this.valueType = type; this.dirty = true; this.value = (type === AnimTargetValue.TYPE_QUAT ? [0, 0, 0, 1] : [0, 0, 0]); this.baseValue = null; this.setter = null; } get _normalizeWeights() { return this._component.normalizeWeights; } getWeight(index) { if (this.dirty) this.updateWeights(); if (this._normalizeWeights && this.totalWeight === 0 || !this.mask[index]) { return 0; } else if (this._normalizeWeights) { return this.weights[index] / this.totalWeight; } return math.clamp(this.weights[index], 0, 1); } _layerBlendType(index) { return this._component.layers[index].blendType; } setMask(index, value) { this.mask[index] = value; if (this._normalizeWeights) { if (this._component.layers[index].blendType === ANIM_LAYER_OVERWRITE) { this.mask = this.mask.fill(0, 0, index); } this.dirty = true; } } updateWeights() { this.totalWeight = 0; for (let i = 0; i < this.weights.length; i++) { this.weights[i] = this._component.layers[i].weight; this.totalWeight += this.mask[i] * this.weights[i]; } this.dirty = false; } updateValue(index, value) { // always reset the value of the target when the counter is 0 if (this.counter === 0) { AnimBlend.set(this.value, AnimTargetValue.IDENTITY_QUAT_ARR, this.valueType); if (!this._normalizeWeights) { AnimBlend.blend(this.value, this.baseValue, 1, this.valueType); } } if (!this.mask[index] || this.getWeight(index) === 0) return; if (this._layerBlendType(index) === ANIM_LAYER_ADDITIVE && !this._normalizeWeights) { if (this.valueType === AnimTargetValue.TYPE_QUAT) { // current value const v = AnimTargetValue.q1.set(this.value[0], this.value[1], this.value[2], this.value[3]); // additive value const aV1 = AnimTargetValue.q2.set(this.baseValue[0], this.baseValue[1], this.baseValue[2], this.baseValue[3]); const aV2 = AnimTargetValue.q3.set(value[0], value[1], value[2], value[3]); const aV = aV1.invert().mul(aV2); // scale additive value by it's weight aV.slerp(Quat.IDENTITY, aV, this.getWeight(index)); // add the additive value onto the current value then set it to the targets value v.mul(aV); AnimTargetValue.quatArr[0] = v.x; AnimTargetValue.quatArr[1] = v.y; AnimTargetValue.quatArr[2] = v.z; AnimTargetValue.quatArr[3] = v.w; AnimBlend.set(this.value, AnimTargetValue.quatArr, this.valueType); } else { AnimTargetValue.vecArr[0] = value[0] - this.baseValue[0]; AnimTargetValue.vecArr[1] = value[1] - this.baseValue[1]; AnimTargetValue.vecArr[2] = value[2] - this.baseValue[2]; AnimBlend.blend(this.value, AnimTargetValue.vecArr, this.getWeight(index), this.valueType, true); } } else { AnimBlend.blend(this.value, value, this.getWeight(index), this.valueType); } if (this.setter) this.setter(this.value); } unbind() { if (this.setter) { this.setter(this.baseValue); } } } export { AnimTargetValue };
"use strict"; exports.AllDayPanelTitle = exports.AllDayPanelTitleProps = exports.viewFunction = void 0; var _inferno = require("inferno"); var _vdom = require("@devextreme/vdom"); var _message = _interopRequireDefault(require("../../../../../../../localization/message")); var _combine_classes = require("../../../../../../utils/combine_classes"); var _excluded = ["className", "visible"]; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var viewFunction = function viewFunction(viewModel) { return (0, _inferno.normalizeProps)((0, _inferno.createVNode)(1, "div", viewModel.classes, viewModel.text, 0, _extends({}, viewModel.restAttributes))); }; exports.viewFunction = viewFunction; var AllDayPanelTitleProps = { className: "", visible: true }; exports.AllDayPanelTitleProps = AllDayPanelTitleProps; var AllDayPanelTitle = /*#__PURE__*/function (_InfernoWrapperCompon) { _inheritsLoose(AllDayPanelTitle, _InfernoWrapperCompon); function AllDayPanelTitle(props) { var _this; _this = _InfernoWrapperCompon.call(this, props) || this; _this.state = {}; return _this; } var _proto = AllDayPanelTitle.prototype; _proto.render = function render() { var props = this.props; return viewFunction({ props: _extends({}, props), text: this.text, classes: this.classes, restAttributes: this.restAttributes }); }; _createClass(AllDayPanelTitle, [{ key: "text", get: function get() { return _message.default.format("dxScheduler-allDay"); } }, { key: "classes", get: function get() { return (0, _combine_classes.combineClasses)(_defineProperty({ "dx-scheduler-all-day-title": true, "dx-scheduler-all-day-title-hidden": !this.props.visible }, this.props.className, !!this.props.className)); } }, { key: "restAttributes", get: function get() { var _this$props = this.props, className = _this$props.className, visible = _this$props.visible, restProps = _objectWithoutProperties(_this$props, _excluded); return restProps; } }]); return AllDayPanelTitle; }(_vdom.InfernoWrapperComponent); exports.AllDayPanelTitle = AllDayPanelTitle; AllDayPanelTitle.defaultProps = _extends({}, AllDayPanelTitleProps);
$(document).ready(function () { function openDialog() { $('.modal').modal('show'); } $(document).on('click', '.editLinkForComment', function (event) { openDialog(); $.get(this.href, function (data) { $('#commentEdit').html(data); }); event.preventDefault(); }); $(document).on('submit', '[data-formtype="ajaxForm"]', function (event) { $.post(this.action, $(this).serialize(), function (data) { if (data === "OK") document.location.reload(); else $('#commentEdit').html(data); }); event.preventDefault(); }); });
/* * --------------------------------------- * --------- CREATED BY CREATOR ---------- * fecha: 21-03-2016 17:03:55 * Descripcion : cslSuscripto.js * --------------------------------------- */ var cslSuscripto_ = function(){ /*metodos privados*/ var _private = {}; _private.idSuscripto = 0; _private.mapaSitio = ""; _private.config = { modulo: "sitioweb/cslSuscripto/" }; /*metodos publicos*/ this.publico = {}; /*crea tab : CslSuscripto*/ this.publico.main = function(element){ simpleScript.addTab({ id : diccionario.tabs.CSUSC, label: $(element).attr("title"), fnCallback: function(){ _private.mapaSitio = $(element).data("sitemap"); cslSuscripto.getContenido(); } }); }; /*contenido de tab: CslSuscripto*/ this.publico.getContenido = function(){ simpleAjax.send({ dataType: "html", root: _private.config.modulo, data: "&_siteMap="+ _private.mapaSitio, fnCallback: function(data){ $("#"+diccionario.tabs.CSUSC+"_CONTAINER").html(data); cslSuscripto.getGridCslSuscripto(); } }); }; this.publico.getGridCslSuscripto = function (){ var oTable = $("#"+diccionario.tabs.CSUSC+"gridCslSuscripto").dataTable({ bProcessing: true, bServerSide: true, bDestroy: true, sPaginationType: "bootstrap_full", //two_button sServerMethod: "POST", bPaginate: true, iDisplayLength: 10, aoColumns: [ {sTitle: lang.generico.NRO, sWidth: "5%", sClass: "center"}, {sTitle: lang.generico.NRODOC, sWidth: "10%"}, {sTitle: lang.generico.NOMBRE, sWidth: "35%"}, {sTitle: lang.generico.CIUDAD, sWidth: "20%"}, {sTitle: lang.generico.FECHA, sWidth: "20%", sClass: "center"}, {sTitle: lang.generico.ESTADO, sWidth: "10%", sClass: "center"}, {sTitle: lang.generico.ACCIONES, sWidth: "8%", sClass: "center", bSortable: false} ], aaSorting: [[0, "desc"]], sScrollY: "300px", sAjaxSource: _private.config.modulo+"getGridCslSuscripto", fnServerParams: function(aoData) { aoData.push({"name": "_estado", "value": $("#"+diccionario.tabs.CSUSC+"lst_estadoSearch").val()}); aoData.push({"name": "_idLista", "value": $("#"+diccionario.tabs.CSUSC+"lst_lista").val()}); }, fnDrawCallback: function() { $("#"+diccionario.tabs.CSUSC+"gridCslSuscripto_filter").find("input").attr("placeholder",lang.busqueda.CSUSC).css("width","210px"); simpleScript.enterSearch("#"+diccionario.tabs.CSUSC+"gridCslSuscripto",oTable); /*para hacer evento invisible*/ simpleScript.removeAttr.click({ container: "#widget_"+diccionario.tabs.CSUSC, typeElement: "button" }); } }); setup_widgets_desktop(); }; this.publico.getFormEditCslSuscripto = function(btn,id){ _private.idSuscripto = id; simpleAjax.send({ element: btn, dataType: "html", root: _private.config.modulo + "getFormEditCslSuscripto", data: "&_idSuscripto="+_private.idSuscripto, fnCallback: function(data){ $("#cont-modal").append(data); /*los formularios con append*/ $("#"+diccionario.tabs.CSUSC+"formEditCslSuscripto").modal("show"); } }); }; this.publico.postDesactivar = function(btn,id){ simpleAjax.send({ element: btn, root: _private.config.modulo + 'postDesactivar', data: '&_idSuscripto='+id, fnCallback: function(data) { if(!isNaN(data.result) && parseInt(data.result) === 1){ simpleScript.notify.ok({ content: lang.mensajes.MSG_24, callback: function(){ simpleScript.reloadGrid('#'+diccionario.tabs.CSUSC+'gridCslSuscripto'); } }); } } }); }; this.publico.postActivar = function(btn,id){ simpleAjax.send({ element: btn, root: _private.config.modulo + 'postActivar', data: '&_idSuscripto='+id, fnCallback: function(data){ if(!isNaN(data.result) && parseInt(data.result) === 1){ simpleScript.notify.ok({ content: lang.mensajes.MSG_25, callback: function(){ simpleScript.reloadGrid('#'+diccionario.tabs.CSUSC+'gridCslSuscripto'); } }); } } }); }; this.publico.postPDF = function(btn){ var estadox = $("#"+diccionario.tabs.CSUSC+"lst_estadoSearch").val(); var idLista = $("#"+diccionario.tabs.CSUSC+"lst_lista").val(); simpleAjax.send({ element: btn, root: _private.config.modulo + 'postPDF', data: '&_idLista='+idLista+'&_estado='+estadox, fnCallback: function(data) { if(parseInt(data.result) === 1){ $('#'+diccionario.tabs.CSUSC+'btnDowPDF').off('click'); $('#'+diccionario.tabs.CSUSC+'btnDowPDF').attr("onclick","window.open('public/files/"+data.archivo+"','_blank');globalScript.deleteArchivo('"+data.archivo+"');"); $('#'+diccionario.tabs.CSUSC+'btnDowPDF').click(); } } }); }; return this.publico; }; var cslSuscripto = new cslSuscripto_();
/***************************************************** IMAGE ANIMATION **********************/ document.getElementById('right').addEventListener('mouseover', function () { document.getElementById("pupil-left").className = 'pupil pupil-toright'; document.getElementById("pupil-right").className = 'pupil pupil-toright'; }); document.getElementById('left').addEventListener('mouseover', function () { document.getElementById("pupil-left").className = 'pupil pupil-toleft'; document.getElementById("pupil-right").className = 'pupil pupil-toleft'; }); document.getElementById('Box').addEventListener('mouseenter', function () { document.getElementById("pupil-left").className = 'pupil'; document.getElementById("pupil-right").className = 'pupil'; }); document.getElementById('main').addEventListener('mouseenter', function () { document.getElementById("pupil-left").className = 'pupil pupil-toDown'; document.getElementById("pupil-right").className = 'pupil pupil-toDown'; });
const { client } = require('../../config/db'); getTrainingCommittee = (id,callback)=>{ client.query('SELECT * FROM training_committee WHERE training_committee.id=($1)',[id],function (err, result) { console.log('orgs') if (err) { console.log(err); callback(err); } callback(null, result.rows[0]); }); }; postTrainingCommitteeModel=(body,hash,callback)=>{ client.query("INSERT INTO training_committee( id , name , email ,password ) values($1, $2,$3,$4);",[body.id,body.name,body.email,hash], function (err, result){ if (err) { console.log(err); callback(err); } newUser=[body.id,hash] console.log("newUser ::", newUser) callback(null, newUser); }); }; loginModelCheckUser=(id,callback)=>{ client.query('SELECT id,password FROM training_committee WHERE training_committee.id=($1)',[id],function (err, result) { if (err) { console.log(err); callback(err); } callback(null, result.rows[0]); }); }; module.exports = { getTrainingCommittee: getTrainingCommittee, postTrainingCommitteeModel:postTrainingCommitteeModel, loginModelCheckUser:loginModelCheckUser }
/** * Created by Tomasz Jodko on 2016-06-05. */ app.factory('projectFactory', ['$http', function ($http) { var urlBase = '/projektzespolowy/projekty'; var projectFactory = {}; projectFactory.getProjects = function (callback) { return $http.get(urlBase + '/getAll').then(function (response) { if (response.data.error) { return null; } else { projectFactory.returnedData = response.data; callback(projectFactory.returnedData); } }); }; projectFactory.getProject = function (id, callback) { return $http.get(urlBase + '/getById/' + id).then(function (response) { if (response.data.error) { return null; } else { projectFactory.returnedData = response.data; callback(projectFactory.returnedData); } }); }; projectFactory.getProjectsByCompanyId = function (id, callback) { return $http.get(urlBase + '/getByCompanyId/' + id).then(function (response) { if (response.data.error) { return null; } else { projectFactory.returnedData = response.data; callback(projectFactory.returnedData); } }); }; projectFactory.getProjectsByUserId = function (id, callback) { return $http.get(urlBase + '/getByUserId/' + id).then(function (response) { if (response.data.error) { return null; } else { projectFactory.returnedData = response.data; callback(projectFactory.returnedData); } }); }; projectFactory.saveProject = function (wrapper, callback) { return $http.post(urlBase + '/saveProjekt', wrapper).then(function (response) { if (response.data.error) { return null; } else { projectFactory.returnedData = response.data; callback(projectFactory.returnedData); } }); }; projectFactory.setUsers = function (wrapper) { return $http.put(urlBase + '/setUsers',wrapper); }; projectFactory.setCompanies = function (wrapper) { return $http.put(urlBase + '/setCompanies',wrapper); }; projectFactory.deleteProject = function (id) { return $http.put(urlBase + '/deleteById/' + id); }; return projectFactory; }]);
'use strict'; var express = require('express'); var routes = require('./app/routes/index.js'); var mongoose = require('mongoose'); var passport = require('passport'); var session = require('express-session'); var fs=require('fs'); var app = express(); app.get('/api/whoami',function(req,res){ fs.writeFile('log.txt',req,function(err){ if(err) throw err; }); var object={}; var ips=req.ip.split(':'); object['ipaddress']=ips[ips.length-1]; object['language']=req.headers['accept-language'].split(',')[0]; object['software']=req.headers['user-agent'].split('(')[1].split(')')[0]; //console.log(req.headers); res.end(JSON.stringify(object)); }); var port = process.env.PORT || 8080; app.listen(port, function () { console.log('Node.js listening on port ' + port + '...'); });
import { extractTokens } from './extractTokens' import { normalizeTokens } from './normalizeTokens' // Transform emoji data for storage in IDB export function transformEmojiData (emojiData) { performance.mark('transformEmojiData') const res = emojiData.map(({ annotation, emoticon, group, order, shortcodes, skins, tags, emoji, version }) => { const tokens = [...new Set( normalizeTokens([ ...(shortcodes || []).map(extractTokens).flat(), ...tags.map(extractTokens).flat(), ...extractTokens(annotation), emoticon ]) )].sort() const res = { annotation, group, order, tags, tokens, unicode: emoji, version } if (emoticon) { res.emoticon = emoticon } if (shortcodes) { res.shortcodes = shortcodes } if (skins) { res.skinTones = [] res.skinUnicodes = [] res.skinVersions = [] for (const { tone, emoji, version } of skins) { res.skinTones.push(tone) res.skinUnicodes.push(emoji) res.skinVersions.push(version) } } return res }) performance.measure('transformEmojiData', 'transformEmojiData') return res }
import React,{Component, component} from 'react'; class Footer extends Component{ state={ users:[] } render(){ // const users=this.state.users return( <div> <div className="bottom" id="dowbottomn"> <div className="container"> <div className="row"> <div className="col-2"> <img src="../static/img/WF.png" height={60} widht={60} /> </div> <div className="col-3"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </div> <div className="col-3" style={{marginLeft: 40}}> <h4 style={{marginBottom: 30}}> Follow us </h4> <a href="#"> <img src="../static/img/Path 108.png" height={25} width={25} id="links" /> </a> <a href="#"> <img src="../static/img/Path 109.png" height={25} width={25} id="links" /> </a> <a href="#"> <img src="../static/img/Path 110.png" height={25} width={25} id="links" /> </a> <a href="#"> <img src="../static/img/Path 111.png" height={25} width={25} id="links" /> </a> </div> <div className="col-3"> <h4> Newsletter </h4> <input type="text" name="email" id="email" placeholder="E-mail" /> <input type="submit" /> </div> </div></div></div> <div className="bottom1"> <div className="container"> <div className="row"> <div className="col-4" style={{marginTop: 20}}> <center> <img src="../static/img/Group 56.png" height={60} width={50} /> <h5 style={{textAlign: 'center', marginTop: 5}}>+91-720-80-99-369</h5> </center></div> <div className="col-4" style={{marginTop: 20}}> <center> <img src="../static/img/Group 57.png" height={40} width={50} /> <h5 style={{textAlign: 'center', marginTop: 20}}>weFund@gmail.com</h5> </center></div> <div className="col-4" style={{marginTop: 20}}> <center> <img src="../static/img/Group 58.png" height={40} width={50} /> <h5 style={{textAlign: 'center', marginTop: 20}}>Algiers,Algeria</h5> </center></div></div> <hr className="whiteline" /> <center><bottom> Copyright @ 2020 WeFund. All rights reserved. </bottom></center> </div> </div> </div> ) } } export default Footer;
import React from 'react' import PropTypes from 'prop-types' import { responsive } from '../../../traits' import { table } from '../../../macros' import { useID, useRowIDs } from '../../../hooks' import Overflow from '../overflow' import * as Styled from './styles' const TableResponsive = ({ height, minWidth, rowData }) => { const [tableID] = useID() const [rowIDs] = useRowIDs(rowData) if (rowData && rowData.length > 0) { return ( <Overflow height={height} x="scroll"> <Styled.TableResponsive minWidth={minWidth}> <thead> <tr> {Object.keys(rowData[0]).map(colName => ( <th key={`table-${tableID}-${colName}`}>{colName}</th> ))} </tr> </thead> {rowData.map((row, rowIndex) => { const rowKey = rowIDs.length ? `table-${tableID}-row-${rowIDs[rowIndex]}` : `table-${tableID}-row-${rowIndex}` return ( <tbody key={rowKey}> {Object.keys(row).map(colName => ( <tr> <th>{colName}</th> <td>{row[colName]}</td> </tr> ))} </tbody> ) })} </Styled.TableResponsive> </Overflow> ) } return ( <Overflow height={height} x="scroll"> <table> <thead> <tr> <td>No data.</td> </tr> </thead> </table> </Overflow> ) } TableResponsive.propTypes = { ...table.propTypes(), ...responsive.propTypes(), rowData: PropTypes.arrayOf(PropTypes.object).isRequired, } TableResponsive.defaultProps = { ...table.defaultProps(), ...responsive.defaultProps(), } export default TableResponsive