text
stringlengths
7
3.69M
export default function foo() { console.log('foo'); } function foo2() { console.log('foo2'); } export default foo2
$(function() { $("#btnSalvarMenu").click(function(){ salvarMenu(); }); $("#btnController").click(function(){ ListarControllers(); }); $("#btnMetodo").click(function(){ ListarMetodos(); }); $("#nmeController").change(function(){ $("#nmeMethod").val(''); }); }); function salvarMenu(){ swal({ title: "Aguarde, salvando registro!", imageUrl: "../../Resources/images/preload.gif", showConfirmButton: false }); var indAtivo='N'; var indVisible='N'; if ($("#indAtivo").is(":checked")){ indAtivo = 'S'; } if ($("#indVisible").is(":checked")){ indVisible = 'S'; } ExecutaDispatch('Menu', 'SalvarMenu', "dscMenu<=>"+$("#dscMenu").val()+"|"+ "codMenu<=>"+$("#codMenu").val()+"|"+ "nmeController<=>"+$("#nmeController").val()+"|"+ "nmeMethod<=>"+$("#nmeMethod").val()+"|"+ "codMenuPai<=>"+$("#codMenuPai").val()+"|"+ "indAtivo<=>"+indAtivo+"|"+ "indVisible<=>"+indVisible, trataRetornoSalvar); } function trataRetornoSalvar(retorno){ if (retorno[0]==true){ $("#codMenu").val(retorno[2]); $("#cadastroMenu").modal("hide"); swal.close(); carregarListaMenus(); }else{ $(".jquery-waiting-base-container").fadeOut({modo:"fast"}); swal({ title: "Erro!", text: retorno[1], type: "error", confirmButtonText: "Fechar" }); } } function ListarControllers(){ $.post('../../Dispatch.php', { method: 'ListarClasses', controller: 'Menu' }, function(retorno){ retorno = eval ('('+retorno+')'); swal.close(); carregarListaControllers(retorno); } ); } function carregarListaControllers(retorno){ var tabela = '<table>'; for(i=0;i<retorno.length;i++){ tabela += '<tr><td><a href="javascript:preencheCampo(\'nmeController\', \''+retorno[i].nmeArquivo+'\', \'modalControllers\');">'+retorno[i].nmeArquivo+'</a></td></tr>'; } tabela += '</table>'; $("#conteudoController").html(tabela); $('#modalControllers').modal('show'); } function ListarMetodos(){ if ($.trim($("#nmeController").val())==''){ swal({ title: "Erro!", text: 'Selecione uma controller, por favor!', type: "error", confirmButtonText: "Fechar" }); return; } $.post('../../Dispatch.php', { method: 'ListarMetodos', controller: 'Menu', nmeController: $("#nmeController").val() }, function(retorno){ retorno = eval ('('+retorno+')'); swal.close(); carregarListaMetodos(retorno); } ); } function carregarListaMetodos(retorno){ var tabela = '<table>'; for(i=0;i<retorno.length;i++){ tabela += '<tr><td><a href="javascript:preencheCampo(\'nmeMethod\', \''+retorno[i].dscMetodo+'\', \'modalMetodos\');">'+retorno[i].dscMetodo+'</a></td></tr>'; } tabela += '</table>'; $("#conteudoMetodos").html(tabela); $('#modalMetodos').modal('show'); } function preencheCampo(Campo, Valor, modal){ $("#"+Campo).val(Valor); $('#'+modal).modal('hide'); } function carregaComboMenuPai(Dados){ if (!Dados[0]){ var DropDown = ''; }else{ Dados = Dados[1]; var DropDown = '<select class="form-control" id="codMenuPai">'; DropDown += ' <option value="-1">Selecione</option>'; for (i=0;i<Dados.length;i++){ DropDown += ' <option value="'+Dados[i].COD_MENU+'">'+Dados[i].DSC_MENU+'</option>'; } DropDown += '</select>'; } $("#divCodMenuPai").html(DropDown); } $(document).ready(function(){ ExecutaDispatch('Menu', 'ListarMenusAtivos', undefined, carregaComboMenuPai); });
/************************** JS **************************/ let storage = localStorage; var arrayDia = new Array(7); arrayDia = ["Domingo","Segunda-feira","Terça-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sábado"]; var arrayMes = new Array(12); arrayMes = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"]; const data = new Date(); var numero_item_pendente = 0; var numero_item_concluido = 0; var numero_total_item = 0; var percentagem_item_concluida = 0; var objData = { diaSemana: arrayDia[data.getDay()], diaMes: data.getDate(), mes: data.getMonth() + 1, ano: data.getFullYear() } var DomString = { diaSemana: '.dia_semana', dataCompleto: '.data_completo', num_item_pendente: '.num_item_pendente', container_pendente: '.container-item-pendente', container_item_pendente: '.container-item', container_item_pendente_text: '.container-item-text', container_item_pendente_remover: '.remover_text_pendente', container_concluido: '.container-item-concluido', percent_item_concluido: '.percent_item_concluido', container_item_concluido_text: '.container-item-concluido-text', container_item_concluido_remover: '.remover_text_concluido', container_item_message: '.container-item-message', container_footer: '.container-footer', btn_limpar_tudo: '.btn-clean-all', btn_esconder_item: '.btn-hide-item', btn_mostrar_item: '.btn-show-item', btn_add: '.btn-add', input_task: '.input-task', remover_text_pendente: '.remover_text_pendente', percentagem_item_concluido: '.percent_item_concluido' }; var DomObj = { inputTask: document.querySelector(DomString.input_task), btnAdd: document.querySelector(DomString.btn_add), btnEsconderItem: document.querySelector(DomString.btn_esconder_item), btnMostrarItem: document.querySelector(DomString.btn_mostrar_item), container_item_pendente: document.querySelector(DomString.container_pendente), btn_remover_item_pendente: document.querySelector(DomString.remover_text_pendente), item_pendente: document.querySelector(DomString.num_item_pendente), item_concluido: document.querySelector(DomString.percent_item_concluido), container_item_pendente_text: document.querySelector(DomString.container_item_concluido_text), container_item_concluido: document.querySelector(DomString.container_concluido), container_footer: document.querySelector(DomString.container_footer) } function inputLength(){ return DomObj.inputTask.value.length; } DomObj.btnAdd.addEventListener('click', function(){ var html_item = '<div class="container-item"><div class="container-item-checkBox add-concluido"></div><h2 class="container-item-text">%task_item%</h2><div class="container-item-div remover_text_pendente"><i class="trash far fa-trash-alt"></i></div></div>'; if(inputLength() > 0){ html_item = html_item.replace('%task_item%', DomObj.inputTask.value); DomObj.container_item_pendente.insertAdjacentHTML('beforeend', html_item); DomObj.inputTask.value = ''; numero_item_pendente++; numero_total_item++; console.log('Preenchido'); percentagem_item_concluida = percentagem_concluido(numero_total_item, numero_item_concluido); render(); }else{ alert('Impossível Adicionar Tarefa, não preencheu o campo!'); } }); DomObj.container_item_pendente.addEventListener('click', function(e){ const element = e.target; //const parent = element.parentNode.parentNode.parentNode; const parent = element.parentNode.parentNode; //console.log(element.className); console.log(parent.parentNode); // Para remover if(element.className == 'trash far fa-trash-alt') { parent.parentNode.removeChild(element.parentNode.parentNode); numero_item_pendente--; numero_total_item--; render(); } if(element.className == 'container-item-checkBox add-concluido'){ element.parentNode.parentNode.removeChild(element.parentNode); var html = '<div class="container-item"><div class="container-item-concluido-checkBox remove-concluido"><i class="checked fas fa-check"></i></div><h2 class="container-item-concluido-text">%task_item%</h2><div class="container-item-div remover_text_concluido"><i class="trash far fa-trash-alt"></i></div></div>'; var task_item = element.nextSibling.textContent; html = html.replace('%task_item%',task_item); DomObj.container_item_concluido.insertAdjacentHTML('beforeend', html); numero_item_pendente--; numero_item_concluido++; percentagem_item_concluida = percentagem_concluido(numero_total_item, numero_item_concluido); render(); } }); DomObj.container_item_concluido.addEventListener('click', function(e){ const element = e.target; if(element.className == 'trash far fa-trash-alt'){ element.parentNode.parentNode.parentNode.removeChild(element.parentNode.parentNode); numero_total_item--; numero_item_concluido--; percentagem_item_concluida = percentagem_concluido(numero_total_item, numero_item_concluido); render(); } if(element.className == 'checked fas fa-check'){ var task_item__ = element.parentNode.nextSibling.textContent; var html = '<div class="container-item"><div class="container-item-checkBox add-concluido"></div><h2 class="container-item-text">%task_item%</h2><div class="container-item-div remover_text_pendente"><i class="trash far fa-trash-alt"></i></div></div>'; html = html.replace('%task_item%', task_item__); DomObj.container_item_pendente.insertAdjacentHTML('beforeend', html); element.parentNode.parentNode.parentNode.removeChild(element.parentNode.parentNode); numero_item_concluido--; numero_item_pendente++; percentagem_item_concluida = percentagem_concluido(numero_total_item, numero_item_concluido); render(); } }); DomObj.container_footer.addEventListener('click', function(e){ const element = e.target; if(element.className == 'btn-hide-item'){ var filhos = document.querySelector('.container-item-concluido'); console.log(filhos); filhos.style.display = 'none'; element.style.display = 'none'; document.querySelector('.btn-show-item').style.display = 'block'; } if(element.className == 'btn-show-item'){ var filhos = document.querySelector('.container-item-concluido'); filhos.style.display = 'block'; element.style.display = 'none'; document.querySelector('.btn-hide-item').style.display = 'block'; } if(element.className == 'btn-clean-all'){ var nodeContainerPendente = document.querySelector('.container-item-pendente'); var nodeContainerConcluido = document.querySelector('.container-item-concluido'); while(nodeContainerPendente.lastChild.className != 'item-pendente-text'){ nodeContainerPendente.removeChild(nodeContainerPendente.lastChild); } while(nodeContainerConcluido.lastChild.className != 'item-concluido-text'){ nodeContainerConcluido.removeChild(nodeContainerConcluido.lastChild); } numero_item_concluido = 0; numero_item_pendente = 0; numero_total_item = 0; percentagem_item_concluida = percentagem_concluido(numero_total_item, numero_item_concluido); render(); } }); function percentagem_concluido(total_item, item_concluido){ return (total_item > 0) ? (100*item_concluido)/total_item : 0; } function render(){ setDate(); DomObj.item_pendente.innerHTML = `${numero_item_pendente}`; DomObj.item_concluido.innerHTML = `${percentagem_item_concluida}%`; if (numero_item_pendente == 0){ document.querySelector('.container-item-message').style.display = 'block'; document.querySelector('.container-item-pendente').style.display = 'none'; }else{ document.querySelector('.container-item-message').style.display = 'none'; document.querySelector('.container-item-pendente').style.display = 'block'; } } function setDate() { var length_dia_mes = Math.log(objData.diaMes) * Math.LOG10E + 1 | 0; var length_mes = Math.log(objData.diaMes) * Math.LOG10E + 1 | 0; var expressao_dia_mes = ''; var expressao_mes = ''; expressao_dia_mes = length_dia_mes < 2 ? '0'+objData.diaMes : objData.diaMes; expressao_mes = length_mes < 2 ? '0'+objData.mes : objData.mes; document.querySelector(DomString.diaSemana).textContent = objData.diaSemana; document.querySelector(DomString.dataCompleto).textContent = `${expressao_dia_mes}-${expressao_mes}-${objData.ano}`; } render();
import './style' import { setTitle } from '@kuba/title' import h from '@kuba/h' import text from '@kuba/text' function component () { setTitle(component.title) return ( <text.H1 className='setNewPassword__title' master dark md highlight bold>{component.title}</text.H1> ) } Object.assign(component, { title: 'Set new password' }) export default component
(function ($) { /** * JS for RND15 Google Tag Manager * * Author: J.Pitt * Contributors: - * * Last update: 31st August 2014 * * Description & additional notes: * - Tracks breakpoint * - Tracks touch or non touch * */ Drupal.behaviors.rnd15gtm = { attach: function (context, settings) { var _base = Drupal.behaviors.rnd15gtm; if(settings.ajaxPageState && settings.ajaxPageState.theme == 'rnd15'){ // Setup the menu, passing in the relevant context $('html').once('rnd15GTM', _base.setupDataLayer); } }, /** * Sets up the touch menu * * - Declares the menu wide objects required and caches them * - Enables responsive touch so the menu works from non-touch to touch and vice versa * - Provides a debug mode (append ?touch=true/false to test the menu) * - Checks if we are on a touch device OR on XS/SM breakpoint * - Sets up the menu with some data attributes so we can nicely animate it * - * @param {[type]} context [description] * @return {[type]} [description] */ setupDataLayer : function() { var _base = Drupal.behaviors.rnd15gtm; // Track the current breakpoint _base.trackBreakpoints(); // Track the Touch devices _base.trackTouch(); }, /** * Handle the Breakpoints * * Register relevant JS media query handles */ trackTouch: function() { var _base = Drupal.behaviors.rnd15gtm; if(typeof Modernizr == 'undefined') return; var touchString = String(Modernizr.touch); dataLayer.push({event: 'rnd15.touch', hasTouch:touchString}); }, /** * Handle the Breakpoints * * Register relevant JS media query handles */ trackBreakpoints: function() { var _base = Drupal.behaviors.rnd15gtm; // Skip if we do not have enquire loaded if(typeof enquire == 'undefined') return; // We use the exception handler in case enquire.js is not available try { // Attach enquire JS events enquire .register(Drupal.settings.crl2.breakpoints.xs, { match : _base.trackActiveBreakpoint }) .register(Drupal.settings.crl2.breakpoints.sm, { match : _base.trackActiveBreakpoint }) .register(Drupal.settings.crl2.breakpoints.md, { match : _base.trackActiveBreakpoint }, true) .register(Drupal.settings.crl2.breakpoints.lg, { match : _base.trackActiveBreakpoint }); } catch(err) { // Output the error if (window.console) { console.log(err); } } }, /* * Helper function to track the current breakpoint */ trackActiveBreakpoint: function() { var _base = Drupal.behaviors.rnd15gtm; var breakpointEvent = {}; var activeBreakpointString = String(Drupal.settings.crl2.breakpointActive); if(Drupal.settings.crl2.breakpointFrom === null) { breakpointEvent.event = 'rnd15.breakpoint'; breakpointEvent.breakpoint = activeBreakpointString; } else { var fromBreakpointString = String(Drupal.settings.crl2.breakpointFrom); breakpointEvent.event = 'rnd15.breakpointSwitch'; breakpointEvent.breakpointFrom = fromBreakpointString; breakpointEvent.breakpointTo = activeBreakpointString; } dataLayer.push(breakpointEvent); } }; })(jQuery);
import { CLEAR_ERROR, } from '../store/actionTypes'; export const clearError = () => ({ type: CLEAR_ERROR, });
/* EXERCICI 1 */ console.log('Hola mundo'); /* EXERCICI 2 */ function alertMessage(message) { alert(message); }; window.onload = alertMessage('¡Me llamo marta!'); /* EXERCICI 3 */ const name = 'Marta'; const lastName = 'Camacho'; /* EXERCICI 4 */ const number1 = 31348627428; const number2 = 437427468738; let sum = number1 + number2; /* EXERCICI 5 */ let nota_examen; function passedOrNot(nota_examen) { if(nota_examen < 5){ alertMessage(`Ohhh! has suspendido el examen con un ${nota_examen}`) } else { alertMessage(`Oleee! has aprobado el examen con un ${nota_examen}`) }; }; passedOrNot(3); passedOrNot(7); /* EXERCICI 6 */ const text = 'Tinc un cotxe de color blau'; const blau = text.replace('blau', 'verd'); const u = text.replace(/o/g, 'u'); /* EXERCICI 7 */ const obj = ['taula', 'cadira', 'ordinador', 'libreta']; for (let i = 0; i < obj.length; i++){ const message = `L'objecte ${obj[i]} està a la posició ${[i]}.` console.log(message); }; /* EXERCICI 8 */ function calculadora( operator, val1, val2){ if(operator == 'resta'){ console.log(val1 - val2); } else if (operator == 'suma') { console.log(val1 + val2); } else if (operator == 'multiplicacion'){ console.log(val1 * val2); }; }; var resultat = calculadora('multiplicacion',40,20);
/** * Controller */ angular.module('ngApp.timezone').controller('TimeZoneAddEditController', function ($scope, $location,$translate, TimeZoneService, SessionService, $uibModal, $uibModalInstance, timezones, timezone, $log, toaster, mode) { //Set Multilingual for Modal Popup var setModalOptions = function () { $translate(['FrayteError', 'FrayteInformation', 'FrayteValidation', 'ErrorSavingRecord', 'PleaseCorrectValidationErrors', 'SuccessfullySavedInformation']).then(function (translations) { $scope.TitleFrayteError = translations.FrayteError; $scope.TitleFrayteInformation = translations.FrayteInformation; $scope.TextSuccessfullySavedInformation = translations.SuccessfullySavedInformation; $scope.TitleFrayteValidation = translations.FrayteValidation; $scope.TextSuccessfullySavedInformation = translations.SuccessfullySavedInformation; $scope.TextErrorSavingRecord = translations.ErrorSavingRecord; $scope.TextValidation = translations.PleaseCorrectValidationErrors; }); }; //$scope.mode = mode; if (mode === "Add") { $translate('Add').then(function (add) { $scope.mode = add; }); } if (mode === "Modify") { $translate('Modify').then(function (modify) { $scope.mode = modify; }); } $scope.GlobalTimezone = { SelectedTimezone: {} }; $scope.timezones = timezones; $scope.timezoneDetail = { TimezoneId: timezone.TimezoneId, Name: timezone.Name, Offset: timezone.Offset, OffsetShort: timezone.OffsetShort }; $scope.submit = function (isValid, timezoneDetail) { if (isValid) { var timezoneId = timezoneDetail.TimezoneId; TimeZoneService.SaveTimeZone(timezoneDetail).then(function (response) { if (timezoneId === undefined || timezoneId === 0) { //Here we need to add the data in $scope.timezones timezoneDetail.TimezoneId = response.data.TimezoneId; $scope.timezones.push(timezoneDetail); } else { //Need to update the timezones collection and then return back to main grid $scope.updateTimeZone(timezoneDetail); } toaster.pop({ type: 'success', title: $scope.TitleFrayteInformation, body: $scope.TextSuccessfullySavedInformation, showCloseButton: true }); $uibModalInstance.close($scope.timezones); }, function () { toaster.pop({ type: 'warning', title: $scope.TitleFrayteError, body: $scope.TextErrorSavingRecord, showCloseButton: true }); }); } else { toaster.pop({ type: 'warning', title: $scope.TitleFrayteValidation, body: $scope.TextValidation, showCloseButton: true }); } }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }; $scope.updateTimeZone = function (timezoneDetail) { var objects = $scope.timezones; for (var i = 0; i < objects.length; i++) { if (objects[i].TimezoneId === timezoneDetail.TimezoneId) { objects[i] = timezoneDetail; break; } } }; $scope.SetTimezone = function () { $scope.timezoneDetail = { TimezoneId: 0, Name: $scope.GlobalTimezone.SelectedTimezone.Name, Offset: $scope.GlobalTimezone.SelectedTimezone.Offset }; }; $scope.GlobalTimezones = [ { Name: 'IST-Indian Starndard Time', Offset: '+5:30' }, { Name: 'ISL-Indian Starndard Long', Offset: '+4:30' } ]; function init() { // set Multilingual Modal Popup Options setModalOptions(); } init(); });
import {GET_LOGINS_FAILURE, GET_LOGINS_REQUEST, GET_LOGINS_SUCCESS} from "./logins-action-types"; const INITIAL_STATE = { logins: [], loading: false, error: null, singleLogin: {}, loginsCount: 0 }; const loginsReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case GET_LOGINS_REQUEST: return { ...state, loading: true, error: "" } case GET_LOGINS_SUCCESS: return { ...state, loading: false, error: "", logins: action.payload.logins, loginsCount: action.payload.loginsCount } case GET_LOGINS_FAILURE: return { ...state, loading: false, logins: [], error: action.payload, loginsCount: 0 } default: return state; } } export default loginsReducer;
Meteor.publish("favorisUser", function(userId) { return Favoris.getCollByUserId(userId); });
'use strict'; var app = angular.module('app'); app.controller('chartCtrl', function appCtrl($scope) { // data context $scope.ctx = { chart: null, itemsSource: [] }; // populate itemsSource var names = ['Oranges', 'Apples', 'Pears', 'Bananas', 'Pineapples'], data = []; for (var i = 0; i < names.length; i++) { $scope.ctx.itemsSource.push({ name: names[i], mar: Math.random() * 3, apr: Math.random() * 10, may: Math.random() * 5 }); } });
import { DEBUG_SETTINGS_UPDATED, updateDebugSettings } from './actions' import { debugReducer, initialState } from './reducer' export { DEBUG_SETTINGS_UPDATED, updateDebugSettings, debugReducer, initialState }
import axios from 'axios'; import qs from 'qs'; var RQM = { getAll: function(){ return axios.get(window.apiDomainUrl+'/requests/get-all', qs.stringify({})) }, getById: function(id){ return axios.get(window.apiDomainUrl+'/requests/get-by-id?id='+id, qs.stringify({})); }, create: function(data){ return axios.post(window.apiDomainUrl+'/requests/create', qs.stringify(data)); }, update: function(data){ return axios.post(window.apiDomainUrl+'/requests/update', qs.stringify(data)); }, delete: function(data){ return axios.post(window.apiDomainUrl+'/requests/delete', qs.stringify(data)); }, copy: function(data){ return axios.post(window.apiDomainUrl+'/requests/copy', qs.stringify(data)); }, // getAllRequests: function(){ // // return axios.get(window.apiDomainUrl+'/requests/get-all-requests', qs.stringify({})) // }, getRequestsByPage: function(page, perPage, filters){ return axios.post(window.apiDomainUrl+'/requests/get-all-requests-by-page', qs.stringify({page:page, perPage:perPage, filters:filters})) }, }; export function RequestsManager() { return RQM; }
import React from 'react'; import { Switch, Route } from 'react-router-dom'; import './../styles/App.css'; import Quiz from './Quiz'; import FinishedScreen from './../components/FinishedScreen'; const App = () => { return ( <div className="app-container"> <div className="content-container"> <Switch> <Route exact path="/" component={Quiz} /> <Route exact path="/finished" component={FinishedScreen} /> </Switch> </div> </div> ); }; export default App;
var paragraph=$("p"); console.log(paragraph) function setAttributes(attr){ for (var i = 0; i < paragraph.length; i++) { paragraph[i].setAttribute('onclick','red(this)'); } } function red(red){ var itemToRed=red; itemToRed.style.color="red"; } setAttributes();
export const Radom = function (min,max) { return Math.random()*(max-min+1)+min | 0 } export const shuffle = function(arr){ let _arr = [] _arr = arr.slice() for(let i = 0;i<_arr.length;i++){ let j = Radom(0,i) let t = _arr[i] _arr[i] = _arr[j] _arr [j] = t } return _arr } export let playModeName={ listPlay:0, radomPlay:1, singerPlay: 2 } // export const playMode = { // sequence:0, // loop:1, // random:2 // }
var focused = -1; var focusedPanel = 0; var blockEnter = false; var handlerHref = ''; function tableKeyDown(event) { var table = document.getElementById("tr_" + focusedPanel + "_0").parentNode; if (event.key == 'ArrowDown') { focused++; if (focused > table.childNodes.length - 2) focused = 0; document.getElementById('tr_' + focusedPanel + '_' + focused).focus(); } else if (event.key == 'ArrowUp') { focused--; if (focused < 0) focused = focused = table.childNodes.length - 2; document.getElementById('tr_' + focusedPanel + '_' + focused).focus(); } else if (event.key == 'ArrowRight') { sendEventToFramework("tr_" + focusedPanel + '_' + focused, 'DoubleClick', ''); } else if (event.key == 'Enter') { if (blockEnter) return; if (focused >= 0) { sendEventToFramework("tr_" + focusedPanel + '_' + focused, 'RightClick', ''); } } else if (event.key == 'Tab') { focusedPanel = (focusedPanel == 0) ? 1 : 0; document.getElementById("tr_" + focusedPanel + "_0").focus(); event.preventDefault(); } else if (event.key == 'Delete') { // pass delete tek to the framework sendEventToFramework('tr_' + focusedPanel + '_' + focused, 'KeyDown', 'Delete'); } else if (event.key == 'Escape') { sendEventToFramework('tr_' + focusedPanel + '_' + focused, 'KeyDown', 'Escape'); } if([32, 37, 38, 39, 40].indexOf(event.keyCode) > -1) { event.preventDefault(); } } function tableKeyUp(event) { } function onDocumentGotFocus(event) { //document.getElementById("muka").innerHTML = 'XXXXXXXXXXXXXXXXXXXXXXXXX' + event.target.getAttribute('id'); } function onDocumentLostFocus(event) { //document.getElementById("muka").innerHTML = 'XXXXXXXXXXXXXXXXXXXXXXXXX ---- LOST FOCUS'; } function tableGotFocus(panel) { focusedPanel = panel; var p = document.getElementById('panel_' + panel); p.className = 'selected_header'; blockEnter = true; window.setTimeout(function() { blockEnter = false; }, 100); } function tableLostFocus(panel) { var p = document.getElementById('panel_' + panel); p.className = ''; } function tableRowFocus(event) { focused = Number(event.target.id.split('_')[2]); } function tableRowBlur(event) { focused = -1; } function tableRowClick(event) { // XXX - do nothing here } function tableRowRightClick(event) { if (event.button == 2) { sendEventToFramework(event.target.parentNode.id, 'RightClick', 'XXX-PARAM-XXX ' + event.button ); } } function tableRowDoubleClick(event) { sendEventToFramework(event.target.parentNode.id, 'DoubleClick', ''); } function sendEventToFramework(element, event, param) { if (handlerHref == '') { handlerHref = document.getElementById("event_handler_a").getAttribute('href'); } var href = handlerHref; // document will be prepended to the file href = href.replace('xdocumentx', documentId); href = href.replace('xelementx', element); href = href.replace('xeventx', event); href = href.replace('xparamx', param); document.getElementById("event_handler_a").setAttribute('href', href); document.getElementById("event_handler_a").click(); } function onPageLoaded() { document.getElementById("tr_0_0").focus(); } var count = 0; function onPageResize() { var el = document.getElementById("chat"); el.style.position = 'absolute'; el.style.overflow = 'scroll'; el.style.left = '20px'; el.style.top = '20px'; el.style.width = (window.innerWidth - 40) + 'px'; el.style.height = (window.innerHeight - 40) + 'px'; }
'use strict'; /** * @ngdoc service * @name nodeTokenApp.authToken * @description * # authToken * Factory in the nodeTokenApp. */ angular.module('nodeTokenApp') .factory('authToken', function ($window) { var storage = $window.localStorage; var cachedToken; var userToken = "userToken"; // Public API here var authTok = { setToken: function(token){ cachedToken = token; storage.setItem(userToken, token); }, getToken: function(){ if(!cachedToken) { cachedToken = storage.getItem(userToken); } return cachedToken; }, isAuthenticated: function(){ if(!cachedToken) { cachedToken = storage.getItem(userToken); } return !!cachedToken; //get result cast it to a bool then inverses it }, removeToken: function(){ cachedToken = null; storage.removeItem(userToken); } }; return authTok; });
import React from 'react' const ContextUser = React.createContext() const UserProvider = ContextUser.Provider const UserConsumer = ContextUser.Consumer export {UserProvider, UserConsumer}
import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; import {CompanySigninUser} from '../store/action/action'; import Bar from './appbar' import Paper from 'material-ui/Paper'; const style = { height: 500, width: 500, margin: 20, textAlign: 'center', display: 'inline-block' }; class CompanyLogin extends Component { constructor(props) { super(props) this.state = { email: "", password: "", profile: "Company" } } handleChange(e) { this.setState({ [e.target.name]: e.target.value }) } submit(ev) { ev.preventDefault() let data = { email: this.state.email, password: this.state.password, profile: this.state.profile, auth: "Logout" } this .props .CompanySigninUser(data); } signup() { this .props .history .push('/signup') } render() { return ( <div> <Bar/> <center> <div className="container"> <Paper style={style} zDepth={2}> <form onSubmit={this .submit .bind(this)}> <h1>Company Login</h1> <input type="email" name="email" onChange={this .handleChange .bind(this)} placeholder="Email"/> <br/> <br/> <input type="password" name="password" onChange={this .handleChange .bind(this)} placeholder="password"/> <br/> <button type="submit">Signin</button> <Link to='./companysignup'> <button type="submit">Register</button> </Link> </form> </Paper> {/* <button onClick={this.signup.bind(this)}>Go</button> */} </div> </center> </div> ) } } function mapStateToProp(state) { return ({userName: state.root.userName}) } function mapDispatchToProp(dispatch) { return ({ CompanySigninUser: (data) => { dispatch(CompanySigninUser(data)) } }) } export default connect(mapStateToProp, mapDispatchToProp)(CompanyLogin);
// This file controls the target URLs matched from the "sendto" query parameter. // Add or update the available target URLs by saving edits to these values: const redirects = { main: "https://www.facebook.com/Wildcat-Bluff-Disc-Golf-Course-392191570823455/posts", hole1blue: "https://youtu.be/nhc1yL4MFKc", hole1red: "https://youtu.be/RY-DA82uRdk", hole2blue: "https://youtu.be/Z8vdF8ngr6I", hole2red: "https://youtu.be/q975huukMSM", hole3: "https://youtu.be/uBQ-JtPGvMg", hole4blue: "https://youtu.be/z1clkMo-zUY", hole4red: "https://youtu.be/x8mtGALtd5A", hole5blue: "https://youtu.be/RnTLr47sUk0", hole5red: "https://youtu.be/aREvLDFEGt4", hole6blue: "https://youtu.be/sR3UgUnZPGo", hole6red: "https://youtu.be/Ukj-7SH_gMY", hole7: "https://youtu.be/YJJLbykr67o", hole8: "https://youtu.be/pJ4VPL7U-xc", hole9: "https://youtu.be/ius-lYfqEZY", hole10blue: "https://youtu.be/Hi2Wjn-BsO8", hole10red: "https://youtu.be/pkYARgk14Y0", hole11blue: "https://youtu.be/bnprjgLliLo", hole11red: "https://youtu.be/I2JkuKyFA4A", hole12blue: "https://youtu.be/bZhKn8mox4M", hole12red: "https://youtu.be/C6KX2GMOr8I", hole13blue: "https://youtu.be/pnXzvdDz0cI", hole13red: "https://youtu.be/k1uivcQsXb4", hole14blue: "https://youtu.be/b50ZvPJYFdc", hole14red: "https://youtu.be/_zzeOyfYItk", hole15: "https://youtu.be/QxnFwAHrPK4", hole16: "https://youtu.be/M4Q46L3t6cc", hole17blue: "https://youtu.be/uDeUU-xLko4", hole17red: "https://youtu.be/f5M3JLSJxnM", hole18blue: "https://youtu.be/f3sgFbCdP7A", hole18red: "https://youtu.be/C1Xac2vKRD4", hole19: "https://youtu.be/Vkuzzte_2yw", hole20blue: "https://youtu.be/5fKjJQ_bHIA", hole20red: "https://youtu.be/HApNwRJRpQw", hole21: "https://youtu.be/xtINVX_xKvc" };
module.exports = { entry : { home : "./entry/home", product : "./entry/product", me : "./entry/me", more : "./entry/more", asset : "./entry/asset", profit : "./entry/profit", basic : "./entry/basic", record : "./entry/record", score : "./entry/score", bonus : "./entry/bonus", interest : "./entry/interest", invite : "./entry/invite", info : "./entry/info", activity : "./entry/activity", signin : "./entry/signin", signup: "./entry/signup", reset : "./entry/reset", payment : "./entry/payment" }, output : { filename : "../resource/js/[name].js" }, externals : { react : "React", "react-dom" : "ReactDOM", "react-router" : "ReactRouter", redux : "Redux", "react-redux" : "ReactRedux" }, module : { loaders : [ { test : /\.js/, loaders : [ "jsx", "babel" ] } ] }, extensions : [".js"] };
$(document).ready(function() { $("#msgValidacion").text(""); $("#msgValidacion").hide(); // Agregar Editorial $("#formAddEditorial").validate({ rules: { tbxEditorial: { required: true}, } }); inicializar(); cargarDatosEditorialSeleccionada(); ////////////////////////Guardar usuario $("#btnGuardarEditorial").click(function(){ validarGuardar(); }); //////////////////////////Fin guardar libro. }); /** *Funcion encargada de inicialiar variables */ function inicializar(){ //inicializar variables $("#idEditorial").val(0); $("#descripcionOriginal").val(''); ////////////Si esta en la interfaz de ListarEditorial if ($('#tblListaEditoriales').length){ //Listar Editoriales listadoEditoriales(); } } /** *Funcion encargada de verificar si existe una Editorial seleccionada por el admin * y posterior carga de datos del mismo. */ function cargarDatosEditorialSeleccionada(){ $.ajax({ type : "POST", async: false, dataType: 'json', url : "../controllers/EditorialController.php", data : { llamadoAjax : "true", opcion : "cargarDatosEditorialSeleccionada" } }).done(function(data) { if(data != null){ $("#idEditorial").val(data.idEditorial); $("#descripcionOriginal").val(data.descripcion); $("#tbxEditorial").val(data.descripcion); } }); } /** * Verifica si un elemento ya se encuentra registrado en la bd * Tabla ha verificar * Campo ha verificar * Valor ha verificar */ function verficarDatoEnBd(tablaVerificar,campoVerificar,valorVerificar){ var respuesta = false; $.ajax({ type : "POST", async: false, url : "../../../util/ControllerGeneral.php", data : { llamadoAjax : "true", opcion : "verficarDatoEnBd", tabla : tablaVerificar, campo : campoVerificar, valor : valorVerificar } }).done(function(data) { if(data == 1){ respuesta = true; } }); return respuesta; } /** *Funcion encargada de validar los datos y posterior guardado */ function validarGuardar(){ var validaciones = true; /** * Si esta creando una nueva editorial */ if($("#idEditorial").val() == 0){ //Validacion descripcion if($("#tbxEditorial").val().trim() != ""){ if(verficarDatoEnBd('EDITORIAL','DESCRIPCION',$("#tbxEditorial").val().trim())){ $("#msgValidacion").text("Editorial ya registrada"); $("#msgValidacion").show(); validaciones = false; } } } /** *Si esta editando una editorial */ if($("#idEditorial").val() != 0){ //Validacion cedula if($("#tbxEditorial").val().trim() != "" && $("#descripcionOriginal").val() != $("#tbxEditorial").val().trim()){ if(verficarDatoEnBd('EDITORIAL','DESCRIPCION',$("#tbxEditorial").val().trim())){ $("#msgValidacion").text("Editorial ya registrada"); $("#msgValidacion").show(); validaciones = false; } } } if(validaciones){ $("#msgValidacion").text(""); $("#msgValidacion").hide(); $("#formAddEditorial").submit(); } } /** *Funcion encargada de listar los usuarios */ function listadoEditoriales(){ $.ajax({ type : "POST", async: false, dataType: 'json', url : "../../../util/ControllerGeneral.php", data : { llamadoAjax : "true", opcion : "listadoEditorial" } }).done(function(data) { var html = ""; $.each(data, function (index, item) { html += '<tr>'; html += '<td>'+item.descripcion+'</td>'; html += '<td><input type="radio" name="rbtSeleccion" value='+item.idEditorial+' onClick="cargarEditar('+item.idEditorial+')" ></td>'; html += '</tr>'; }); $("#tblListaEditoriales").append(html); $("#tblListaEditoriales").dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers" }); }); } /** *Funcion encargada de capturar la editorial seleccionada * @param {Object} idEditorial */ function cargarEditar(idEditorial){ $.ajax({ type : "POST", async: false, dataType: 'json', url : "../controllers/EditorialController.php", data : { llamadoAjax : "true", opcion : "capurarEditorialSeleccionada", idEditorial: idEditorial } }).done(function(data) { $("#formListarEditoriales").submit(); }); }
import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import Footer from './footer'; import Header from './header'; import Form from './form'; class Obrigado extends Component{ render(){ return( <div> <Header/> <Form/> <div className="agradecimento"> Obrigado pela inscrição </div> <Link to="/" className="botaoMenu linkColor"> <button>Voltar para Menu</button> </Link> <Footer/> </div> ) } } export default Obrigado;
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue'; import styleImport from 'vite-plugin-style-import'; import vueJsx from '@vitejs/plugin-vue-jsx' // 添加这一句 import path from "path"; // https://vitejs.dev/config/ export default defineConfig({ resolve: { alias: { "@": path.resolve(__dirname, "src"), "components": path.resolve(__dirname, "src/components"), "styles": path.resolve(__dirname, "src/styles"), "plugins": path.resolve(__dirname, "src/plugins"), "views": path.resolve(__dirname, "src/views"), "layouts": path.resolve(__dirname, "src/layouts"), "utils": path.resolve(__dirname, "src/utils"), "apis": path.resolve(__dirname, "src/apis"), "dirs": path.resolve(__dirname, "src/directives"), }, }, plugins: [ vue(), vueJsx(), styleImport({ libs: [ { libraryName: 'vant', esModule: true, resolveStyle: (name) => `vant/es/${name}/style`, }, ], }), ] })
(function(){ 'use strict'; angular .module('app') .controller('AdminModalController', adminModalController); adminModalController.$inject = ['adminService', '$uibModalInstance', 'currentObject']; function adminModalController(adminService, $uibModalInstance, currentObject) { var self = this; //Variables self.alreadyExist = false; self.password = ""; self.password1 = ""; self.currentObject = currentObject; self.duplicateAdminsMessage = false; self.wasNotEditSubjectMessage = false; self.passwordConfirmation = false; self.wrongData = false; //Methods self.create = create; self.update = update; self.cancelForm = cancelForm; function create(){ if (self.password != ""){ if (self.password == self.password1){ self.currentObject.password = self.password; } else { self.passwordConfirmation = true; return; } } if(adminService.duplicateLogin(self.currentObject.username)){ self.duplicateAdminsMessage = true; return; } adminService.createAdmin(self.currentObject) .then(complete); } function cancelForm () { $uibModalInstance.dismiss(); } function update(){ if (self.password != ""){ if (self.password == self.password1){ self.currentObject.password = self.password; } else { self.passwordConfirmation = true; return; } } else { delete(self.currentObject.password); } if(adminService.duplicateLogin(self.currentObject.username)){ self.duplicateAdminsMessage = true; return; } adminService.editAdmin(self.currentObject) .then(complete); } function complete(response) { if(response.status == 200 && response.data.response === "Failed to validate array") { self.wrongData = true; return; } if(response.data.response === "ok") { $uibModalInstance.close(); } } } }());
let handler = async (m, { conn }) => { conn.reply(m.chat,`“${pickRandom(global.bucin)}”`, m) } handler.help = ['bucin'] handler.tags = ['quotes'] handler.command = /^(bucin)$/i handler.owner = false handler.mods = false handler.premium = false handler.group = false handler.private = false handler.admin = false handler.botAdmin = false handler.fail = null module.exports = handler function pickRandom(list) { return list[Math.floor(list.length * Math.random())] } // https://jalantikus.com/tips/kata-kata-bucin/ global.bucin = [ "Escolho ficar sozinha, não por esperar o perfeito, mas preciso que nunca desista.", "Uma única pessoa foi criada com um parceiro que ele não havia encontrado.", "Solteiros. Talvez seja a maneira de Deus dizer 'Descansa do amor errado'.", "Solteiros são jovens que priorizam o desenvolvimento pessoal para um amor mais elegante depois.", "Não procuro alguém que seja perfeito, mas procuro alguém que se torna perfeito graças à minha força.", "O namorado de alguém é nossa alma gêmea pendente.", "Os solteiros devem passar. Chega um momento em que toda solidão se torna uma união com seu amante halal. Seja paciente.", "Romeu está disposto a morrer por Julieta, Jack morreu porque salvou Rose. A questão é, se você ainda quer viver, seja solteiro.", "Procuro pessoas não com base nas suas qualidades, mas procuro pessoas com base na sua sinceridade.", "Matchmaking não é flip-flops, que muitas vezes são confundidos. Portanto, você deve continuar na luta que deveria estar.", "Se você é a corda do violão, não quero ser o guitarrista. Porque não quero terminar com você.", "Se amar você é uma ilusão, deixe-me imaginar para sempre.", "Querida ... Meu trabalho é só te amar, não contra o destino.", "Quando estou com você, parece que dura 1 hora e apenas 1 segundo, mas se estou longe de você, parece que 1 dia se transforma em 1 ano.", "A compota de banana sabe suedang, embora a distância se estenda, meu amor nunca irá desaparecer.", "Eu quero ser o único, não o único.", "Não posso prometer ser bom. Mas prometo estar sempre ao seu lado.", "Se eu me tornar o representante do povo, definitivamente fracassarei, como você gostaria de pensar no povo se tudo o que tenho em mente é você.", "Olha o meu jardim, cheio de flores. Olha os teus olhos, o meu coração desabrocha.", "Prometa estar comigo agora, amanhã e para sempre.", "A falta surge não só por causa da distância. Mas também por causa de desejos que não se realizam.", "Você nunca estará longe de mim, onde quer que eu vá, você está sempre lá, porque você está sempre no meu coração, que é apenas o nosso corpo, não o nosso coração.", ]
const requestWorkers = new XMLHttpRequest(); requestWorkers.onreadystatechange = function () { if (requestWorkers.readyState === 4) { const employees = JSON.parse(requestWorkers.responseText); let statusHTML = '<ul class="bulleted">'; employees.forEach( (e) => { if (e.inoffice) { statusHTML += '<li class="in">'; } else { statusHTML += '<li class="out">'; } statusHTML += e.name + "</li>"; }); statusHTML += '</ul>'; document.getElementById('employeeList').innerHTML = statusHTML; } }; requestWorkers.open('GET', 'data/employees.json'); requestWorkers.send(); const requestRooms = new XMLHttpRequest(); requestRooms.onreadystatechange = function () { if (requestRooms.readyState === 4) { const rooms = JSON.parse(requestRooms.responseText); let statusHTML = '<ul class="rooms">'; rooms.forEach( (e) => { if (e.available) { statusHTML += '<li class="empty">'; } else { statusHTML += '<li class="full">'; } statusHTML += e.room + "</li>"; }); statusHTML += '</ul>'; document.querySelector('#roomList').innerHTML = statusHTML; } }; requestRooms.open('GET', 'data/rooms.json'); requestRooms.send();
var searchData= [ ['excludeprefabs',['excludePrefabs',['../class_set_selection_to_material.html#af55b791f383e5183f1fc09e0b9535011',1,'SetSelectionToMaterial']]] ];
var jparse = { dataUrl : "", markupUrl : "", wrapperElement : "", targetElement : "", parseObj : {}, jParseLog : function(msg){ var has_logger = !!(window.console && window.console.log); if(has_logger){ console.log('jParse: ' + msg); } }, loadData : function(options){ options = options || {}; parseObj = options.parseObj || this.parseObj; transformFunc = options.transformFunc || this.transform; jParseLog = this.jParseLog; $.ajax({ url: options.dataUrl || this.dataUrl, success: function(data){ parseObj.data = transformFunc(data); } }).done(function(){ jParseLog('ajax data call complete.'); options.success && options.success(); }); }, transform : function(theData){ return theData; }, loadMarkup : function(options){ options = options || {}; parseObj = options.parseObj || this.parseObj; jParseLog = this.jParseLog; $.ajax({ url: options.markupUrl || this.markupUrl, success: function(markup){ parseObj.markup = markup; } }).done(function(){ jParseLog('ajax markup call complete.'); options.success && options.success(); }); }, displayItems : function(options){ options = options || {}; parseObj = options.parseObj || this.parseObj; theWrapper = options.wrapperElement || this.wrapperElement; theContainer = options.targetElement || this.targetElement; theItems = parseObj.data.items; theTemplate = parseObj.markup; jParseLog = this.jParseLog; var wrapperInstance = $(theWrapper).clone(); for(x=0;x<theItems.length;x++){ var itemInstance = $(theTemplate).clone(); // populate text nodes itemTextTargets = itemInstance.find('[data-text]').addBack('[data-text]'); $(itemTextTargets).each(function(index){ $(this).text(theItems[x][$(this).attr('data-text')]); }); // populate id attributes itemIdTargets = itemInstance.find('[data-id]').addBack('[data-id]'); $(itemIdTargets).each(function(index){ $(this).attr("id",theItems[x][$(this).attr('data-id')]); }); // populate (replace) data-type attribute // (should be external custom binding function...) itemTypeTargets = itemInstance.find('[data-type]').addBack('[data-type]'); $(itemTypeTargets).each(function(index){ $(this).attr("data-type",theItems[x][$(this).attr('data-type')]); }); (theWrapper == "") ? itemInstance.appendTo(theContainer) : itemInstance.appendTo(wrapperInstance); } if(theWrapper != ""){ wrapperInstance.appendTo(theContainer); } jParseLog('display of items complete.'); options.success && options.success(); }, jLoadData : function(options){ return this.loadData(options); }, jLoadMarkup : function(options){ return this.loadMarkup(options); }, jDisplayItems : function(options){ return this.displayItems(options); } }; $(function(){ $.extend(jparse); $.jParseLog('jParse instantiated!'); });
// Friends file for Creating, Reading, Updating, and Deleting // Friends and Friend Management var admin = require("firebase-admin"); var firebase = require("../firebase/admin"); require("firebase/firestore"); // Firestore const db = firebase.firestore(); const usersCollection = db.collection("users"); // Friend Color Constants const COLOR1 = "#FE5951"; // > 15 days const COLOR2 = "#FC6C58"; // > 10 days const COLOR3 = "#FA7D5D"; // > 7 days const COLOR4 = "#F88E63"; // > 5 days const COLOR5 = "#F69D68"; // > 4 days const COLOR6 = "#FBBA7C"; // > 3 days const COLOR7 = "#F7C748"; // > 2 days const COLOR8 = "#F9D94C"; // < 2 days // Time Constants const SECOND = 1000; const DAY15 = 1296000; const DAY12 = 864000; const DAY7 = 604800; const DAY5 = 432000; const DAY4 = 345600; const DAY3 = 259200; const DAY2 = 172800; // Helper Functions /** * Calculate how long ago the last hug was between user and friend * and returns the proper color for the friends list * @param {timestamp} last_hug_date * @return {string} color */ function calculateFriendColor(last_hug_date) { // Times let dateInSeconds = Math.floor(Date.now() / SECOND); let hugDateInSeconds = last_hug_date.seconds; // Time since last hug in seconds let diff = dateInSeconds - hugDateInSeconds; // Convert difference to color accordingly if (diff > DAY15) { // > 15 days return COLOR1; } else if (diff > DAY12) { // > 10 days return COLOR2; } else if (diff > DAY7) { // > 7 days return COLOR3; } else if (diff > DAY5) { // > 5 days return COLOR4; } else if (diff > DAY4) { // > 4 days return COLOR5; } else if (diff > DAY3) { // > 3 days return COLOR6; } else if (diff > DAY2) { // > 2 days return COLOR7; } else { return COLOR8; // <= 2 days } } /** * Helper function to get user information out of a Firebase document * and return as a friend object * @param {Document} userDoc * @return {JSON} friend object */ function userFill(userDoc) { let friend = { user_id: userDoc.id, name: userDoc.get("first_name") + " " + userDoc.get("last_name"), username: userDoc.get("username"), profile_pic: userDoc.get("profile_pic"), // Storage }; return friend; } // Exported APIs const FriendsAPI = { /** * Add a new friend to the user * @param {string} userId * @param {string} friendId */ addFriend: async function (userId, friendId) { let userQuery = await usersCollection.doc(userId).get(); let friendQuery = await usersCollection.doc(friendId).get(); if (!userQuery.exists || !friendQuery.exists) { return { out: "User or friend doesn't exist!" }; } // Add friend to user await usersCollection .doc(userId) .collection("friends") .doc(friendId) .set({ // Priority new friend to top of list last_hug_date: new admin.firestore.Timestamp(0, 0), // seconds, nanoseconds user_ref: usersCollection.doc(friendId), }); // Add user to friend await usersCollection .doc(friendId) .collection("friends") .doc(userId) .set({ // Priority new friend to top of list last_hug_date: new admin.firestore.Timestamp(0, 0), // seconds, nanoseconds user_ref: usersCollection.doc(userId), }); return { out: true }; }, /** * Remove a friend from the user * @param {string} userId * @param {string} friendId */ removeFriend: function (userId, friendId) { // Remove friend from user usersCollection .doc(userId) .collection("friends") .doc(friendId) .delete() .then(function () { console.log("Document successfully deleted!"); }) .catch(function (error) { console.error("Error removing document: ", error); }); // Remove user from friend usersCollection .doc(friendId) .collection("friends") .doc(userId) .delete() .then(function () { console.log("Document successfully deleted!"); }) .catch(function (error) { console.error("Error removing document: ", error); }); }, /** * Check the status of the friend to the user * @param {string} userId * @param {string} friendId * @returns {JSON} friend status */ getFriendStatus: async function (userId, friendId) { let status; // If Friend // if a document by the name of friendId exists let friendRef = usersCollection .doc(userId) .collection("friends") .doc(friendId); await friendRef .get() .then(async (doc) => { // Friend is found if (doc.exists) { status = "friend"; } else { // If Pending // Search through all the friend's notifications for a user_id that matches userId let friendNotificationsRef = usersCollection .doc(friendId) .collection("notifications"); let query = await friendNotificationsRef .where("user_ref", "==", usersCollection.doc(userId)) .get(); // Check if any matching results if (!query.empty) { // Currently Pending status = "pending"; } else { // No notification exists status = "stranger"; } } }) .catch(function (error) { console.log("Error getting document:", error); }); return { status: status }; }, /** * Get all the User's friends and return * @param {String} userId * @return {JSON} All the friends in an array */ getFriendsList: async function (userId) { let friends = []; // friends array let friendsRef = usersCollection.doc(userId).collection("friends"); const friendsSnapshot = await friendsRef.orderBy("last_hug_date").get(); // No friends if (friendsSnapshot.empty) { // console.log("Friends 222 No matching documents."); return { friends: friends }; } let colors = []; let friendPromises = []; // Get all user_id references from friends await friendsSnapshot.forEach(async (friendDoc) => { friendPromises.push(friendDoc.get("user_ref")); colors.push(friendDoc.get("last_hug_date")); }); // Resolve promises for (let i = 0; i < friendPromises.length; i++) { // Get the actual userDocument from the friend stored reference let userDoc = await friendPromises[i].get(); if (!userDoc.exists) { console.log("Friends 240 No such document!"); } else { // Helper function fill let friend = userFill(userDoc); friend.color = calculateFriendColor(colors[i]); // Add friend object to array friends.push(friend); } } // Return the friends return { friends: friends }; }, /** * Update Friend Hug Counts to be used for Friend list sorting * @param {string} user1 * @param {string} user2 * @param {timestamp} date_time */ updateFriendHugDate: function (user1, user2, date_time) { let user1Ref = usersCollection.doc(user1); let user2Ref = usersCollection.doc(user2); // Update user1 who has user2 as a friend user1Ref .collection("friends") .doc(user2) .update({ last_hug_date: date_time, }) .then(console.log(user1 + " friend date updated!")); // Update user2 who has user1 as a friend user2Ref .collection("friends") .doc(user1) .update({ last_hug_date: date_time, }) .then(console.log(user2 + " friend date updated!")); }, }; const FriendSearchAPI = { /** * Search through the user's friends for all friend's first_name * that match the query string * @param {string} userId * @param {string} query */ searchFriends: async function (userId, query) { // Clean and format input query let nameQuery = query.trim(); nameQuery = nameQuery.charAt(0).toUpperCase() + nameQuery.slice(1).toLowerCase(); let userFriendsRef = usersCollection.doc(userId).collection("friends"); let friends = []; let friendPromises = []; // Search through user's friends const friendsSnapshot = await userFriendsRef.get(); // No friends if (friendsSnapshot.empty) { // console.log("Friends 283 No matching documents."); return { friends: friends }; } // Get all user_id references from friends friendsSnapshot.forEach(async (friendDoc) => { friendPromises.push(friendDoc.get("user_ref")); }); // Resolve Promises and get user documents for (let i = 0; i < friendPromises.length; i++) { // Get the actual userDoc from the friend stored reference let userDoc = await friendPromises[i].get(); if (!userDoc.exists) { console.log("Friends 297 No such document!"); } else if (userDoc.get("first_name") === nameQuery) { // If first_name matches nameQuery let friend = userFill(userDoc); // Add friend object to array friends.push(friend); } } return { friends: friends }; }, /** * Search through all users for users' usernames that match * the query username * @param {string} userId * @param {string} query */ searchUsers: async function (userId, query) { // Clean and format input query let usernameQuery = query.trim(); usernameQuery = usernameQuery.toLowerCase(); let username; await usersCollection .doc(userId) .get() .then(function (userDoc) { username = userDoc.get("username"); }); // Check if self if (query === username) { return { user: [] }; } let user; // Get all user matches in firestore let userSnapshot = await usersCollection .where("username", "==", usernameQuery) .get(); // No matches if (userSnapshot.empty) { console.log("No matching documents."); return { user: [] }; } // Go through the snapshot userSnapshot.forEach((userDoc) => { user = userFill(userDoc); }); return { user: user }; }, }; // Export the module module.exports = { FriendsAPI, FriendSearchAPI };
function runTest() { FBTest.openNewTab(basePath + "html/breakpoints/5316/issue5316.html", function(win) { FBTest.openFirebug(function() { FBTest.enableScriptPanel(function() { var chrome = FW.Firebug.chrome; var content = win.document.getElementById("content"); var context = chrome.window.Firebug.currentContext; var BP_BREAKONATTRCHANGE = 1; // Set breakpoint. FBTest.selectPanel("html"); FW.Firebug.HTMLModule.MutationBreakpoints.onModifyBreakpoint(context, content, BP_BREAKONATTRCHANGE); // Select the Script panel and cause Firebug to break. FBTest.selectPanel("script"); breakOnMutation(win, function() { // Reload and cause break again. FBTest.reload(function(win) { breakOnMutation(win, function() { FBTest.testDone(); }); }); }); }); }); }); } function breakOnMutation(win, callback) { var chrome = FW.Firebug.chrome; FBTest.waitForBreakInDebugger(chrome, 20, false, function(sourceRow) { FBTest.sysout("issue5136; before continue"); FBTest.clickContinueButton(chrome); FBTest.progress("The continue button is pushed"); callback(); }); FBTest.click(win.document.getElementById("testButton")); FBTest.sysout("button clicked"); }
import React, { Component } from 'react' import axios from 'axios' import './../components/shop.css' export default class Shop extends Component { constructor() { super() this.state = { itemName: "", itemPrice: null, itemCreated: false, allItems: [], deletedItem: [], itemEdited: false, found: [] } this.handleClick = this.handleClick.bind(this) this.deleteItem = this.deleteItem.bind(this) this.showAllItems = this.showAllItems.bind(this) this.searchItems = this.searchItems.bind(this) } handleChange1(val) { this.setState({ itemName: val }) } handleChange2(val) { this.setState({ itemPrice: val }) } handleClick() { axios.post('http://localhost:8080/api/addItem', { item_name: this.state.itemName, item_price: this.state.itemPrice }) .then(res => ({ itemCreated: true }) ) } showAllItems() { axios.get('http://localhost:8080/api/allItems') .then(res => { this.setState({ allItems: res.data }) }) } deleteItem(id){ axios.delete(`http://localhost:8080/api/deleteItem/${id}`) .then(res => { console.log("DELETE", res) this.setState({ deletedItem: res.data }) }) } editItem(id){ axios.put(`http://localhost:8080/api/editItem/${id}`, { item_name: this.state.itemName, item_price: this.state.itemPrice }) .then(res => { itemEdited: true }) } searchItems(){ axios.get(`http://localhost:8080/api/search?name=${this.state.itemName}`) .then(res => { this.setState({ found: res.data }) // console.log(res.data, "search") }) } render() { console.log("STATE", this.state) return ( <div> <input type="text" onChange={(e) => this.handleChange1(e.target.value)} /> <input type='text' onChange={(e) => this.handleChange2(e.target.value)} /> <button onClick={this.handleClick}>Create Item</button> <button onClick={this.showAllItems}>Show ALL Item</button> <button onClick={this.searchItems}>Search</button> {this.state.allItems.map((item, i) => { return ( <div key={i}> <p>NAME: {item.item_name}</p> <p>PRICE: {item.item_price}</p> <button onClick={() => {this.deleteItem(item.id)}}>X</button> <button onClick={() => {this.editItem()}}>Edit item</button> </div> ) })} {this.state.found.map((item, i) => { return <div key={i}> {item.item_name} {item.item_price} </div> })} </div> ) } }
import React from 'react' import Link from 'gatsby-link' import get from 'lodash/get' import Helmet from 'react-helmet' class Home extends React.Component { render() { const siteTitle = get(this, 'props.data.site.siteMetadata.title') return ( <div className="flex justify-center pv6 pv7-ns"> <Helmet title={siteTitle} /> <div className="ph3"> <div className="fw6 f3 f2-ns mv2">Hey there! I'm Mike.</div> <div className="f4-ns lh-copy">I build things for the internet.</div> </div> </div> ) } } export default Home export const query = graphql` query HomeQuery { site { siteMetadata { title } } } `
import React, { Component } from 'react' import { PropTypes } from 'prop-types'; import { connect } from 'react-redux' import { reduxForm } from 'redux-form' import { firebaseConnect, pathToJS, isLoaded } from 'react-redux-firebase' import { submit } from 'redux-form' import { reduxFirebase as rfConfig } from 'config' import { UserIsAuthenticated } from 'utils/router' import TransferForm from 'components/TransferForm' import { TRANSFER_ETHER_FORM_NAME } from 'constants/formNames' import { sendEther } from 'store/ethereum/web3' @UserIsAuthenticated // redirect to /login if user is not authenticated @firebaseConnect() // add this.props.firebase @connect( // Map redux state to props ({ firebase, web3 }) => ({ auth: pathToJS(firebase, 'auth'), account: pathToJS(firebase, 'profile'), web3: web3 }), { // action for submitting redux-form submitForm: () => (dispatch) => dispatch(submit(TRANSFER_ETHER_FORM_NAME)), onSubmit: (formModel) => (dispatch) => dispatch(sendEther(formModel)) } ) export default class TransferFormContainer extends Component { render() { const { web3, submitForm, onSubmit } = this.props return ( <TransferForm web3={web3} submitForm={submitForm} onSubmit={onSubmit} /> ) } }
var output, sNumber, len, number, third; number = 9999799; output = []; sNumber = number.toString(); len = sNumber.length; for (var i = 0; i < len; i += 1) { output.push(+sNumber.charAt(i)); } third = len-3; if (output[third]===7) { console.log('is 7'); } else { console.log('not 7'); }
Ext.define('eapp.store.Activity', { extend:'Ext.data.Store', config: { model:'eapp.model.Activity', } });
$(document).ready(function() { $('.remove').click(function(e){ e.preventDefault(); var r=confirm('sei sicuro di voler rimuovere quest\'oggetto?'); if(r){ rimuoviOggetto($(this).attr('on')); $(this).parent().parent().remove() } }) }); function rimuoviOggetto(v){ $.ajax({ type : "POST", url : "ShopManager", datatype : "json", mimeType: "textPlain", data : { idRemove : v, }, success : function(data) { if($('tr').length==1) window.location.href=window.location.href; }, fail : function() { alert('niente'); } }); }
import React from "react"; import {useSelector } from "react-redux"; import { Redirect, useParams } from "react-router"; import { contactSelector, editContact } from "../../redux/contactSlice"; import EditForm from "./EditForm"; function Edit() { const { id } = useParams(); const contact = useSelector((state) => contactSelector.selectById(state, id)); if (!contact) { return <Redirect to="/" /> } return ( <div> <div className="edit_home"> <h1>Edit</h1> </div> <EditForm contact={contact} /> </div> ); } export default Edit;
import { TOGGLE_THEME } from "../constants/themeConstants"; export const themeReducer = (state = { darkMode: false }, action) => { switch (action.type) { case TOGGLE_THEME: return { darkMode: !state.darkMode, }; default: return state; } };
/Users/michaelcamarata/Documents/Titanium_Studio_Workspace/VFW_Project4_1409/Resources/Test.js
/* eslint-env mocha */ 'use strict' const chai = require('chai') const dirtyChai = require('dirty-chai') const expect = chai.expect chai.use(dirtyChai) const multiaddr = require('multiaddr') const series = require('async/series') module.exports = (create) => { describe('peer discovery', () => { let ws1 let ws1Listener const base = (id) => { return `/ip4/127.0.0.1/tcp/15555/ws/p2p-webrtc-star/ipfs/${id}` } const ma1 = multiaddr(base('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo3A')) let ws2 const ma2 = multiaddr(base('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo3B')) let ws3 const ma3 = multiaddr(base('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo3C')) let ws4 const ma4 = multiaddr(base('QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSooo3D')) it('listen on the first', (done) => { series([ (cb) => { ws1 = create() ws1Listener = ws1.createListener((conn) => {}) ws1.discovery.start(cb) }, (cb) => { ws1Listener.listen(ma1, cb) } ], (err) => { expect(err).to.not.exist() done() }) }) it('listen on the second, discover the first', (done) => { let listener ws1.discovery.once('peer', (peerInfo) => { expect(peerInfo.multiaddrs.has(ma2)).to.equal(true) done() }) series([ (cb) => { ws2 = create() listener = ws2.createListener((conn) => {}) ws2.discovery.start(cb) }, (cb) => { listener.listen(ma2, cb) } ], (err) => { expect(err).to.not.exist() }) }) // this test is mostly validating the non-discovery test mechanism works it('listen on the third, verify ws-peer is discovered', (done) => { let listener let discoveredPeer = false // resolve on peer discovered ws1.discovery.once('peer', (peerInfo) => { discoveredPeer = true }) ws1Listener.io.once('ws-peer', (maStr) => { expect(discoveredPeer).to.equal(true) done() }) series([ (cb) => { ws3 = create() listener = ws3.createListener((conn) => {}) ws3.discovery.start(cb) }, (cb) => { listener.listen(ma3, cb) } ], (err) => { expect(err).to.not.exist() }) }) it('listen on the fourth, ws-peer is not discovered', (done) => { let listener let discoveredPeer = false // resolve on peer discovered ws1.discovery.once('peer', (peerInfo) => { discoveredPeer = true }) ws1Listener.io.once('ws-peer', (maStr) => { expect(discoveredPeer).to.equal(false) done() }) series([ (cb) => { ws1.discovery.stop(cb) }, (cb) => { ws4 = create() listener = ws4.createListener((conn) => {}) ws4.discovery.start(cb) }, (cb) => { listener.listen(ma4, cb) } ], (err) => { expect(err).to.not.exist() }) }) }) }
import React, { Component } from 'react'; import { Layout, Menu, Breadcrumb , Button } from 'antd'; import { SearchOutlined , DownloadOutlined } from '@ant-design/icons'; import './App.css'; const { Header, Footer, Content } = Layout; const menu = ( <Menu> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/"> General </a> </Menu.Item> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/"> Layout </a> </Menu.Item> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href="http://www.tmall.com/"> Navigation </a> </Menu.Item> </Menu> ); class App extends Component { render() { return ( <Layout> <Header style={{ position: 'fixed', zIndex: 1, width: '100%' }}> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}> <Menu.Item key="1">nav 1</Menu.Item> <Menu.Item key="2">nav 2</Menu.Item> <Menu.Item key="3">nav 3</Menu.Item> </Menu> </Header> <Content className="site-layout" style={{ padding: '0 50px', marginTop: 64 }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Ant Design</Breadcrumb.Item> <Breadcrumb.Item> <a href="">Component</a> </Breadcrumb.Item> <Breadcrumb.Item overlay={menu}> <a href="">General</a> </Breadcrumb.Item> <Breadcrumb.Item>Button</Breadcrumb.Item> </Breadcrumb> <div className="site-layout-background" style={{ padding: 24, minHeight: 380 }}> <Button icon={<SearchOutlined />}>Search</Button> <Button type="primary" icon={<DownloadOutlined />}/> <Button danger>Danger Default</Button> </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer> </Layout> ); } } export default App;
import themes from './theme.data' import ThemeActionTypes from './theme.types' const INITIAL_STATE = { currentTheme: themes['light'] } const themeReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case ThemeActionTypes.SET_THEME: return { ...state, currentTheme: themes[action.payload] } default: return state } } export default themeReducer
var text1 = React.createElement("h1", null, "Hello Dojo!"); ReactDOM.render(text1, document.getElementById("hello")); var text2 = React.createElement("h2", null, "Things I need to do: "); ReactDOM.render(text2, document.getElementById("things")); var list = React.createElement( "ul", { className: "customlist" }, React.createElement("li", {id: "li1"}, "Learn React"), React.createElement("li", {id: "li2"}, "Watch Super Smash Bros. Ultimate videos"), React.createElement("li", {id: "li3"}, "Watch basketball games"), React.createElement("li", {id: "li4"}, "Eat pizza"), React.createElement("li", {id: "li5"}, "Chat with other people online") ); ReactDOM.render(list, document.getElementById("content"));
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "components/f2/index" ], { "0a1c": function(t, e, n) { function o(t, e) { var n = Object.keys(t); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(t); e && (o = o.filter(function(e) { return Object.getOwnPropertyDescriptor(t, e).enumerable; })), n.push.apply(n, o); } return n; } function a(t) { for (var e = 1; e < arguments.length; e++) { var n = null != arguments[e] ? arguments[e] : {}; e % 2 ? o(Object(n), !0).forEach(function(e) { r(t, e, n[e]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(n)) : o(Object(n)).forEach(function(e) { Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(n, e)); }); } return t; } function r(t, e, n) { return e in t ? Object.defineProperty(t, e, { value: n, enumerable: !0, configurable: !0, writable: !0 }) : t[e] = n, t; } function c(t) { if (t) return t.preventDefault || (t.preventDefault = function() {}), t; } Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var i = function(t) { return t && t.__esModule ? t : { default: t }; }(n("e004")), s = { props: { canvasId: { type: String, default: "f2-canvas" }, onInit: Function, opts: Object, source: Array, yLabel: Function, valueFormatter: Function, axisXLabelFormatter: Function }, data: function() { return { hasInit: !1 }; }, computed: { id: function() { return "".concat(this.canvasId, "-").concat(new Date().getTime()); } }, watch: {}, created: function() { this.$watch(function() { return { source: this.source, hasInit: this.hasInit }; }, function(t) { t.source.length > 0 && t.hasInit && this.onChangeData(this.source); }, { immediate: !0 }); }, mounted: function() { var t = this; wx.createSelectorQuery().in(this).select("#".concat(this.id)).fields({ node: !0, size: !0 }).exec(function(e) { var n = e[0], o = n.node, r = n.width, c = n.height, s = o.getContext("2d"), u = wx.getSystemInfoSync().pixelRatio; o.width = r * u, o.height = c * u; var l = { context: s, width: r, height: c, pixelRatio: u }; i.default.Global.fontFamily = "sans-serif"; var f = new i.default.Chart(a(a({}, l), t.opts.global)); t.hasInit = !0, f && (t.chart = f, t.canvasEl = f.get("el")); }); }, methods: { onChangeData: function(t) { var e = this, n = this.opts, o = n.defs, r = n.axis, c = n.axisX, i = n.legend, s = n.color, u = n.area, l = n.area_color, f = n.tooltipOpts, h = void 0 === f ? {} : f, d = {}, p = o.x, v = void 0 === p ? {} : p, b = o.y, m = void 0 === b ? {} : b; this.$nextTick(function() { e.chart.clear(), e.chart.source(t, { x: a({}, v), y: a(a({}, m), {}, { formatter: e.valueFormatter || function(t) { return t; } }) }), e.chart.axis(r[0], r[1]), c && e.chart.axis(c[0], a(a({}, c[1]), {}, { label: c[1].label || e.axisXLabelFormatter || {} })), e.chart.legend(i), e.chart.line().position("x*y").color("type", s).shape("smooth"), u && l && (e.chart.area().position("x*y").color(l).shape("smooth"), e.chart.point().position("x*y").style({ fill: "#fff", lineWidth: 2 }).color(s), d = a(a({}, h), {}, { showCrosshairs: !0, onShow: function(t) { return t.items && t.items.length && t.items.splice(1); } })), e.yLabel && e.chart.axis("y", { label: e.yLabel }), e.chart.tooltip(a(a({}, d), {}, { triggerOn: [ "touchstart", "touchmove" ] })), e.chart.render(); }); }, touchStart: function(t) { var e = this.canvasEl; e && e.dispatchEvent("touchstart", c(t)); }, touchMove: function(t) { var e = this.canvasEl; e && e.dispatchEvent("touchmove", c(t)); }, touchEnd: function(t) { var e = this.canvasEl; e && e.dispatchEvent("touchend", c(t)); } } }; e.default = s; }, "205d": function(t, e, n) { var o = n("2677"); n.n(o).a; }, 2677: function(t, e, n) {}, "4d0a": function(t, e, n) { n.d(e, "b", function() { return o; }), n.d(e, "c", function() { return a; }), n.d(e, "a", function() {}); var o = function() { var t = this; t.$createElement; t._self._c; }, a = []; }, 5064: function(t, e, n) { n.r(e); var o = n("4d0a"), a = n("8454"); for (var r in a) [ "default" ].indexOf(r) < 0 && function(t) { n.d(e, t, function() { return a[t]; }); }(r); n("205d"); var c = n("f0c5"), i = Object(c.a)(a.default, o.b, o.c, !1, null, "09c0ae1a", null, !1, o.a, void 0); e.default = i.exports; }, 8454: function(t, e, n) { n.r(e); var o = n("0a1c"), a = n.n(o); for (var r in o) [ "default" ].indexOf(r) < 0 && function(t) { n.d(e, t, function() { return o[t]; }); }(r); e.default = a.a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "components/f2/index-create-component", { "components/f2/index-create-component": function(t, e, n) { n("543d").createComponent(n("5064")); } }, [ [ "components/f2/index-create-component" ] ] ]);
import React from 'react'; import {View, StyleSheet, Text, ScrollView, Image, TextInput, TouchableOpacity} from 'react-native'; import {AppButton} from "../ui/AppButton"; export const LotChoice = ({navigation}) => { const [cad, onChangeCad] = React.useState(null); return ( <View style={styles.mainWrap}> <Text style={styles.heading}> Добавить участок </Text> <View style={{width: '100%', marginTop: -75}}> <View style={styles.imgWrap}> <Image source={require('../../assets/img/agro1.png')} style={styles.promo} /> </View> <View style={styles.inputWrap}> <Text style={styles.tag}> Введите кадастровый номер участка: </Text> <TextInput style={styles.input} onChangeText={onChangeCad} placeholder={'00:00:0000000:00'} value={cad}/> </View> <View style={styles.ifWrap}> <Text style={styles.tagIf}> или </Text> <TouchableOpacity activeOpacity={0.7} onPress={() => navigation.navigate('MapChoice')}> <Text style={styles.registerLink}> Нарисуйте границы участка на карте </Text> </TouchableOpacity> </View> </View> <View style={styles.buttonWrap}> <AppButton text={'Далее'} onPress={() => navigation.navigate('Map')}/> </View> </View> ) }; const styles = StyleSheet.create({ mainWrap: { flex: 1, backgroundColor: '#f5f5f5', flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'center', paddingVertical: '10%', width: '100%', paddingHorizontal: 20 }, heading: { fontFamily: 'Inter-Bold', fontSize: 24, }, imgWrap: { width: '100%', flexDirection: 'row', justifyContent: 'center' }, promo: { resizeMode: 'contain', width: '100%', zIndex: -100, marginRight: 30 }, inputWrap: { marginTop: -75, width: '100%', flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'center', }, tag: { fontFamily: 'Inter-Medium', fontSize: 18, maxWidth: '90%' }, input: { height: 40, minWidth: '90%', borderBottomWidth: 1, borderBottomColor: '#459F40', marginVertical: '3%', }, buttonWrap: { position: 'absolute', bottom: 10, width: '100%', alignItems: 'center', }, ifWrap: { paddingHorizontal: 20, marginTop: 30 }, tagIf: { textAlign: 'center', fontFamily: 'Inter-Medium', fontSize: 18, maxWidth: '100%', marginBottom: 12 }, registerLink: { textAlign: 'center', marginBottom: '5%', fontFamily: 'Inter-Medium', fontSize: 16, color: '#459F40' } })
/** * @author v.lugovsky * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.app.FREnreport', [ 'BlurAdmin.pages.app.FREnreport.report_sale', 'BlurAdmin.pages.app.FREnreport.report_stock', /* 'BlurAdmin.pages.app.FREnreport.report_sl_001', 'BlurAdmin.pages.app.FREnreport.report_sl_002', 'BlurAdmin.pages.app.FREnreport.report_sl_003', 'BlurAdmin.pages.app.FREnreport.report_sl_004', 'BlurAdmin.pages.app.FREnreport.report_sl_005', 'BlurAdmin.pages.app.FREnreport.report_sl_006', 'BlurAdmin.pages.app.FREnreport.report_sl_007', 'BlurAdmin.pages.app.FREnreport.report_sl_008', 'BlurAdmin.pages.app.FREnreport.report_sl_009', 'BlurAdmin.pages.app.FREnreport.report_sl_010', 'BlurAdmin.pages.app.FREnreport.report_sl_011', 'BlurAdmin.pages.app.FREnreport.report_sl_012', 'BlurAdmin.pages.app.FREnreport.report_sl_013', 'BlurAdmin.pages.app.FREnreport.report_sl_014', */ ]) .config(routeConfig); /** @ngInject */ function routeConfig($stateProvider) { $stateProvider .state('app.FREnreport', { url: '/FREnreport', template : '<ui-view></ui-view>', abstract: true, // controller: 'ReportCtrl', title: 'report.main', sidebarMeta: { icon: 'ion-document-text', order: 1000, }, }); } })();
function myfont(){ var htmlWidth=document.documentElement.clientWidth||document.body.clientWidth; var htmlDom=document.getElementsByTagName('html')[0]; htmlDom.style.fontSize=htmlWidth/20+'px'; } window.onload=function(){ myfont(); var mybtn=document.getElementsByTagName('input'); var littlebox=document.getElementById('ninebox').getElementsByTagName('span'); var count=9,num=3,click=0; var myset; function getRandom(){ var arr=[]; var arrout=[]; //构建数组 for(var i=0;i<count;i++){ arr[i]=i; } for(var i=0;i<num;i++){ var temp=Math.round(Math.random()*(arr.length-1)); arrout.push(arr[temp]); arr.splice(temp,1); } return arrout; } function getcolor(){ var tempcolor=[]; for(var i=0;i<num;i++){ var r=Math.round(Math.random()*255); var g=Math.round(Math.random()*255); var b=Math.round(Math.random()*255); var temp='rgb('+r+','+g+','+b+')'; tempcolor.push(temp); } return tempcolor; } function blingbling(){ var m=getRandom(),n=getcolor(); for(var i=0;i<3;i++){ var a=m[i],b=n[i]; littlebox[a].style.background=b; } setTimeout(renew,500); } function renew(){ for(var i=0;i<count;i++){ littlebox[i].style.background='#FFB000'; } } mybtn[0].onclick=function(){ if(click==0){ clearInterval(myset); myset=setInterval(blingbling,1000); click++; } } mybtn[1].onclick=function(){ clearInterval(myset); click=0; } } window.onresize=function(){ myfont(); }
var config = {attributes: false, childList: true, characterData: false}; var emotes = []; var channelEmotes = []; var globalEmotes = []; var foundChat = false; var htmlBody = $("body")[0]; var channel = "" var channelDisplay = "" $("body").addClass("darkmode") RegExp.escape= function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; var chatLoadedObserver = new MutationObserver(function (mutations, observer) { mutations.forEach(function (mutation) { console.log(mutation) var chatSelector = $(".chat-lines"); if (chatSelector.length > 0) { if (!foundChat){ console.log("Found Chat"); var target = chatSelector[0]; foundChat = true; getChannel(target) //observer.disconnect(); } }else { if (foundChat) console.log("Lost Chat"); foundChat = false; emotes = [] channelEmotes = [] chatObserver.disconnect(); } }) }); var getChannel = function(target){ console.log(window.location.pathname) var loc = window.location.pathname.split("/")[1] console.log(loc) if (loc){ channel = channelDisplay = loc.toLowerCase(); $.getJSON("https://api.twitch.tv/kraken/users/"+channel,function(data){ channelDisplay = data["display_name"] }).fail(function(){console.log("Error retrieving display name")}).always(function(){ fetchEmotes(function(){ chatObserver.observe(target, config); console.log("EMOTES: ",emotes); }); }); }else{ console.log("Couldn't identify channel...Where are you?") console.log(window.location.href) } } chatLoadedObserver.observe(htmlBody, config); // Attach listener that acts when a new chat message appears. var chatObserver = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { mutation.addedNodes.forEach(function (addedNode) { var chatMessage = $(addedNode); if (!chatMessage.is(".chat-line", ".message-line")) { // this isn't a chat message, skip processing. return; } parseMsgHTML(chatMessage); }); }); }); var parseMsgHTML = function (msg) { injectMessageElements(msg); adjustNameColor(msg); }; var injectMessageElements = function(msg) { var msgElement = msg.find(".message") if (!msgElement[0]) return; var contents = msgElement[0].childNodes var s = "" for (var i = 0; i < contents.length; i++){ var e = contents[i]; if (e instanceof Text){ //Check text element for unparsed emotes s += processText(e.data) } else if (e){ s += e.outerHTML } } msgElement.html(s); } var adjustNameColor = function(msg){ var minL = 0.0; var maxL = 0.5; if (isDarkMode()){ minL = 0.60; maxL = 1.0; } nameElement = msg.find(".from"); color = $(nameElement).css("color"); rgb = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); color = "#" + componentToHex(+rgb[1]) + componentToHex(+rgb[2]) + componentToHex(+rgb[3]); console.log(color) $(nameElement).attr("truecolor",color); console.log(minL, maxL) newRgb = clampLightness(hexToRgb(color),minL, maxL); $(nameElement).css("color",rgbToHex(newRgb[0],newRgb[1],newRgb[2])); } var isDarkMode = function(){ return $("body").hasClass("darkmode"); } var processText = function(text,n){ n = n || 0; if (n > 1000) return text; //No infinite recursion pls. if (text && text.trim()){ var s = "" for (var i = 0; i < emotes.length; i++){ var emote = emotes[i]; if (text.length >= emote.name.length){ var re = emote.re; re.lastIndex = 0; var match = re.exec(text); var lastIndex = re.lastIndex if(match){ s += processText(text.substring(0,lastIndex - emote.name.length), n+1) + '<span class="balloon-wrapper">' + '<img class="emoticon' + (emote.ext == "BTTV" ? ' bttv-emo-' + emote.id : "") + '" src="' + emote.url + '" alt="'+ emote.name +'">' + '<div class="balloon balloon--tooltip balloon--up balloon--right mg-t-1">' + '<center>Emote: ' + emote.name + "<br />" + emote.setName + '</center>' + '</div>'+ '</span>'; text = text.substring(lastIndex); i--; } } } return s + text; } return text; } var fetchEmotes = function(callback){ console.log(emotes) if (globalEmotes.length){ getFFZEmotes(null,function(){ getFFZEmotes(channel,function(){ emotes = globalEmotes.concat(channelEmotes) if(callback) callback(); }); }); }else{ getBTTVEmotes(null,function(){ getBTTVEmotes(channel,function(){ getFFZEmotes(null,function(){ getFFZEmotes(channel,function(){ emotes = globalEmotes.concat(channelEmotes) if(callback) callback(); }); }); }); }); } } var getBTTVEmotes = function(chan,callback){ callback = callback || function(){}; var url = "//api.betterttv.net/2/emotes/" if (chan) url = "//api.betterttv.net/2/channels/" + chan.toLowerCase(); var emotes = globalEmotes; if (chan) emotes = channelEmotes; console.log(url) $.getJSON(url, function(data){ if (data.error) return null; for (var i in data["emotes"]){ var emote = data["emotes"][i]; emote.image = new Image(); emote.image.src = data["urlTemplate"].replace("{{id}}",emote.id).replace("{{image}}","1x"); emotes.push({ name: emote.code, owner: emote.channel || "[Global]", setName: (emote.channel ? "Channel: " + channelDisplay : "BetterTTV Global Emote"), image: emote.image, url: emote.image.src, id: emote.id, ext: "BTTV", re: RegExp("(?:^|\\s|&nbsp;|&NBSP;)(" + RegExp.escape(emote.code) + ")(?=$|\\s+)","g") }); } }).fail(function(){console.log("ERROR")}).always(callback); } var getFFZEmotes = function(chan,callback){ callback = callback || function(){}; var url = "//api.frankerfacez.com/v1/set/global" if (chan) url = "//api.frankerfacez.com/v1/room/" + chan.toLowerCase() var emotes = globalEmotes; if (chan) emotes = channelEmotes; $.getJSON(url, function(data){ for (var i in data["sets"]){ //check data["default_sets"] to see if set is contained var set = data["sets"][i]; for (var j in set["emoticons"]){ var emote = set["emoticons"][j]; emote.image = new Image(); emote.image.src = emote.urls[1] emotes.push({ name: emote.name, owner: emote.owner.display_name, setName: (set.title == "Global Emoticons" ? "FFZ Global Emoticons" : "FFZ " + set.title), image: emote.image, url: emote.image.src, id: emote.id, ext: "FFZ", re: RegExp("(?:^|\\s|&nbsp;|&NBSP;)(" + RegExp.escape(emote.name) + ")(?=$|\\s+)","g") }) } } }).always(callback); } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h, s, and l are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. * * @param {number} h The hue * @param {number} s The saturation * @param {number} l The lightness * @return {Array} The RGB representation */ function hslToRgb(h, s, l){ var r, g, b; if(s == 0){ r = g = b = l; // achromatic }else{ var hue2rgb = function hue2rgb(p, q, t){ if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; } /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and l in the set [0, 1]. * * @param {number} r The red color value * @param {number} g The green color value * @param {number} b The blue color value * @return {Array} The HSL representation */ function rgbToHsl(r, g, b){ r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if(max == min){ h = s = 0; // achromatic }else{ var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, l]; } function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [ parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16) ] : null; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } function componentToHex(c) { var hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function clampLightness(rgb, minLightness, maxLightness){ hsl = rgbToHsl(rgb[0],rgb[1],rgb[2]); hsl[2] = Math.max(minLightness, Math.min(maxLightness, hsl[2])); return hslToRgb(hsl[0], hsl[1], hsl[2]); } /* Message Format: <li id="ember4881" class="ember-view message-line chat-line"><div class="indicator"></div> <!----> <span class="timestamp float-left">12:30</span> <!----><!----> <span class="badges float-left"> <!----> </span> <span class="from" style="color:#NAMECOLOR" data-ember-action="4882">TWITCH_USERNAME</span> <span class="colon">:</span> <span class="message" style=""> SOME TEXT <span class="balloon-wrapper"> <img class="emoticon" src="//static-cdn.jtvnw.net/emoticons/v1/245/1.0" srcset="//static-cdn.jtvnw.net/emoticons/v1/245/2.0 2x" alt="ResidentSleeper"> <div class="balloon balloon--tooltip balloon--up balloon--center mg-t-1">ResidentSleeper</div> </span> </span> <!----><!----></li> */
import React from "react"; export const Nav = props => ( <div data-pka-anchor="purple-navigator" style={{ display: "flex", justifyContent: "flex-end", width: "100%", height: "40px", background: "#4B2164" }} > {props.children} </div> ); export const TextLine = props => { const { repeat } = props; return [ ...Object.keys(Array(repeat).fill(null)).map(i => ( <svg key={i} viewBox="0 0 100 4" xmlns="http://www.w3.org/2000/svg"> <rect fill="#EEE" x="0" width="100%" height="2px" rx="2" /> </svg> )), ]; };
function Exposure($target, callback) { this.$target = $target this.callback = callback this.init() this.bindEvent() } Exposure.prototype.init = function() { this.$window = $(window) this.check(this.$target) } Exposure.prototype.bindEvent = function() { var _this = this $(window).on('scroll', function() { _this.check(_this.$target) }) } Exposure.prototype.check = function($node) { var _this = this $node.not('.show').each(function() { if (_this.isShow($(this))) { _this.callback(_this.$target) } console.log('check') }) } Exposure.prototype.isShow = function($node) { var scrollTop = this.$window.scrollTop() var windowHeight = this.$window.height() var nodeHeight = $node.height() var offsetTop = $node.offset().top if (offsetTop < scrollTop + windowHeight && offsetTop + nodeHeight > scrollTop) { $node.addClass('show') return true } else { return false } }
import * as a from './_const' export function loadPage (id) { return { type: a.LOAD_PAGE, payload: { request: { url: `/pages/${id}`, }, }, } }
import '../css/common.css'; // const logMessage = () => { // console.log('Лог при вызове ф-и'); // }; // console.log('Лог до'); // setTimeout(() => { // console.log('Лог при вызове ф-и'); // }, 2000); // console.log('Лог после'); // -------------Отменяем вызов таймаута---------- // console.log('Лог до'); // const logger = time => { // console.log('Лог при вызове ф-и'); // }; // const timerId = setTimeout(logger, 2000, 2000); // // идентификатор таймаута // const shouldCancelTimer = Math.random() > 0.3; // console.log(shouldCancelTimer); // if (shouldCancelTimer) { // clearTimeout(timerId); // // если хотим отчистить таймер, передаем его идентификатор // } // console.log('Лог после'); // ----------Метод setInterval (callback, delay, args) // const logger = time => { // console.log(`Лог каждый ${time}ms - ${Date.now()}`); // }; // console.log('Лог до'); // setInterval(logger, 2000, 2000) // console.log('Лог после'); // ----------------Метод clearInterval(id)---------------- // const logger = time => { // console.log(`Лог каждый ${time}ms - ${Date.now()}`); // }; // const intervalId = setInterval(logger, 2000, 2000); // // идентификатор интервала // const shouldCancelInterval = Math.random() > 0.3; // console.log(shouldCancelInterval); // if (shouldCancelInterval) { // clearInterval(intervalId); // // если хотим отчистить интервал, передаем его идентификатор // } // ------------------------Напоминалка------------------------------- /** * - Показываем и скрываем добавляя/удаляя класс is-visible * - Скрываем через определённое время * - Скрываем при клике * - Не забываем чистить таймер */ // const NOTIFICATION_DELAY = 3000; // let timeoutId = null; // const refs = { // notification: document.querySelector('.js-alert'), // }; // refs.notification.addEventListener('click', onNotificationClick); // showNotification(); // /* // * Функции // */ // function onNotificationClick() { // hideNotification(); // clearTimeout(timeoutId); // } // function showNotification() { // refs.notification.classList.add('is-visible'); // timeoutId = setTimeout(() => { // console.log('Закрываем алерт автоматически чтобы не висел'); // hideNotification(); // }, NOTIFICATION_DELAY); // } // function hideNotification() { // refs.notification.classList.remove('is-visible'); // } const refs = { daysRef: document.querySelector('[data-value="days"]'), hoursRef: document.querySelector('[data-value="hours"]'), minsRef: document.querySelector('[data-value="mins"]'), secsRef: document.querySelector('[data-value="secs"]'), }; console.log(refs.daysRef); class Timer { } const timer = { start() { // const currentDate = Date.now(); const targetDate = new Date('December 1, 2020'); setInterval(() => { const currentDate = Date.now(); // const currentTime = Date.now(); const deltaTime = targetDate - currentDate; const time = getTimeComponents(deltaTime); // const { days, hours, mins, secs } = getTimeComponents(deltaTime); // console.log(currentTime); console.log(deltaTime); // console.log(`Days ${days}, ${hours}::${mins}:${secs}`); updateTimerInterface(time); }, 1000); }, }; timer.start(); // const targetDate = new Date('December 1, 2020'); // const deltaTime = targetDate - currentDate; // console.log(date); function pad(value) { return String(value).padStart(2, '0'); }; function getTimeComponents(time) { const days = pad(Math.floor(time / (1000 * 60 * 60 * 24))); const hours = pad(Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))); const mins = pad(Math.floor((time % (1000 * 60 * 60)) / (1000 * 60))); const secs = pad(Math.floor((time % (1000 * 60)) / 1000)); return { days, hours, mins, secs }; }; function updateTimerInterface({ days, hours, mins, secs }) { refs.daysRef.textContent = `${days}`; refs.hoursRef.textContent = `${hours}`; refs.minsRef.textContent = `${mins}`; refs.secsRef.textContent = `${secs}`; }; // new CountdownTimer({ // selector: '#timer-1', // targetDate: new Date('Jul 17, 2019'), // });
const raiz = function(n) { return n ** 0.5; } // const squareRoot = number => number ** 0.5; console.log(squareRoot(25)); // const squareRoot = function(number) { // return number ** 0.5; // }; // console.log(squareRoot(25)); // function sum(x = 1, y = 1) { // const result = x + y; // return result; // } // const result = sum(); // console.log(result); // function greetings(myName) { // return `Bom dia, ${myName}!` // } // const variable = greetings('Rob'); // console.log(variable);
module.exports = { secret: 'devdacticIsAwesome', database: process.env.DATABASE || 'mongodb://shlomoariel:a1345678@ds153413.mlab.com:53413/user-management', };
import React from 'react'; import {BrowserRouter, Route} from 'react-router-dom'; // Conteúdos do site import Navbar from './components/Navbar'; import Header from './components/Header'; import Portfolio from './components/Portfolio'; import PortfolioModal from './components/PortfolioModal'; import About from './components/About'; import Contact from './components/Contact'; import Footer from './components/Footer'; import Copyright from './components/Copyright'; function App() { return ( <div classNameName='App'> <BrowserRouter> <Navbar /> <Route path='/' exact component={Header} /> <Route path='/Portfolio' component={Portfolio} /> <Route path='/Portfolio' component={PortfolioModal} /> <Route path='/About' component={About} /> <Route path='/Contact' component={Contact} /> <Footer /> <Copyright /> </BrowserRouter> </div> ); } export default App;
import React from 'react'; import PropTypes from 'prop-types'; import CircularProgress from '@material-ui/core/CircularProgress'; import Container from '@material-ui/core/Container'; import { getTemplate } from '../../engine/template.engine'; export default function Layout({ content }) { return ( <Container style={{ margin: '0 auto', textAlign: 'center' }}> {(content && getTemplate(content)) || <CircularProgress />} </Container> ); } Layout.defaultProps = { content: null, }; Layout.propTypes = { content: PropTypes.oneOfType([PropTypes.shape({}), PropTypes.array]), };
import React, { useEffect, useState } from 'react'; import UndoIcon from '@material-ui/icons/Undo'; import SearchIcon from '@material-ui/icons/Search'; import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp'; import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown'; export default function ChatInfoUserData({ isTyping, profileImg, userName, setChatWith, searchMsgText, setSearchMsgText, numOfResFromSearch, chatWith, setCurrMarkPrev }) { const [isSearchOpen,setIsSearchOpen]= useState(false); useEffect(() => { setIsSearchOpen(false); }, [chatWith]) function getNextMark() { if (numOfResFromSearch === 0) return; setCurrMarkPrev(prevState => prevState === numOfResFromSearch ? 1 : prevState + 1) } function getPrevMark() { if (numOfResFromSearch === 0) return; setCurrMarkPrev(prevState => prevState === 1 ? numOfResFromSearch : prevState - 1) } return ( <div className={`user-info ${isTyping ? 'typing' : ''} ${isSearchOpen?'search-open':''}`}> <div className={`flex align-center ${isSearchOpen?'close-when-search-open':''}`}> <img src={profileImg} alt="" /> <div className="flex column"> <span>{userName}</span> {isTyping && <span className="typing">is typing...</span> } </div> </div> {numOfResFromSearch === 0 && searchMsgText && <span className="not-found">Not Found</span> } <div className="flex align-center"> <div> <input className={`search ${isSearchOpen? '':'close'}`} placeholder="Search..." type="text" value={searchMsgText} onChange={({ target }) => { setSearchMsgText(target.value) }} /> </div> <div className={`button ${isSearchOpen? '':'close'}`} onClick={getPrevMark}> <ArrowDropUpIcon /> </div> <div className={`button ${isSearchOpen? '':'close'}`} onClick={getNextMark}> <ArrowDropDownIcon /> </div > <div onClick={()=>{setIsSearchOpen(prevState=>!prevState)}} className="button search-button"> <SearchIcon /> </div> <div className="return button" onClick={() => { setChatWith('') }}> <UndoIcon /> </div> </div> </div> ) }
//根据不同的状态获得不同的标签颜色 function getStateColor(state) { var str = "" if (state == "待确认") { str = "<span class='label label-sm label-warning'>待确认</span>" } if (state == "待出库") { str = "<span class='label label-sm label-danger'>待出库</span>" } if (state == "已出库") { str = "<span class='label label-sm label-primary'>已出库</span>" } if (state == "已完成") { str = "<span class='label label-sm label-success'>已完成</span>" } return str; } //格式化时间戳 function formationDate(shijiancuo) { var datetime = new Date(shijiancuo); var month = datetime.getMonth() + 1; var day = datetime.getDate(); var hours = datetime.getHours(); var minutes = datetime.getMinutes(); var seconds = datetime.getSeconds(); if (month >= 1 && month <= 9) { month = "0" + month; } if (day >= 0 && day <= 9) { day = "0" + day; } if (hours >= 0 && hours <= 9) { hours = "0" + hours; } if (minutes >= 0 && minutes <= 9) { minutes = "0" + minutes; } if (seconds >= 0 && seconds <= 9) { seconds = "0" + seconds; } return datetime.getFullYear() + "-" + month + "-" + day + "&nbsp;" + hours + ":" + minutes + ":" + seconds; } //格式化日期 function formatTime(obj, i) { if (obj == null) { return null; } if (i == 1) { var str = obj.replace('年', '-').replace('月', '-').replace('日', 'T00:00:00.000+0800'); return str; } var str = obj.replace('年', '-').replace('月', '-').replace('日', 'T23:59:59.999+0800'); return str; }
import angular from 'angular'; import coreModule from './core/core.module'; import routesModule from './routes/routes.module'; import homepageModule from './homepage/homepage.module'; import categoryModule from './category/category.module'; import continentModule from './continent/continent.module'; import countryModule from './country/country.module'; import articleModule from './article/article.module'; import playerModule from './player/player.module'; var app = 'app'; angular .module(app, [ coreModule.name, routesModule.name, homepageModule.name, categoryModule.name, continentModule.name, countryModule.name, articleModule.name, playerModule.name ]);
var dessertList = ['Chocolate Cake','Cream Brulee','Cheesecake', 'Keyline Pie','Cherry Cobbler','Chocolate Chip Cookies'] dessertVoting.onshow=function(){ drpDesserts.clear() for (i = 0; i <= dessertList.length - 1; i++) drpDesserts.addItem(dessertList[i]) } btnChoose.onclick=function(){ lblDessert.value = `You picked ${drpDesserts.item}- that's a great dessert!` } btnMe.onclick=function(){ ChangeForm(describeYou) }
const qiniuUploader = require("../../utils/qiniu.js"); const app = getApp(); const util = require('../../utils/util.js') Page({ data: { count: 9, parm: { content: '验证码', title: '哈哈哈' }, imgError: false, phoneError: false, errorMsg: '请输入手机号', order_name: '', imgList: [], etc: '', user_name: '', phone: '', customer_name: '莲雾', email: '', address: '', token: '', isValid: true, feedTime: '', }, // 收费标准 toFeeScale: function () { wx.navigateTo({ url: '../feeScale/feeScale', }) }, // 获取地址 getLocation: function () { let _this = this wx.chooseLocation({ success: function (e) { _this.setData({ address: e.address }) // this.orderInfo.address=e.address; } }) }, // 存储信息 orderItemValue: function (e) { let name = e.target.dataset.name this.data[name] = e.detail.value; }, initQiniu: function () { var options = { region: 'NCN', // 华北区 uptoken: this.data.token, domain: 'http://7xo285.com1.z0.glb.clouddn.com', shouldUseQiniuFileName: false }; qiniuUploader.init(options); }, // 删除图片 delImg: function (e) { var _this = this; var imgList = _this.data.imgList imgList.splice(e.target.dataset.index, 1) _this.setData({ imgList: imgList, count: _this.data.count + 1 }) }, // 选择图片 chooseImageTap: function (e) { let _this = this; wx.showActionSheet({ itemList: ['从相册中选择', '拍照'], itemColor: "#404040", success: function (res) { if (!res.cancel) { if (res.tapIndex == 0) { _this.chooseWxImage('album') } else if (res.tapIndex == 1) { _this.chooseWxImage('camera') } } } }) }, chooseWxImage: function (type) { let _this = this; // _this.initQiniu(); wx.chooseImage({ sizeType: ['original', 'compressed'], sourceType: [type], count: this.data.count, success: function (res) { _this.imgUpload(res); } }) }, // 上传图片 imgUpload: function (res) { var _this = this; for (var i = 0; i < res.tempFilePaths.length; i++) { var filePath = (res.tempFilePaths)[i]; var tmp = filePath.split('.') var fileName = filePath.split('//')[1]; // 交给七牛上传 qiniuUploader.upload(filePath, (res) => { _this.setData({ imgList: _this.data.imgList.concat(res.imageURL), count: _this.data.count - 1, }); }, (error) => { console.error('error: ' + JSON.stringify(error)); } , { region: 'NCN', // 华北区 key: tmp[tmp.length - 2] + '.' + tmp[tmp.length - 1], domain: 'http://p0ry8xouf.bkt.clouddn.com', shouldUseQiniuFileName: false, uptoken: _this.data.token } ); } }, // 预览图片 previewImage: function (e) { let current = e.target.dataset.src; wx.previewImage({ current: current, // 当前显示图片的http链接 urls: this.data.imgList // 需要预览的图片http链接列表 }) }, // 验证信息 toValidParm: function () { var _this = this; var title = '' title = _this.data.imgList == 0 ? '请选择图片' : !_this.data.user_name ? '请填写联系人' : !_this.data.phone ? '请填写手机号' : (_this.data.phone && !/^1[3|4|5|8][0-9]\d{4,8}$/.test(_this.data.phone)) ? '手机号码格式不正确' : !_this.data.customer_name ? '企业名称未填写' : (_this.data.email && !/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g.test(_this.data.email)) ? '邮箱格式不正确' : '' _this.setData({ 'isValid': title ? false : true, 'popErrorMsg': title }) _this.ohShitfadeOut(); }, ohShitfadeOut: function () { var fadeOutTimeout = setTimeout(() => { this.setData({ popErrorMsg: '' }); clearTimeout(fadeOutTimeout); }, 1200); }, // 下单 addOrder: function (e) { var self = this; self.toValidParm(); if (self.data.isValid && (app.globalData.phone == null || app.globalData.phone == '')) { wx.navigateTo({ url: `../detectPhone/detectPhone?phone=${this.data.phone}` }) } else if (self.data.isValid && app.globalData.phone != '') { wx.showLoading({ title: '下单中', }) wx.request({ url: `${util.apiPath}/FE/OrderManage/addOrder`, method: 'POST', header: { 'session-token': app.globalData.token, }, data: { order_name: self.data.order_name, user_name: self.data.user_name, img: self.data.imgList, etc: self.data.etc, phone: self.data.phone, email: self.data.email, customer_name: self.data.customer_name, address: self.data.address }, success: function (res) { if (res.data.code == 200) { self.setData({ imgList: [], user_name: '', etc: '', phone: app.globalData.phone, customer_name: app.globalData.customer_name, email: '', address: '' }) app.globalData.customer_name ? '' : app.globalData.customer_name = self.data.customer_name wx.hideLoading() wx.navigateTo({ url: '../orders/orders' }) } } }) } }, getFeedback: function () { var date = new Date() var hour = date.getHours() date.setHours(hour + 4) this.setData({ feedTime: date.toLocaleString() }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.setData({ token: app.globalData.qiToken, }) //this.doCallback(self.toOrder) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { this.setData({ phone: app.globalData.phone, customer_name: app.globalData.customer_name }) }, /** * 生命周期函数--监听页面显示 */ onShow: function () { this.getFeedback() }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
import React from 'react' import styled from "styled-components"; import {Search} from "../Components/Search" import {UserRFFG, UserCard, Followers} from "../Components/User Related" import {Repos} from "../Components/Repos Related" const Main = () => { return ( <main> <Search></Search> <UserRFFG></UserRFFG> <UserCard></UserCard> <Followers></Followers> <Repos></Repos> </main> ) } export default Main
'use strict'; var _ = require('lodash'); var LuttePlace = require('./luttePlace.model'); // Get list of luttePlaces exports.index = function(req, res) { LuttePlace.find(function (err, luttePlaces) { if(err) { return handleError(res, err); } return res.status(200).json(luttePlaces); }); }; // Get a single luttePlace exports.show = function(req, res) { LuttePlace.findById(req.params.id, function (err, luttePlace) { if(err) { return handleError(res, err); } if(!luttePlace) { return res.status(404).send('Not Found'); } return res.json(luttePlace); }); }; // Creates a new luttePlace in the DB. exports.create = function(req, res) { LuttePlace.create(req.body, function(err, luttePlace) { if(err) { return handleError(res, err); } return res.status(201).json(luttePlace); }); }; // Updates an existing luttePlace in the DB. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } LuttePlace.findById(req.params.id, function (err, luttePlace) { if (err) { return handleError(res, err); } if(!luttePlace) { return res.status(404).send('Not Found'); } var updated = _.merge(luttePlace, req.body); updated.save(function (err) { if (err) { return handleError(res, err); } return res.status(200).json(luttePlace); }); }); }; // Deletes a luttePlace from the DB. exports.destroy = function(req, res) { LuttePlace.findById(req.params.id, function (err, luttePlace) { if(err) { return handleError(res, err); } if(!luttePlace) { return res.status(404).send('Not Found'); } luttePlace.remove(function(err) { if(err) { return handleError(res, err); } return res.status(204).send('No Content'); }); }); }; function handleError(res, err) { return res.status(500).send(err); }
import { graphql, useStaticQuery } from "gatsby" import React from "react" import Image from "gatsby-image" export default function HeroSection() { const data = useStaticQuery(graphql` query { file(relativePath: { eq: "screens.png" }) { childImageSharp { fluid(quality: 100) { ...GatsbyImageSharpFluid } } } } `) return ( <section className="relative text-white bg-darkBlack"> <div className="container flex flex-col items-center justify-between h-full px-5"> <div> <h1 className="max-w-2xl mx-auto mb-10 text-5xl text-center mt-14 lg:text-7xl"> Work at the speed of thought </h1> <p className="max-w-xl px-10 mx-auto mb-20 text-xl text-center lg:px-0"> Most calendars are designed for teams. Slate is designed for freelancers who want a simple way to plan their schedule. </p> </div> <div className="flex flex-col mb-10 lg:flex-row"> <button className="z-50 px-10 py-4 mb-5 transition-transform duration-200 transform lg:mb-0 lg:mr-8 hover:-translate-y-1 bg-primary"> Try For Free </button> <button className="z-50 px-10 py-4 transition-transform duration-200 transform border border-white hover:-translate-y-1"> Learn More </button> </div> <div className="w-full"> <Image fluid={data.file.childImageSharp.fluid} /> </div> <div className="absolute bottom-0 z-50 w-full h-1/6 lg:h-2/6" style={{ background: "linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, #0E0E0E 66.15%)", }} ></div> </div> </section> ) }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsVerticalDistribute = { name: 'vertical_distribute', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M22 2v2H2V2h20zM7 10.5v3h10v-3H7zM2 20v2h20v-2H2z"/></svg>` };
const express = require("express"); const router = express.Router(); const {User} = require("../models/users"); const passport = require("passport"); const passportLocal = require("passport-local"); const catchAsync = require("../utils/catchAsync"); router.get("/register" , (req , res) => { res.render("users/register"); }) router.post("/register" , catchAsync(async (req , res) => { try { const {email , username , password} = req.body; const user = new User({email , username}); const newUser = await User.register(user , password); await req.login(newUser , function(err) { if (err) return next(err); else { req.flash("success" , "Welcome to the YelpCamp") res.redirect("/campgrounds"); } }) } catch (err) { req.flash('fail' , err.message); res.redirect("/register"); } })); router.get("/login" , (req , res) => { res.render("users/login"); }) router.post("/login" , passport.authenticate("local" , {failureFlash : true , successFlash : "Welcome Back!" , failureRedirect : "/login"}) , (req , res) => { const redirect = req.session.redirect || "/campgrounds"; req.session.redirect = null; res.redirect(redirect); }) router.get("/logout" , (req , res) => { req.logout(); req.flash("success" , "GoodBye! Hope to see ya soon!"); res.redirect("/campgrounds"); }) module.exports = router;
var RiftDataMapLabel = function () { _render = function () { } }
import React from "react"; import { Link } from "react-router-dom"; import ReactSVG from 'react-svg' import PropTypes from "prop-types"; import { Image } from 'semantic-ui-react' import styles from "./styles.module.scss"; import { WEBSITE_PATH } from "../../config/constants" const HomeScreen = (props, context) => ( <div className={styles.RootDivision}> <div className={styles.OutterDivision} > <div className={styles.TopDivision}> {/* <ReactSVG className={styles.LeftLogoImage} src={require("images/logos/gemtown_logo.svg")} /> */} <Image className={styles.LogoImage} src={require("images/logos/gemtown_logo_with_text_white.png")} // size="small" /> </div> <div className={styles.Top2Division}> <Image className={styles.IconImage} src={require("images/icons/png/home_star.png")} // size="small" /> <ReactSVG className={styles.DescriptionSvgIcon} src={require("images/icons/svg/home_description_text.svg")} svgStyle={{width: "250px", height: "100px"}} /> </div> <div className={styles.MiddleDivision}> <div className={styles.MenuDivision}> <Link to={WEBSITE_PATH.MUSIC} > <div className={styles.InnerDivision}> <ReactSVG className={styles.LeftSvgIcon} src={require("images/icons/svg/home_music_icon.svg")} svgStyle={{width: "30px", height: "30px"}} /> <ReactSVG className={styles.RightSvgIcon} src={require("images/icons/svg/home_music_text.svg")} svgStyle={{width: "150px", height: "40px"}} /> </div> </Link> </div> <div className={styles.MenuDivision}> <Link to={WEBSITE_PATH.MODEL} > <div className={styles.InnerDivision}> <ReactSVG className={styles.LeftSvgIcon} src={require("images/icons/svg/home_model_icon.svg")} svgStyle={{width: "30px", height: "30px"}} /> <ReactSVG className={styles.RightSvgIcon} src={require("images/icons/svg/home_model_text.svg")} svgStyle={{width: "150px", height: "40px"}} /> </div> </Link> </div> <div className={styles.MenuDivision}> <div className={styles.InnerDivision}> <ReactSVG className={styles.LeftSvgIcon} src={require("images/icons/svg/home_story_icon.svg")} svgStyle={{width: "30px", height: "30px"}} /> <ReactSVG className={styles.RightSvgIcon} src={require("images/icons/svg/home_story_text.svg")} svgStyle={{width: "150px", height: "40px"}} /> </div> </div> <div className={styles.MenuDivision}> <div className={styles.InnerDivision}> <ReactSVG className={styles.LeftSvgIcon} src={require("images/icons/svg/home_video_icon.svg")} svgStyle={{width: "30px", height: "30px"}} /> <ReactSVG className={styles.RightSvgIcon} src={require("images/icons/svg/home_video_text.svg")} svgStyle={{width: "150px", height: "40px"}} /> </div> </div> </div> <div className={styles.BottomDivision}> <div className={styles.InnerDivision}> <ReactSVG className={styles.LeftSvgIcon} src={require("images/icons/svg/home_logo_symbol.svg")} svgStyle={{width: "25px", height: "25px"}} /> <p className={styles.Text}>©2019 GEMTOWN CORP. ALL RIGHTS RESERVED</p> </div> </div> </div> </div> ) HomeScreen.propTypes = { } HomeScreen.contextTypes = { t: PropTypes.func.isRequired }; export default HomeScreen;
var turn = 0; var currentGame; var attachListeners = function() { $("td").click(function(event) { doTurn(event); }); $("#previous").click(function() { getAllGames(); }); $("#save").click(function() { saveGame(); }); } var doTurn = function(event) { var cell = event.target; if($(cell).text() === "") { updateState(event); checkWinner(); turn += 1; } } var updateState = function(event) { var cell = event.target; $(cell).text(player()); } var player = function() { if(turn % 2 === 0) { return "X" } else { return "O" } } var checkWinner = function() { const winningCombos = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; var state = $("td").map(function(i,td) { return $(td).text() }).toArray(); var won = false; winningCombos.forEach(function(combo) { var currentCombo = [state[combo[0]], state[combo[1]], state[combo[2]]]; if((currentCombo[0] === "X" && currentCombo[1] === "X" && currentCombo[2] === "X") || (currentCombo[0] === "O" && currentCombo[1] === "O" && currentCombo[2] === "O")) { message("Player " + player() + " Won!"); resetGame(); won = true; } }); if(won === false && state.every(function(token){ return token === "X" || token === "O"; })){ message("Tie game"); resetGame(); } return won; } function message(string) { $("#message").text(string); } var resetGame = function() { saveGame(); resetBoard(); turn = -1; currentGame = 0; } var resetBoard = function() { $("td").each(function() { $("#id").text(""); $(this).html(""); }); } var getAllGames = function() { $.get("/games", function(data) { if(data["games"].length !== 0) { var gamesHTML = ''; data["games"].forEach(function(game){ gamesHTML += '<li data-gameid="'; gamesHTML += game["id"]; gamesHTML += '" onclick="loadGame(this);">'; gamesHTML += game["id"].toString(); gamesHTML += '</li>'; }); $("#games").html(gamesHTML); } }); $("li").click(function() { loadGame(); }); } var saveGame = function() { var state = $("td").map(function(i,td) { return $(td).text() }).toArray(); currentGame = $("#id").text(); if(currentGame == ""){ var posting = $.post("/games", {"game": { "state": state }}, function(data) { $("#id").text(data["game"]["id"]) }); } else { $.ajax({ url: '/games/' + currentGame, type: 'PATCH', data: { "game": {"state": state }} }); } } var loadGame = function(listItem) { var id = listItem.innerText; currentGame = id; $("#id").text(id); $.get("/games", function(data){ var game = data["games"][id-1]; $("td").each(function(index, cell){ cell.innerHTML = game["state"][index]; }) $("#id").text(data["games"]["id"]); var numOfBlankCells = $("td").toArray().filter(function(cell){ return cell.innerHTML === ""; }).length turn = 10 - numOfBlankCells; }) } $(document).ready(function() { attachListeners(); });
define(['jquery','common','nprogress','template'], function ($,undefined,nprogress,template) { //该页所有的js加载完毕,js结束 nprogress.done(); //渲染讲师列表 $.get('/v6/teacher', function (data) { if(data.code==200){ var html = template('teacher-list-tpl',{list:data.result}); //console.log( $('#teacher-list-tbody')); $('#teacher-list-tbody').html(html); } }); });
export default function isIterable(thing) { return ( thing != null && typeof thing[Symbol.iterator] === 'function' ) }
import {pageSize, pageSizeType, description, searchConfig} from '../../globalConfig'; const controls = [ {key: 'serviceName', title: '所属服务名', type: 'text', required: true}, {key: 'serviceExplain', title: '服务名说明', type: 'text', required: true} ]; const index = { pageSize, pageSizeType, description, searchConfig }; const edit = { controls, edit: '编辑', add: '新增', config: {ok: '确定', cancel: '取消'} }; const addConfig = { index, edit }; export default addConfig;
const chai = require('chai'); const assert = chai.assert; describe('/lib/strategies/api-strategy-config', function(){ console.log("Loading api-strategy-config-test.js"); var Config; before(function(){ Config = require("../lib/strategies/api-strategy-config"); }); beforeEach(function(){ delete process.env.VCAP_SERVICES; delete process.env.VCAP_APPLICATION; delete process.env.redirectUri; }); describe("#getConfig(), #getTenantId, #getServerUrl", function(){ it("Should fail since there's no options argument nor VCAP_SERVICES", function(){ var config = new Config(); assert.isObject(config); assert.isObject(config.getConfig()); assert.isUndefined(config.getTenantId()); assert.isUndefined(config.getServerUrl()); }) it("Should succeed and get config from options argument", function(){ var config = new Config({ tenantId: "abcd", serverUrl: "http://abcd" }); assert.isObject(config); assert.isObject(config.getConfig()); assert.equal(config.getTenantId(), "abcd"); assert.equal(config.getServerUrl(), "http://abcd"); }); it("Should succeed and get config from VCAP_SERVICES", function(){ process.env.VCAP_SERVICES = JSON.stringify({ AdvancedMobileAccess: [ { credentials: { tenantId: "abcd", serverUrl: "http://abcd" } } ] }); var config = new Config(); assert.isObject(config); assert.isObject(config.getConfig()); assert.equal(config.getTenantId(), "abcd"); assert.equal(config.getServerUrl(), "http://abcd"); }); }) });
console.log('Weekend project 7'); // First step // Create an object const listOfBooks = [ { title: 'Night of the knight', author: 'Jeritiko', genre: 'Fantasy', pages: 230, id: Date.now(), read: true, }, { title: 'The lord of the rings', author: 'William', genre: 'Story', pages: 340, id: Date.now(), read: false, }, { title: 'Lolita', author: 'Vlamire', genre: 'Story', pages: 140, id: Date.now(), read: true, }, ]; const bookForm = document.querySelector('.book_form'); const bookList = document.querySelector('.book_list'); const newBookLists = document.querySelector('.book-lists'); console.log(bookForm, bookList); const bookLists = () => { const html = listOfBooks.map(book => { return ` <li class="book_item" id="${book.id}"> <span class="itemTitle">${book.title}</span> <span class="itemAuthor">${book.author}</span> <span class="itemGenre">${book.genre}</span> <span class="itemPages">${book.pages}</span> <input ${book.read ? 'checked' : ''} value="book.id" type="checkbox"> <button class="delete_btn" aria-label="Remove" value="item.id">✖️</button> </li> `; }).join(''); bookList.innerHTML = html; } let myItems = []; const handleToSubmit = e => { // debugger; e.preventDefault(); const form = e.currentTarget; const title = form.title.value; const author = form.author.value; const genre = form.genre.value; const pages = form.pages.value; const read = form.status.value; console.log(title); const item = { title: `${title}`, author: `${author}`, genre: `${genre}`, pages: `${pages}`, id: Date.now(), read: `${read}`, }; myItems.push(item); console.log(myItems); e.target.reset(); bookList.dispatchEvent(new CustomEvent('itemUpdated')); }; const newBookList = e => { e.preventDefault(); const newhtml = myItems.map(item => ` <li class="book_item" id="${item.id}"> <span class="itemTitle">${item.title}</span> <span class="itemAuthor">${item.author}</span> <span class="itemGenre">${item.genre}</span> <span class="itemPages">${item.pages}</span> <input ${item.read === "Read" ? 'checked' : ''} value="book.id" type="checkbox"> <button class="delete_btn" aria-label="Remove" value="item.id">✖️</button> </li> `).join(''); newBookLists.innerHTML = newhtml; // bookList.insertAdjacentHTML('beforeend',newhtml); console.log(bookList); } // delete list const handleDeleteList = (e) => { if(e.target.classList.contains('delete_btn')) { const deleteList = e.target; deleteList.closest('.book_item').remove(); } } document.addEventListener('click', handleDeleteList); window.addEventListener('DOMContentLoaded', bookLists); bookForm.addEventListener('submit', handleToSubmit); bookList.addEventListener('itemUpdated', newBookList);
"use strict"; var bImage = null; var tiles = []; var imgPrefix = "img/"; var mobile = !location.hash.includes('desktop') && (navigator.userAgent.match(/Mobil/) !== null || location.hash.includes('mobile')); var numTiles = 24; var perm = (function () { var perm = []; for (var i = 0; i < numTiles; i++) { perm.push(i + 1); } shuffleArray(perm); return perm; })(); function draw(tile) { var ctx = tile.doorCanvas.getContext("2d"); var iwidth = bImage.oWidth; var factor = iwidth / compWidth(bImage.img); var width = compWidth(tile.doorCanvas); var height = compHeight(tile.doorCanvas); var ix = parseInt(tile.main.style.left); var iy = parseInt(tile.main.style.top); ix *= factor; iy *= factor; ctx.drawImage(bImage.img, ix, iy, width * factor, height * factor, 0, 0, width, height); } function size(tile, x, y) { tile.main.style.width = x + 'px'; tile.main.style.maxWidth = x + 'px'; tile.main.style.height = y + 'px'; tile.doorCanvas.width = x; tile.doorCanvas.height = y; tile.number.style.fontSize = y * tile.fontScale + 'px'; draw(tile); } function move(tile, x, y) { var elem = tile.main; elem.style.top = y + 'px'; elem.style.left = x + 'px'; draw(tile); } function BImage(file) { this.main = Div("image-cropper"); this.main.style.height = sizes.screenHeight + 'px'; this.img = Elem("img"); var me = this; this.img.onload = function () { me.oWidth = me.img.naturalWidth; me.oHeight = me.img.naturalHeight; moveTiles(); }; this.img.src = file; this.oWidth = this.img.naturlaWidth; this.oHeight = this.img.naturalHeight; this.main.appendChild(this.img); } BImage.prototype.zoom = function (landscape) { if (landscape) { this.img.style.width = "100%"; this.img.style.height = "auto"; } else { this.img.style.width = "auto"; this.img.style.height = "100%"; } }; function createTiles(area) { var tileWidth = sizes.tileWidth; var tileHeight = sizes.tileHeight; for (var i = 0; i < numTiles; i++) { var j = perm[i]; var song = songs[j] !== undefined ? songs[j]: null; var t = new lib.Tile(tileWidth, tileHeight, song, j); tiles.push(t); area.appendChild(t.main); } } function moveTiles() { var imageAR = bImage.oWidth / bImage.oHeight; var aR = sizes.screenWidth / sizes.screenHeight; var top = sizes.vborder; var left = sizes.hborder; var width = sizes.screenWidth; var vspace = sizes.vspace; var hspace = sizes.hspace; var tilesPerRow = sizes.tilesPerRow; var tileWidth = sizes.tileWidth; var tileHeight = sizes.tileHeight; var x = left; var y = top; bImage.zoom(aR > imageAR); for (var i = 0; i < tiles.length; i++) { move(tiles[i], x, y); x = x + tileWidth + hspace; if ((i + 1) % tilesPerRow === 0) { x = left; y = y + tileHeight + vspace; } } } function init() { var area = new lib.Main(); var img = new BImage("landscape_v.jpg"); bImage = img; area.main.appendChild(img.main); document.body.appendChild(area.main); createTiles(area.main); moveTiles(); } function ready(f) { document.addEventListener("DOMContentLoaded", function(event) { f(); }); } if (!(mobile)) { var lib = libDesktop; var sizes = new lib.Sizes(); ready(init); } else { var lib = libMobile; var sizes = new lib.Sizes(); ready(init); }
import styled from 'styled-components'; import BasicP from '../P'; const P = styled(BasicP)` margin: 0; font-size: calc(1.03vw + 1.03vh + 1.03vmin); `; export default P;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { createServer, Model, Factory, Response } from "miragejs" import img1 from './assets/1.jpg'; import img2 from './assets/2.jpg'; import img3 from './assets/3.jpg'; const articlesPerPage = 5 const imgs = [ img1, img2, img3 ] const titles = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit', 'Cras malesuada ligula erat, non egestas risus congue sit amet.', 'Vivamus euismod a tellus eget interdum. Aenean ac.' ] const contents = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper quam et ultricies porta. Suspendisse semper pulvinar justo at maximus. Etiam a ex eu libero laoreet molestie. Nam tristique iaculis eros, vel efficitur urna lobortis in. Praesent consectetur quam quis nisi pellentesque vulputate. Aliquam vitae nibh libero. Morbi consequat ultricies enim quis tristique. Duis at odio non eros ornare volutpat et sed libero. Sed at turpis odio.', 'Cras malesuada ligula erat, non egestas risus congue sit amet. Vestibulum pretium non odio sit amet vehicula. Nunc lobortis tristique sapien, ac condimentum lorem interdum eget. Aenean imperdiet felis finibus metus aliquam euismod. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sodales, ipsum faucibus consequat tincidunt, enim leo posuere neque, sed auctor nisi velit sit amet nisl.', 'Aliquam vulputate mi in vulputate aliquam. Mauris ultrices vel felis eget tempus. Morbi a est at lacus malesuada ultrices ac quis turpis. Curabitur ante metus, malesuada eget neque eu, ornare suscipit ligula. Aliquam suscipit cursus eros, ut tincidunt nulla laoreet a. Donec aliquam urna vel pellentesque sodales.' ] function randomImg() { let index = Math.floor(Math.random() * 3) return imgs[index] } function randomTitle() { let index = Math.floor(Math.random() * 3) return titles[index] } function randomContent() { let index = Math.floor(Math.random() * 3) return contents[index] } createServer({ models: { article: Model }, factories: { article: Factory.extend({ image: () => randomImg(), title: () => randomTitle(), content: () => randomContent() }) }, seeds(server) { server.createList('article', 16); }, routes() { this.get("/api/articles", (schema) => { let articles = schema.articles.all().sort((a, b) => { return b.id - a.id; }); return articles; }); this.get("/api/articles/page/:page", (schema, request) => { let articles = schema.articles.all().sort((a, b) => { return b.id - a.id; }); let articlesCount = articles.length let pageCount = Math.ceil(articlesCount / articlesPerPage) let page = request.params.page - 1; let start = page * articlesPerPage let end = start + articlesPerPage articles = articles.slice(start, end).models return {articles, pageCount, articlesCount} }); this.get("/api/articles/:id", (schema, request) => { let id = request.params.id; return schema.find('article', id); }); this.patch("/api/articles/:id", (schema, request) => { let id = request.params.id; let attrs = request.requestBody; return schema.find('article', id).update(attrs); }); this.del("/api/articles/:id", (schema, request) => { let id = request.params.id; return schema.find('article', id).destroy(); }); this.post("/api/articles", (schema, request) => { let attrs = request.requestBody; return schema.articles.create({...attrs, image: randomImg()}); }); this.post("/api/login", (schema, request) => { let attrs = request.requestBody; if (attrs.user === 'admin' && attrs.password === 'admin') { return new Response(200) } return new Response(403) }); } }); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
const {Command, flags} = require('@oclif/command') const fs = require('fs') const requireFromString = require('require-from-string'); const axios = require('axios') const path = require('path') class SubmitCommand extends Command { async run() { const {flags} = this.parse(SubmitCommand) const filename = flags.filename let fcontent = fs.readFileSync(filename).toString() const ctx = requireFromString(fcontent, { appendPaths: [path.resolve(__dirname, './../../node_modules')], }) // console.log(fcontent) const data = ctx.build() axios({method: 'POST', url: process.env['TASK_API'] + '/task', data}) .then(res => { if (res.status === 200) { console.log(`taskId: ${res.data.Id} Version: ${res.data.Version}`) } else { console.error(res.data) } }, err => { console.error((err.response && err.response.data.error) || err.toString()); }).catch(err => console.log(err.toString())) } } SubmitCommand.description = `submit task ... Extra documentation goes here ` SubmitCommand.flags = { filename: flags.string({char: 'f', description: 'file to submit'}), } module.exports = SubmitCommand
import React, { Component } from "react"; import { loginUser } from "../lib/auth"; import Route from "next/router"; export default class LoginForm extends Component { state = { email: "Sincere@april.biz", password: "hildegard.org", error: "", isLoading: false }; handelChange = (event) => { this.setState({ [event.target.name]: event.target.value }); }; handleSubmit = (even) => { const { email, password } = this.state; this.setState({ error: "",isLoading :true }); even.preventDefault(); // console.log(this.state); loginUser(email, password) .then(() => { Route.push("/profile"); }) .catch(this.showError); }; showError = (err) => { console.log(err); const error = (err.response && err.response.data) || err.massage; this.setState({ error ,isLoading :false}); }; render() { const { email, password, error,isLoading } = this.state; return ( <div> <form onSubmit={this.handleSubmit}> <div> <input type="email" name="email" value={email} placeholder="email" onChange={this.handelChange} /> </div> <div> <input type="password" name="password" value={password} placeholder="password" onChange={this.handelChange} /> </div> <button disabled={isLoading} type="submit">{isLoading ? "Sending" :"Submit" }</button> {error && <div>{error}</div>} </form> </div> ); } }
// FIXME identical arrow paths for dimensions, cutonfold, and grainline export default ` <marker orient="auto" refY="4.0" refX="0.0" id="dimensionFrom" style="overflow:visible;" markerWidth="12" markerHeight="8"> <path class="mark fill-mark" d="M 0,4 L 12,0 C 10,2 10,6 12,8 z" /> </marker> <marker orient="auto" refY="4.0" refX="12.0" id="dimensionTo" style="overflow:visible;" markerWidth="12" markerHeight="8"> <path class="mark fill-mark" d="M 12,4 L 0,0 C 2,2 2,6 0,8 z" /> </marker> `;
const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database('./maratonaDev.db') db.serialize(function() { //deletar dado da tabela // TODO adicionar botão de deletar ao site db.run(`DELETE FROM ideas`, function(err) { if(err) return console.log(err) console.log('Ideia deletada', this); }) //consultar dados na tabela db.all(`SELECT * FROM ideas`, function(err, rows) { if(err) return console.log(err) console.log(rows); }) })
var _ = require("underscore"); var MWURobot = function(obj) { var self = this; self.costs = obj.costs; self.epsilon = obj.epsilon; self.precision = obj.precision; self.movesAllowed = self.costs.length; self.atPure = false; self.updateNumber = 0; self.maxed = _.range(self.movesAllowed).map(function(d) { return false; }); self.initializeWeights = function() { var probs = []; var sum = 0; for (var i = 0; i < self.movesAllowed; i++) { probs[i] = Math.random(); sum += probs[i]; } for (var i = 0; i < self.movesAllowed; i++) { probs[i] /= sum; } return probs; } self.weights = self.initializeWeights(); self.updateWeights = function(mixedStrategies) { self.updateNumber++; var summedMixedStrategies = mixedStrategies.reduce(function(a, b) { return a.map(function(d, i) { return d+b[i]; }); }, mixedStrategies[0].map(function(d) { return 0; })); var totalCosts = 0; var rightCosts = self.costs.map(function(d, i) { var rightCost = summedMixedStrategies.reduce(function(a, b, j) { return a + b*d[j]; }, 0); totalCosts += self.weights[i]*rightCost; return rightCost; }); for (var i = 0, c = self.weights.length; i < c; i++) { if (!self.maxed[i]) { self.weights[i] *= (1 - self.epsilon * rightCosts[i]) / (1 - self.epsilon * totalCosts); if (self.weights[i] < self.precision || self.weights[i] > 1-self.precision) self.maxed[i] = true; if (self.weights[i] < self.precision) self.weights[i] = self.precision; if (self.weights[i] > 1-self.precision) self.weights[i] = 1-self.precision; } } if (_.every(self.maxed)) { self.atPure = true; } }; self.move = function() { var totalWeight = self.weights.reduce(function(a, b) { return a+b; }, 0); var pt = Math.random() * totalWeight; var tempSum = 0; for (var i = 0; i < self.movesAllowed; i++) { tempSum += self.weights[i]; if (tempSum > pt) { return i; } } }; }; module.exports = MWURobot;
import React, { useState } from "react"; import { validateEmail } from "./utils/helper"; function Form() { const [email, setEmail] = useState(""); const [name, setName] = useState(""); const [errorMessage, setErrorMessage] = useState(""); const handleInputChange = (event) => { const { target } = event; const inputType = target.name; const inputValue = target.value; if (inputType === "email") { setEmail(inputValue); } else { setName(inputValue); } }; const handleFormSubmit = (event) => { event.preventDefault(); if (!validateEmail(email) || !name) { setErrorMessage("Pleas enter a valid email and name"); return; } setName(""); setEmail(""); }; return ( <div> <form className="form"> <div> <input value={email} name="email" onChange={handleInputChange} type="email" placeholder="email" /> </div> <div> <input value={name} name="name" onChange={handleInputChange} type="text" placeholder="name" /> </div> <div> <button type="button" onClick={handleFormSubmit}> Submit </button> </div> </form> {errorMessage && ( <div> <p className="error-text">{errorMessage}</p> </div> )} </div> ); } export default Form;
$(document).ready(function() { var daysOfTheWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var plannerTimes = [9, 10, 11, 12, 13, 14, 15, 16, 17]; var reminders = []; var dayOfWeek = moment().day(); var month = moment().month(); var day = moment().date(); var dayAndDateDiv = $("<div>"); dayAndDateDiv.text(daysOfTheWeek[dayOfWeek]+", "+months[month] + " " + day) $(".jumbotron").append(dayAndDateDiv); for (i = 0; i < plannerTimes.length; i++){ var row = $("<div class='row'>"); var timeDiv = $("<div class='col-1'>"); var timeH2 = $("<h2>"); var textDiv = $("<div class='col-9'>"); var textArea = $("<textarea class='textArea'>"); var btnDiv = $("<div class='col-2'>"); var btn = $("<button class='save-btn'>"); btn.text('Save') timeH2.text(plannerTimes[i]); btnDiv.append(btn); textDiv.append(textArea); timeDiv.append(timeH2); btn.attr("data-hour", plannerTimes[i]); textArea.attr("data-hour", plannerTimes[i]); row.attr("data-hour", plannerTimes[i]); row.append(timeDiv, textDiv, btnDiv); $(".hours").append(row); }; var time = moment().hour(); // dynamically create jquery selector based on current hour timeSelectStr = ".row[data-hour="+time.toString()+"]" // add class to current time var currentHour = $( timeSelectStr ); currentHour.addClass("current-hour"); // add class to time already past for (x = 0; x < plannerTimes.length; x++){ if (plannerTimes[x] < time){ timeEarlierSelectStr = ".row[data-hour="+plannerTimes[x].toString()+"]"; var earlierHour = $(timeEarlierSelectStr); earlierHour.addClass("earlier"); } } $(".save-btn").on("click", function() { var text = $(this).parents(".row").find(".textArea").val().trim(); var textHour = $(this).parents(".row").data("hour"); var timeAndText = {}; timeAndText[textHour] = text; // console.log(timeAndText); reminders.push(timeAndText); console.log(reminders); localStorage.setItem("reminders", JSON.stringify(reminders)); }); var fromLocalStor = localStorage.getItem("reminders"); fromLocalStor = JSON.parse(fromLocalStor); //convert string to object for (y = 0; y<fromLocalStor.length; y++){ for (var key in fromLocalStor[y]) { console.log(fromLocalStor[y][key]); $(".textArea[data-hour="+ key +"]").text(fromLocalStor[y][key]); }; }; // $(".textArea[data-hour='9']").text('testing'); //This works to set the value of the text area });
// pages/cartoon/detail.js const app = getApp(); Page({ /** * 页面的初始数据 */ data: { mid: null, item: null, reverse: false, is_favourite: false, nextPage: null, lasttPage: null, chapter_index: 1, chapters: [], }, /** * 添加收藏/取消收藏 */ toggle_collect: function () { if (this.data.is_favourite) { this.removeCollect(this.data.mid, "novel") } else { this.addCollect(this.data.mid, "novel") } }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; this.pullup = this.selectComponent("#pullup"); this.setData({ mid: options.mid }); this.loadDetail(options.mid, null); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { this.loadInfo(this.data.mid, null); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { wx.showNavigationBarLoading() this.loadInfo(this.data.mid, null); this.loadDetail(this.data.mid, null); }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { this.pullup.loadMore() if (this.data.nextPage == null) { this.pullup.loadMoreComplete("已全部加载") } else { setTimeout(() => { this.loadDetail(this.data.mid, this.data.nextPage, this.data.reverse); }, 1000) } }, // 章节排序 sort_list: function () { this.setData({ reverse: !this.data.reverse }); this.loadDetail(this.data.mid, null, this.data.reverse); }, /** * 加载详情信息 */ loadInfo: function (mid, api) { var that = this; app.service.getNovelInfo(mid, api) .then(res => { console.log(res); wx.stopPullDownRefresh() wx.hideNavigationBarLoading() that.setData({ item: res.data, is_favourite: res.data.is_favourite }) wx.setNavigationBarTitle({ title: res.data.title, }) }) }, /** * 加载章节 */ loadDetail: function (mid, api, reverse) { var that = this; app.service.getNovelDetail(mid, api, reverse) .then(res => { console.log(res); if (reverse) { that.setData({ chapter_index: res.count }) } else { that.setData({ chapter_index: 1 }) } wx.stopPullDownRefresh() wx.hideNavigationBarLoading() if (api == null) { that.setData({ chapters: res.data, nextPage: res.links.next, lastPage: res.links.previous }) } else { that.setData({ chapters: that.data.chapters.concat(res.data), nextPage: res.links.next, lastPage: res.links.previous }) that.pullup.loadMoreComplete("加载成功") } }) .catch(res => { that.pullup.loadMoreComplete("加载失败") }) }, /** * 添加收藏 */ addCollect: function (mid, source_type) { app.service.addCollect(mid, source_type) .then(res => { // console.log(res); if (res.code == 0) { this.setData({ is_favourite: true }); wx.showToast({ title: '收藏成功', icon: 'none' }) } }) }, /** * 移除收藏 */ removeCollect: function (mid, source_type) { app.service.removeCollect(mid, source_type) .then(res => { // console.log(res); if (res.code == 0) { this.setData({ is_favourite: false }); wx.showToast({ title: '已取消', icon: 'none' }) } }) }, // 开始阅读 continue_read: function (e) { wx.navigateTo({ url: e.target.dataset.url }) } })
// $('.list-drap-drop li').arrangeable({ $('.list-drap-drop li').arrangeable({ dragSelector: '.drag-area' }); $('#swot .drag-list *').click(function(){ // console.log($(this)) var title = $(this).closest('.list-drap-drop').find('h3'); $('.list-drap-drop h3').removeClass('title-select-swot'); title.addClass('title-select-swot'); $('#swot-title').html(title.html()); $('#keySwot').val(title.attr('data-key')); //var index = $(this).parents("li").index(); // var index = $(this).index(); // $('#swot-at').html(index); // var textAt = $(this).find('.title').html(); // $('#name1').val(textAt); }) // $('#scrum .drag-list *').click(function(){ // // console.log($(this)) // var title = $(this).closest('.list-drap-drop').find('h3'); // $('.list-drap-drop h3').removeClass('title-select-scrum'); // title.addClass('title-select-scrum'); // $('#scrum-title').html(title.html()); // $('#keyScrum').val(title.attr('data-key')); // //var index = $(this).parents("li").index(); // // var index = $(this).index(); // // $('#swot-at').html(index); // // var textAt = $(this).find('.title').html(); // // $('#name1').val(textAt); // }) $('body').on('click', '#swot .drag-list li', function (event) { // $('.drag-list li').click(function(){ // console.log($(this)) // var title = $(this).closest('.list-drap-drop').find('h3').html(); // $('#swot-title').html(title); //var index = $(this).parents("li").index(); var index = $(this).index(); $('#swot-at').html(index); $('#keyAtId').val($(this).attr('keyid')); var textAt = $(this).find('.title').html(); $('#name1').val(textAt); $('#swot .drag-area').removeClass('selected') $(this).find('.drag-area').addClass('selected') }) // $('body').on('click', '#scrum .drag-list li', function (event) { // // $('.drag-list li').click(function(){ // // console.log($(this)) // // var title = $(this).closest('.list-drap-drop').find('h3').html(); // // $('#swot-title').html(title); // //var index = $(this).parents("li").index(); // var index = $(this).index(); // $('#scrum-at').html(index); // $('#keyAtIdScrum').val($(this).attr('keyid')); // var textAt = $(this).find('.title').html(); // $('#text-scrum').val(textAt); // $('#scrum .drag-area').removeClass('selected') // $(this).find('.drag-area').addClass('selected') // }) // $('body').on('drag.end.arrangeable', '.drag-list li', function (event) { // alert(123) // })
spacesApp.directive( 'content', function() { return { controller:'content.controller', templateUrl: 'app/content/content.view.html' } } );
jQuery(function ($) { var testimonialsSwiper = new Swiper('.testimonials-section .swiper-container', { // Optional parameters direction: 'horizontal', slidesPerView: 3, slidesPerColumn: 1, slidesOffsetAfter: 0, spaceBetween: 60, loop: false, roundLengths: true, speed: 700, autoplay: false, navigation: { nextEl: '.testimonials-controls .swiper-button-next', prevEl: '.testimonials-controls .swiper-button-prev' }, breakpoints: { 767: { slidesPerView: 1, spaceBetween: 30 }, 991: { slidesPerView: 2, spaceBetween: 40 } } }); // slow scroll by click link /*$(".scroll-link-list").on("click","a", function (event) { event.preventDefault(); var id = $(this).attr('href'), top = $(id).offset().top; $('body,html').animate({scrollTop: top}, 400); });*/ });
import React, {Component} from 'react'; import {Link} from 'react-router-dom' import axios from 'axios' const userApi = axios.create({ baseURL: 'http://localhost:5000/profile' }) const productApi = axios.create({ baseURL: 'http://localhost:5000/api/products' }) const config = { withCredentials: true, headers: { 'Content-Type': 'application/json', }, }; class cartScreen extends Component { state = { cartProductID: [], cartProductData: [], loggedInUser: "", curr_transaction_h: [], totalCartValue: 0 } constructor() { super(); userApi.get('/', config) .then(res => { this.setState( {cartProductID: res.data.cart, loggedInUser: res.data._id, curr_transaction_h: res.data.transaction_h}) }) .then(res => { var i; for(i = 0; i < this.state.cartProductID.length; i++) { productApi.get('/' + this.state.cartProductID[i]) .then(res => { this.setState(prevState => ({ cartProductData: [...prevState.cartProductData, res.data] })) }) .catch(err => console.error(err)) } }) .catch(err => console.error(err)); this.checkOut = this.checkOut.bind(this); this.goHome = this.goHome.bind(this); this.deleteFromCart = this.deleteFromCart.bind(this); } async calcTotalPrice() { var i; var totalPrice = 0; for(i = 0; i < this.state.cartProductData.length; i++) { totalPrice += this.state.cartProductData[i].price; } this.setState({totalCartValue: totalPrice}) } async localCheckOut() { this.calcTotalPrice() .then(res => { var tempTransaction = { productID: this.state.cartProductID, productObjects: this.state.cartProductData, date: Date.now, value: this.state.totalCartValue } this.setState(prevState => ({ curr_transaction_h: [...prevState.curr_transaction_h, tempTransaction] })) this.setState({cartProductID: []}) }) .catch(err => console.error(err)); } checkOut(e) { e.preventDefault() //var cartCopy = this.state.cartProductID; if(this.state.cartProductID.length === 0){ alert("Your Cart is Empty. Please Add Products to your Cart.") window.location = "/" } this.localCheckOut() .then(res => { userApi.put('/' + this.state.loggedInUser, { transaction_h: this.state.curr_transaction_h, cart: this.state.cartProductID, }) .then(res => { alert("Purchase Successful") window.location = '/' }) }) .catch(err => console.error(err)) } goHome(e) { e.preventDefault() window.location = '/' } async localDelete(prodID) { var IDfound = 0; var idxToDelete = -1; for(var i = 0; i < this.state.cartProductID.length && !IDfound; i++) { if(this.state.cartProductID[i] === prodID) { idxToDelete = i; IDfound = 1; } } if(IDfound) this.state.cartProductID.splice(idxToDelete, 1); else alert("ERROR ENCOUNTERED!") } deleteFromCart(prodID, prodName, e) { e.preventDefault() this.localDelete(prodID) .then(res => { userApi.put('/' + this.state.loggedInUser, {cart: this.state.cartProductID}) .then(res => { alert(prodName + " has been removed from cart") window.location = '/cart' }) }) } render() { return ( <div> <h3 className="cart-items">Shopping Cart</h3> <div className="cart-details"> { this.state.cartProductData.map(product => <li> <div className="cart-product"> <Link to={'/product/' + product._id}> <img className="product-image" src={"http://localhost:5000/" + product.productImage} alt="" /> </Link> <div className="product-name"> <Link to={'/product/' + product._id}>{product.name}</Link> </div> <div className="product-price">Rs {product.price}</div> <button onClick = {this.deleteFromCart.bind(this, product._id, product.name)}> Delete </button> </div> </li> ) } </div> <form className="cart-checkout"> <h4 className="done">Checkout</h4> <p className="done1">Ready to get these beverages delivered?</p> <button className="join" onClick={this.checkOut} > Buy These! </button> <p className="done2"> Oh, you're thirsty for even more? </p> <button className="join" onClick={this.goHome}> Shop More! </button> </form> </div> ) } } export default cartScreen
const medidas = [0, 0, 0, 0, 0] let indice = 0; const compareDate = new Date() setInterval(async () => { const response = await requestSerialData() const { leitura } = await response.json() medidas[indice] = parseInt(leitura) indice++ if (indice > 4) { indice = 0 } const mediaMovel = (medidas.reduce((acc, el) => acc + el)) / medidas.length const tensao = (((mediaMovel / 1023.0) * 5)) updateChart(tensao) }, 20) function requestSerialData() { return fetch('http://localhost:3030/leitura-ad') }
$(function(){ $(".lightbox").lightbox({ fitToScreen: true, imageClickClose: false }); });
require('dotenv').config() const cron = require('node-cron') const WeatherChecker = require('./class/WeatherChecker') cron.schedule('00 00,10,20,30,40,50 08-22 * * *', () => { const weatherChecker = new WeatherChecker() weatherChecker.check() })
import React from 'react'; import './Sidebar.scss'; import {MdOutlineKeyboardArrowDown} from 'react-icons/md'; import { Link } from 'react-router-dom'; import { SuitCase, UsersIcon, GroupUsers, MoneyBag, HandShake, PiggyBank, Savings, UserCheck, UserTimes, Bank, CoinStack, Transaction, Services, UserCog, Settlements, Chart, Preferences, Pricing, Wheel, Logout, Clipboard, HomeIcon } from '../../images/icons'; const Sidebar = () => { const navItems = [ {name: "Users", icon: <UsersIcon className="side-icon" />}, {name: "Guarantors", icon: <GroupUsers className="side-icon" />,}, {name: "Loans", icon: <MoneyBag className="side-icon" />}, {name: "Decision Models", icon: <HandShake className="side-icon" />}, {name: "Savings", icon: <PiggyBank className="side-icon" />}, {name: "Loan Requests", icon: <Savings className="side-icon" />}, {name: "Whtelist", icon: <UserCheck className="side-icon" />}, {name: "Karma", icon: <UserTimes className="side-icon" />}, ] const navItems2 = [ {name: "Organization", icon: <SuitCase className="side-icon" />}, {name: "Loan Products", icon: <Savings className="side-icon" />,}, {name: "Savings Products", icon: <Bank className="side-icon" />}, {name: "Fees and Charges", icon: <CoinStack className="side-icon" />}, {name: "Transactions", icon: <Transaction className="side-icon" />}, {name: "Services", icon: <Services className="side-icon" />}, {name: "Service Account", icon: <UserCog className="side-icon" />}, {name: "Settlements", icon: <Settlements className="side-icon" />}, {name: "Reports", icon: <Chart className="side-icon" />}, ] const navItems3 = [ {name: "Preferences", icon: <Preferences className="side-icon" />}, {name: "Fees and Pricing", icon: <Pricing className="side-icon" />,}, {name: "Audit Logs", icon: <Clipboard className="side-icon" />}, {name: "System Messages", icon: <Wheel className="side-icon" />}, ] return ( <div className="sidebar"> <div className="sidebar-container"> <h3 className="sidebar-header"><SuitCase className="sidebar-header-icon" /><span className="sidebar-header-text">Switch Organization</span><MdOutlineKeyboardArrowDown className="switch-dropdown" /></h3> <h3 className="sidebar-header"><HomeIcon className="sidebar-header-icon" /><span className="sidebar-header-text">Dashboard</span></h3> </div> <div className="side-items-container"> <h4 className="side-items-header">CUSTOMERS</h4> <ul className="side-items"> {navItems.map(item => (<li className="side-item"><Link to="/" className="side-link">{item.icon} <span className="side-text">{item.name}</span></Link></li>))} </ul> <h4 className="side-items-header">BUSINESSES</h4> <ul className="side-items"> {navItems2.map(item => (<li className="side-item"><Link to="/" className="side-link">{item.icon} <span className="side-text">{item.name}</span></Link></li>))} </ul> <h4 className="side-items-header">SETTINGS</h4> <ul className="side-items"> {navItems3.map(item => (<li className="side-item"><Link to="/" className="side-link">{item.icon} <span className="side-text">{item.name}</span></Link></li>))} </ul> </div> <ul> <li className="side-item"><Link to="/" className="side-link"><Logout className="side-icon" /><span className="sidebar-header-text">Logout</span></Link></li> </ul> </div> ) } export default Sidebar
import {useNavigation} from '@react-navigation/core'; import React from 'react'; import {useCallback} from 'react'; import {useMemo} from 'react'; import {useState} from 'react'; import {FlatList, ScrollView, StyleSheet, Text, View} from 'react-native'; import {TouchableOpacity} from 'react-native-gesture-handler'; import {useSelector} from 'react-redux'; import {sendUserStatistics} from '../../api/subjectTestsApi'; import {calculateTestResult} from '../../utils/helpers'; import CrossIcon from '../../assets/CrossIcon'; import ResetIcon from '../../assets/ResetIcon'; import Button from '../../components/Button'; import CustomHeader from '../../components/CustomHeader'; import TestPicker from '../../components/TestPicker'; import TestResutItem from '../../components/TestResutItem'; const TestItem = () => { const navigation = useNavigation(); const {sequenceContainer, container, testTitle} = styles; const {test} = useSelector((state) => state.test); const authState = useSelector((state) => state.auth); const [answerHandler, updateAnswerHandler] = useState( test.tests.map((el) => ({type: el.content.type, selected: null})), ); const [currentTest, setCurrentTest] = useState(0); const isLastTest = useMemo(() => currentTest + 1 > test?.tests?.length - 1, [ currentTest, ]); const [showResults, setShowResults] = useState(false); const [finalResults, setFinalResults] = useState(null); const resetTestState = () => { setCurrentTest(0); setShowResults(false); setFinalResults(null); updateAnswerHandler( test.tests.map((el) => ({type: el.content.type, selected: null})), ); }; const handleNextSteps = useCallback(() => { if (!isLastTest) { console.log('next test'); setCurrentTest(currentTest + 1); } else { try { setShowResults(true); let results = calculateTestResult(test.tests, answerHandler); console.log('got results', {results}); setFinalResults(results); sendUserStatistics({ correct: results.score, subject: test.subject, wrong: results.wrongAnswers, missed: results.skippedTests, total: results.maxScore, userId: authState.id, testWrapID: test.id, testTitle: test.title, }); } catch {} } }, [isLastTest, currentTest]); console.log('got test', answerHandler, test); return ( <View> {!showResults && ( <> <CustomHeader title={test.title} canGoBack isTest /> <View style={styles.mainTestBody}> <View style={sequenceContainer}> <Text> {`${currentTest + 1}`}/{test?.tests?.length?.toString()} </Text> <Text adjustsFontSizeToFit style={testTitle}> {test.tests[currentTest].title.text} </Text> </View> <ScrollView style={{height: '65%', overflow: 'scroll'}}> <TestPicker content={test.tests[currentTest].content} answerHandler={answerHandler[currentTest]} currentTest={currentTest} updateAnswerHandler={updateAnswerHandler} /> </ScrollView> <View style={{alignSelf: 'center', paddingTop: 10}}> <Button title={isLastTest ? 'Завершити' : 'Далі'} action={handleNextSteps} /> </View> </View> </> )} {showResults && ( <> <View style={styles.resultsBlock}> <View style={styles.resultUppperContent}> <TouchableOpacity onPress={() => navigation.goBack()} style={{alignItems: 'center', justifyContent: 'center'}}> <CrossIcon selected /> </TouchableOpacity> <Text style={styles.upperText} adjustsFontSizeToFit> {test.title} </Text> <TouchableOpacity onPress={resetTestState}> <ResetIcon /> </TouchableOpacity> </View> <View style={styles.resultContent}> <Text style={styles.yourResults}>Твій результат</Text> <Text style={ styles.yourScore }>{`${finalResults.score}/${finalResults.maxScore}`}</Text> </View> <View style={styles.resultsStats}> <View style={styles.resultsStatsItem}> <Text style={styles.statItemLabel}>Правильні</Text> <Text style={styles.statItemScore}>{finalResults.score}</Text> </View> <View style={styles.resultsStatsItem}> <Text style={styles.statItemLabel}>Неправильні</Text> <Text style={styles.statItemScore}> {finalResults.wrongAnswers} </Text> </View> <View style={styles.resultsStatsItem}> <Text style={styles.statItemLabel}>Пропущені</Text> <Text style={styles.statItemScore}> {finalResults.skippedTests} </Text> </View> </View> </View> <View style={styles.explanationBlock}> <FlatList data={test.tests} renderItem={({item, index}) => ( <TestResutItem originalTest={item} answeredTest={answerHandler[index]} index={index} /> )} /> </View> </> )} </View> ); }; export default TestItem; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, sequenceContainer: { marginTop: 27, alignItems: 'center', height: '12%', }, testTitle: { textAlign: 'center', fontSize: 16, marginHorizontal: 10, marginBottom: 24, }, mainTestBody: {}, explanationBlock: { marginTop: 30, height: '65%', }, resultsBlock: { backgroundColor: '#191744', borderBottomLeftRadius: 20, borderBottomRightRadius: 20, }, resultUppperContent: { flexDirection: 'row', alignItems: 'center', paddingTop: 24, paddingBottom: 42, paddingHorizontal: 16, }, upperText: { width: '85%', color: 'white', fontSize: 22, fontWeight: '600', textAlign: 'center', }, resultContent: { alignItems: 'center', justifyContent: 'center', paddingBottom: 24, }, yourResults: { color: 'gray', fontSize: 12, }, yourScore: { color: 'white', fontSize: 21, fontWeight: '600', }, resultsStats: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 24, paddingBottom: 24, }, statItemLabel: { color: 'gray', fontSize: 12, paddingBottom: 8, }, statItemScore: { fontSize: 14, color: 'white', fontWeight: '600', }, });
/** * * Keep track of the users in the Chat * */ const users = []; /** * * Add users * @param id * @param username * @param room */ const addUser = ( { id, username, room } ) => { /** * Sanitize values */ username = username.trim().toLowerCase(); room = room.trim().toLowerCase(); /** * Validate values */ if( ! username || ! room ) return { error: 'Username and room are required' }; /** * Check for existing user */ const existingUser = users.find( user => { return user.room === room && user.username === username }); /** * Validate User */ if ( existingUser ) return { error: 'Username is in use' }; /** * Store User */ const user = { id, username, room }; users.push( user ); return { user }; }; /** * Remove users by Index * @param Number id */ const removeUser = id => { const index = users.findIndex( user => user.id === id ); // Remove from array and return it. if( index !== -1 ) return users.splice( index, 1 )[0]; }; /** * Get user by id * @param id */ const getUser = id => { return users.find( user => user.id === id ); } /** * Get users in room * @param room */ const getUsersInRoom = room => { room = room.trim().toLowerCase(); return users.filter( user => user.room == room ); }; module.exports = { addUser, removeUser, getUser, getUsersInRoom };
class Controls{ constructor() { this.currentlyDown = []; for(let i=0;i<256;i++){ this.currentlyDown.push(false); } this.clear(); window.addEventListener("keydown", this.handleEvent.bind(this)); window.addEventListener("keyup", this.handleEvent.bind(this)); } clear(){ this.releasedThisTick = []; this.pressedThisTick = []; }; isKeyDown(keyCode){ return this.currentlyDown[keyCode] || this.releasedThisTick.indexOf(keyCode) >= 0; }; wasKeyPressed(keyCode){ return this.pressedThisTick.indexOf(keyCode) >= 0; } handleEvent(event){ this.currentlyDown[event.keyCode] = (event.type === "keydown"); if(event.type === "keyup"){ this.releasedThisTick.push(event.keyCode); } if(event.type === "keydown"){ this.pressedThisTick.push(event.keyCode); } } } export default Controls
import Link from 'next/link'; import { Row, Col } from 'reactstrap'; import FooterColumn from '../footerColumn/footerColumn'; import SharingColumn from '../sharingColumn/sharingColumn'; import footerList from './footerList'; import s from './footer.scss'; const Footer = () => ( <div className="footer"> <div className="footerContainer"> <Row> { footerList.map(item => ( <FooterColumn key={item.title} title={item.title} list={item.list} /> )) } <SharingColumn /> </Row> <Row className="align-items-center justify-content-center"> <Col xs={8} className="d-flex justify-content-center"> <div className="footer__legal"> <Link href="/terms"> <span className="footer__link">Legal</span> </Link> <Link href="/privacy-policy"> <span className="footer__link">Privacy</span> </Link> <Link href="/safety"> <span className="footer__link">Cove Safety Notice</span> </Link> <Link href="/contact"> <span className="footer__link">Contact Us</span> </Link> </div> </Col> </Row> <Row className="align-items-center justify-content-center"> <Col xs={8} className="d-flex justify-content-center"> <p className="footer__copywrite">© 2018 Cove Smart, LLC All rights reserved. | 14015 Minuteman Drive, Draper, UT 84020</p> </Col> </Row> </div> <style jsx>{s}</style> </div> ); export default Footer;
import { getUniqueHairColors } from './filters'; export const getTownsNames = (data) => Object.keys(data); export const getUsersByTown = (data, townName) => data[townName]; export const getUniqueHairColorsByTown = (data, townName) => getUniqueHairColors(data[townName]);