text
stringlengths
7
3.69M
import React from "react"; import "./Chat.css"; function Chat() { return ( <div className='chat'> <div className='chat__header'> <h4> To: <span className='chat__name'>Channel Name</span> </h4> <strong>Details</strong> </div> <div className='chat__messages'></div> </div> ); } export default Chat;
"use strict"; window.onload = function() { let player = 1; //var that keeps track of whos turn var board = document.getElementById("board"); var squares = board.querySelectorAll("div"); var status = document.getElementById("status"); var tiles = [9]; // stores all board div elements in the correct position var game = ["","","","","","","","",""]; //keeps track of the X and O positions //Creates the board and all features (click,hover and moree style classes) for (var i= 0;i < squares.length; i++) { squares[i].classList.add("square"); tiles[i] = squares[i]; click(squares[i]); hover(squares[i]); } //Function for the hover feature function hover(item) { //pink when mouse is over square item.onmouseover = function(element) { console.log("Mouse Over Square"); element.target.className += " hover"; } //disables when mouse is no longer on square item.onmouseout = function(element) { console.log("Mouse Off Square"); element.target.classList.remove("hover"); } } /*Function for click feature After a play, the click is disabled so that it can not be changed */ function click(item) { item.onclick = function(element) { console.log("Clicked Square "); //When clicked by player 1 an X appears on the square if (player == 1) { element.target.innerHTML = "X"; element.target.classList.remove("O"); element.target.className += " X"; console.log("Play X"); element.target.onclick = null; //Disables click player = 2; //Switch to player 2 for next move position(item,"X"); checkBoard("X"); } //When clicked by player 2 an O appears on the square else { element.target.innerHTML = "O"; element.target.classList.remove("X"); element.target.className += " O"; console.log("Play O"); element.target.onclick = null; player = 1; position(item,"O"); checkBoard("O"); } } } /*Function to input the position of the X or O in the list that tracks thee position*/ function position(square,play) { var num = tiles.indexOf(square); game[num] = play; } //Function that checks the board for "XXX" or "OOO" (winning play) function checkBoard(item) { console.log("Checking " + item); if (game[0] == item && game[1] == item && game[2] == (item)) { win(item); } else if (game[3] == item && game[4] == item && game[5] == item) { win(item); } else if (game[6] == item && game[7] == item && game[8] == item) { win(item); } else if (game[0] == item && game[3] == item && game[6] == item) { win(item); } else if (game[1] == item && game[4] == item && game[7] == item) { win(item); } else if (game[2] == item && game[5] == item && game[8] == item) { win(item); } else if (game[2] == item && game[4] == item && game[6] == item) { win(item); } else if (game[0] == item && game[4] == item && game[8] == item) { win(item); } } /*Function that is used to display the winner and not allow anymore moves to bee played*/ function win(str) { status.classList.add("you-won"); status.innerHTML = "Congratulations! " + str + " is the Winner!"; for(var i = 0; i < squares.length; i++) { squares[i].onclick = null; } } //Below is all the features for thee button var button = document.querySelector("button"); // hover feature button.onmouseover = function(element) { console.log("Mouse Over Button"); button.classList.add("btn:hover"); } // click feature button.onclick = function(element) { console.log("Clicked Button"); for (var i=0;i < squares.length;i++) { squares[i].innerHTML = ""; click(squares[i]); } player = 1; game = ["","","","","","","","",""]; status.className = null; status.innerHTML = "Move your mouse over a square and click to play an X or an O."; console.log("Clear Board"); } }
import React from 'react'; import PropTypes from 'prop-types'; import '../css/User.css'; class User extends React.Component { constructor(props){ super(props); this.state = { selectedComponent: false, firstUser: false }; } static propTypes = { id: PropTypes.number, name: PropTypes.string, index: PropTypes.number, choreId: PropTypes.number } confirmationDialog(){ return (<div className="row"> <div onClick={() => {this.handleConfirmationClick()}} className="col-6 confirmation-text"> Confirm </div> <div className="col-6 confirmation-text"> Cancel </div> </div>); } displayText(){ if(this.state.selectedComponent === true) { return this.confirmationDialog(); } else { return <span className="user-text">{this.props.name}</span> } } handleConfirmationClick(){ if (this.state.selectedComponent === true) { var userJson = JSON.stringify({ 'user_id': this.props.id, 'id': this.props.choreId }); fetch(`https://fierce-shelf-51195.herokuapp.com/chores/${this.props.choreId}/rotate.json`, { method: 'post', headers: { "Content-Type": "application/json"}, body: userJson }) } } handleUserClick(){ this.toggleState(); } toggleState() { this.setState({ selectedComponent: !this.state.selectedComponent }); } render(){ return( <div onClick={() => {this.handleUserClick()}} className={`card user-box user-${this.props.index}`}> {this.displayText()} </div> ) } } export default User;
import { url } from '../../utils/entyPoints'; import { logout } from './authActions'; export const booksTypes = { FETCH_BOOKS_REQUEST: 'FETCH_BOOKS_REQUEST', FETCH_BOOKS_SUCCESS: 'FETCH_BOOKS_SUCCESS', FETCH_BOOKS_ERROR: 'FETCH_BOOKS_ERROR', FETCH_ONE_BOOK_REQUEST: 'FETCH_ONE_BOOK_REQUEST', FETCH_ONE_BOOK_SUCCESS: 'FETCH_ONE_BOOK_SUCCESS', FETCH_ONE_BOOK_ERROR: 'FETCH_ONE_BOOK_ERROR', LOAD_MORE: 'LOAD_MORE', SEARCH_BY_TITLE: 'SEARCH_BY_TITLE', FILTER_BY_PRICE: 'FILTER_BY_PRICE', EMPTY_FILTER: 'EMPTY_FILTER', }; export const searchByTitle = search => ({ type: booksTypes.SEARCH_BY_TITLE, payload: { search, }, }); export const filterByPrice = filter => ({ type: booksTypes.FILTER_BY_PRICE, payload: { filter, }, }); export const fetchBooksSuccess = books => ({ type: booksTypes.FETCH_BOOKS_SUCCESS, payload: { books, }, }); export const fetchBooksError = error => ({ type: booksTypes.FETCH_BOOKS_ERROR, payload: error.message, }); export const fetchBooks = () => ({ type: booksTypes.FETCH_BOOKS_REQUEST, payload: { request: { method: 'GET', url: url.books(), }, options: { onSuccess({ dispatch, response }) { dispatch(fetchBooksSuccess(response.data)); }, onError({ dispatch, error }) { dispatch(logout()); dispatch(fetchBooksError(error)); }, }, }, }); export const fetchOneBookSuccess = book => ({ type: booksTypes.FETCH_ONE_BOOK_SUCCESS, payload: { book, }, }); export const fetchOneBookError = error => ({ type: booksTypes.FETCH_ONE_BOOK_ERROR, payload: error.message, }); export const fetchOneBook = id => ({ type: booksTypes.FETCH_ONE_BOOK_REQUEST, payload: { request: { method: 'GET', url: url.oneBook(id), }, options: { onSuccess({ dispatch, response }) { dispatch(fetchOneBookSuccess(response.data)); }, onError({ dispatch, error }) { dispatch(fetchOneBookError(error)); }, }, }, }); export const loadMore = () => ({ type: booksTypes.LOAD_MORE, });
/** * ownCloud * * @author Vincent Petry * @copyright Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ describe('DeleteHandler tests', function() { var showNotificationSpy; var hideNotificationSpy; var clock; var removeCallback; var markCallback; var undoCallback; function init(markCallback, removeCallback, undoCallback) { var handler = new DeleteHandler('dummyendpoint.php', 'paramid', markCallback, removeCallback); handler.setNotification(OC.Notification, 'dataid', 'removed %oid entry', undoCallback); return handler; } beforeEach(function() { showNotificationSpy = sinon.spy(OC.Notification, 'showHtml'); hideNotificationSpy = sinon.spy(OC.Notification, 'hide'); clock = sinon.useFakeTimers(); removeCallback = sinon.stub(); markCallback = sinon.stub(); undoCallback = sinon.stub(); $('#testArea').append('<div id="notification"></div>'); }); afterEach(function() { showNotificationSpy.restore(); hideNotificationSpy.restore(); clock.restore(); }); it('deletes when deleteEntry is called', function() { fakeServer.respondWith(/\/index\.php\/dummyendpoint.php\/some_uid/, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({status: 'success'}) ]); var handler = init(markCallback, removeCallback, undoCallback); handler.mark('some_uid'); handler.deleteEntry(); expect(fakeServer.requests.length).toEqual(1); var request = fakeServer.requests[0]; expect(request.url).toEqual(OC.webroot + '/index.php/dummyendpoint.php/some_uid'); }); it('deletes when deleteEntry is called and escapes', function() { fakeServer.respondWith(/\/index\.php\/dummyendpoint.php\/some_uid/, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({status: 'success'}) ]); var handler = init(markCallback, removeCallback, undoCallback); handler.mark('some_uid<>/"..\\'); handler.deleteEntry(); expect(fakeServer.requests.length).toEqual(1); var request = fakeServer.requests[0]; expect(request.url).toEqual(OC.webroot + '/index.php/dummyendpoint.php/some_uid%3C%3E%2F%22..%5C'); }); it('calls removeCallback after successful server side deletion', function() { fakeServer.respondWith(/\/index\.php\/dummyendpoint.php\/some_uid/, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({status: 'success'}) ]); var handler = init(markCallback, removeCallback, undoCallback); handler.mark('some_uid'); handler.deleteEntry(); expect(fakeServer.requests.length).toEqual(1); var request = fakeServer.requests[0]; var query = OC.parseQueryString(request.requestBody); expect(removeCallback.calledOnce).toEqual(true); expect(undoCallback.notCalled).toEqual(true); expect(removeCallback.getCall(0).args[0]).toEqual('some_uid'); }); it('calls undoCallback and shows alert after failed server side deletion', function() { // stub t to avoid extra calls var tStub = sinon.stub(window, 't').returns('text'); fakeServer.respondWith(/\/index\.php\/dummyendpoint.php\/some_uid/, [ 403, { 'Content-Type': 'application/json' }, JSON.stringify({status: 'error', data: {message: 'test error'}}) ]); var alertDialogStub = sinon.stub(OC.dialogs, 'alert'); var handler = init(markCallback, removeCallback, undoCallback); handler.mark('some_uid'); handler.deleteEntry(); expect(fakeServer.requests.length).toEqual(1); var request = fakeServer.requests[0]; var query = OC.parseQueryString(request.requestBody); expect(removeCallback.notCalled).toEqual(true); expect(undoCallback.calledOnce).toEqual(true); expect(undoCallback.getCall(0).args[0]).toEqual('some_uid'); expect(alertDialogStub.calledOnce); alertDialogStub.restore(); tStub.restore(); }); });
self.__precacheManifest = [ { "revision": "229c360febb4351a89df", "url": "/static/js/runtime~main.229c360f.js" }, { "revision": "df6c7cab77f70d5a881e", "url": "/static/js/main.df6c7cab.chunk.js" }, { "revision": "c47ae7da2b5ab0f6214d", "url": "/static/js/1.c47ae7da.chunk.js" }, { "revision": "df6c7cab77f70d5a881e", "url": "/static/css/main.8c891598.chunk.css" }, { "revision": "c95701c27b3bf3b10a347b4d8f6f1a2f", "url": "/index.html" } ];
/*! * fastbill-automatic - node plugin * * Author: * Robert Boeing <robert.boeing@konexmedia.com> * Paul Em <paul3m@gamil.com> * * MIT Licensed * */ 'use strict'; var Client = require('node-rest-client').Client; var _ = require('underscore'); // // fastbill // var Fastbill = function (config) { var credentials = { user: config.user, password: config.apiKey }; this.config = { user: config.user, apiKey: config.apiKey, serviceUrl: "https://automatic.fastbill.com/api/1.0/api.php", headers: {"Content-Type": "application/json"} }; //authenticate and build our client this.client = new Client(credentials); }; Fastbill.prototype = { // // get // get: function (type, params, callback) { // build the fastbill styled Query params = { data: _.extend(params, {"SERVICE": type + '.get'}), headers: this.config.headers }; // use node-rest-client for communication this.client.post(this.config.serviceUrl, params, function (data, response) { // parsed response body as js object var res = null; try { res = JSON.parse(data); } catch (e) { console.error('fastbill error: could not parse create response'); } if (!res) { callback(null); return; } // get first property of Response-OBJ and fire the callback! for (var props in res.RESPONSE) { var resAry = []; res.RESPONSE[props].forEach(function (e) { resAry.push(e); }); callback(resAry); //break after first element break; } }); }, getOne: function (type, params, callback) { // build the fastbill styled Query params = { data: _.extend(params, {"SERVICE": type + '.get', "LIMIT": 1}), headers: this.config.headers }; // use node-rest-client for communication this.client.post(this.config.serviceUrl, params, function (data, response) { // parsed response body as js object var res = null; try { res = JSON.parse(data); } catch (e) { console.error('fastbill error: could not parse create response'); } if (!res) { callback(null); return; } // get first property of Response-OBJ and fire the callback! for (var props in res.RESPONSE) { callback(res.RESPONSE[props][0]); break; } }); }, create: function (type, params, callback) { // build the fastbill styled Query params = { data: { "SERVICE": type + '.create', "DATA": params }, headers: this.config.headers }; // use node-rest-client for communication this.client.post(this.config.serviceUrl, params, function (data, response) { // parsed response body as js object var res = null; try { res = JSON.parse(data); } catch (e) { console.error('fastbill error: could not parse create response'); } if (res && typeof res === 'object' && res.RESPONSE) { callback(res.RESPONSE); } else { callback(null); } }); }, update: function (type, id, params, callback) { // build the fastbill styled Query params.CUSTOMER_ID = id; params = { data: { "SERVICE": type + '.update', "DATA": params }, headers: this.config.headers }; // use node-rest-client for communication this.client.post(this.config.serviceUrl, params, function (data, response) { // parsed response body as js object var res = null; try { res = JSON.parse(data); } catch (e) { console.error('fastbill error: could not parse create response'); } if (res && typeof res === 'object' && res.RESPONSE) { callback(res.RESPONSE); } else { callback(null); } }); }, del: function (type, id, callback) { // build the fastbill styled Query var params = { data: { "SERVICE": type + '.delete', "DATA": { 'CUSTOMER_ID': id } }, headers: this.config.headers }; // use node-rest-client for communication this.client.post(this.config.serviceUrl, params, function (data, response) { // parsed response body as js object var res = null; try { res = JSON.parse(data); } catch (e) { console.error('fastbill error: could not parse create response'); } if (res && typeof res === 'object' && res.RESPONSE) { callback(res.RESPONSE); } else { callback(null); } }); } }; module.exports = Fastbill;
$("#pullerId").click(function() { $('.menuContainer').toggleClass('menuContainer-active'); }); $("#pullerId").click(function() { $('.dropBox').toggleClass('dropBox-active'); }); //dark mode var checkbox = document.querySelector('input[name=theme]'); checkbox.addEventListener('change', function() { if(this.checked) { trans() document.documentElement.setAttribute('data-theme', 'dark') $('.menuContainer').toggleClass('menuContainer-dark'); $('.scrollTop').toggleClass('scrollTop-dark'); } else { trans() document.documentElement.setAttribute('data-theme', 'light') $('.menuContainer').toggleClass('menuContainer-dark'); $('.scrollTop').toggleClass('scrollTop-dark'); } }) let trans = () => { document.documentElement.classList.add('transition'); window.setTimeout(() => { document.documentElement.classList.remove('transition') }, 1000) } //dark mode
import nodeMailjet from 'node-mailjet' import { expect, sinon } from '../../test-helper' import Mailjet from '../../../src/infrastructure/mailing/mailjet' import * as process from '../../../src/infrastructure/env/process' describe('Unit | Infrastructure | Mailing | Mailjet', () => { let mailJetConnectStub let isProductionMock let consoleLog beforeEach(() => { mailJetConnectStub = sinon.stub(nodeMailjet, 'connect') isProductionMock = sinon.stub(process, 'isProduction') isProductionMock.returns(true) consoleLog = sinon.stub(console, 'log') }) afterEach(() => { mailJetConnectStub.restore() isProductionMock.restore() consoleLog.restore() }) describe('#sendEmail', () => { let options beforeEach(() => { options = { from: 'contact@recontact.me', fromName: 'Ne pas répondre', subject: 'mon sujet', template: 'Corps du mail', to: 'contact@recontact.me', } }) it('should not send mail when not in production', () => { // Given isProductionMock.returns(false) // When Mailjet.sendEmail(options) // Then sinon.assert.notCalled(mailJetConnectStub) sinon.assert.called(consoleLog) }) it('should create an instance of mailJet', () => { // Given mailJetConnectStub.returns({ post: () => ({ request: () => { }, }), }) // When Mailjet.sendEmail(options) // Then sinon.assert.calledWith(mailJetConnectStub, 'fake-mailjet-public-key', 'fake-mailjet-secret-key') }) it('should post a send instruction', () => { // Given const postStub = sinon.stub().returns({ request: () => Promise.resolve() }) mailJetConnectStub.returns({ post: postStub }) // When const result = Mailjet.sendEmail(options) // Then return result.then(() => { sinon.assert.calledWith(postStub, 'send') }) }) it('should request with a payload', () => { // Given const requestStub = sinon.stub().returns(Promise.resolve()) const postStub = sinon.stub().returns({ request: requestStub }) mailJetConnectStub.returns({ post: postStub }) // When const result = Mailjet.sendEmail(options) // Then return result.then(() => { sinon.assert.calledWith(requestStub, { FromEmail: 'contact@recontact.me', FromName: 'Ne pas répondre', Subject: 'mon sujet', 'Html-part': 'Corps du mail', Recipients: [{ Email: 'contact@recontact.me' }], }) }) }) describe('#_formatRecipients', () => { let requestStub let postStub beforeEach(() => { requestStub = sinon.stub().returns(Promise.resolve()) postStub = sinon.stub().returns({ request: requestStub }) mailJetConnectStub.returns({ post: postStub }) options = { from: 'from', fromName: 'name', subject: 'subject', template: 'body', to: null, } }) it('should take into account when specified receivers is null or undefined', () => { // given options.to = null // when const result = Mailjet.sendEmail(options) // then return result.then(() => { expect(mailJetConnectStub).not.to.have.been.calledWith() }) }) it('should take into account when specified receivers is a string with single email', () => { // given options.to = 'recipient@mail.com' // when const result = Mailjet.sendEmail(options) // then return result.then(() => { sinon.assert.calledWithExactly(requestStub, { FromEmail: 'from', FromName: 'name', Subject: 'subject', 'Html-part': 'body', Recipients: [{ Email: 'recipient@mail.com' }], }) }) }) it('should take into account when specified receivers is an array of receivers', () => { // given options.to = ['recipient_1@mail.com', 'recipient_2@mail.com', 'recipient_3@mail.com'] // when const result = Mailjet.sendEmail(options) // then return result.then(() => { sinon.assert.calledWithExactly(requestStub, { FromEmail: 'from', FromName: 'name', Subject: 'subject', 'Html-part': 'body', Recipients: [ { Email: 'recipient_1@mail.com' }, { Email: 'recipient_2@mail.com' }, { Email: 'recipient_3@mail.com' }, ], }) }) }) }) }) })
function showTaller2(){ //ocultamos el div contenedor de los demas talleres document.querySelector('.taller1').style.display = 'none'; document.querySelector('.taller3').style.display = 'none'; document.querySelector('.taller4').style.display = 'none'; document.querySelector('h3').textContent = 'Precios y descuentos'; //quitamos y agregamos la clase active en el menu document.querySelector('.active').classList.remove('active'); document.getElementById('btn-taller2').parentNode.classList.add('active'); //mostramos el div del taller2 document.querySelector('.taller2').style.display = 'flex'; //calculando precios y descuentos calcularDescuento(); } function calcularDescuento(){ document.getElementById('btn_descuento').addEventListener('click', () => { document.getElementById('resultadoDescuento').textContent = ` Descuento: ${ (Number(document.getElementById('precio').value) * Number(document.getElementById('porcentaje').value) / 100 - Number(document.getElementById('precio').value)) * - 1 //multiplicamos por (-1) para cambiar el resultado a positivo(+) } `; }); } export { showTaller2 }
const membersDivEL = document.querySelector('#bookings'); const getRowersURL = 'getRowers'; const removeRowersURL = 'removeRowers'; const bookingIDValue = document.querySelector('#bookingIdInput'); async function deleteRowersAsync(bookingID, rowers) { const data = {bookingID, rowers}; let options = { method: 'POST', header: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) } const response = await fetch(removeRowersURL,options); const json = await response.json(); if (json.status === 'error'){ alert('ERROR: ' + json.message); } else { alert(json.message); } } function removeRowersEventHandler() { let rowersToRemoveFormEL = document.querySelector('#idInput'); rowersToRemoveFormEL.addEventListener('submit', async ()=>{ event.preventDefault(); const bookingID = bookingIDValue.value; const rowers = document.querySelector('#in').value; await deleteRowersAsync(bookingID,rowers); }) } function createLIelement(member) { let li = document.createElement('li'); li.setAttribute('class', 'rowerOption') li.innerHTML += '<br><br>Name: ' + member.name; li.innerHTML += '<br>Age: ' + member.age; li.innerHTML += '<br>Level: ' + member.level; li.innerHTML += '<br>Email: ' + member.emailAddress; li.innerHTML += '<br>ID: ' + member.memberID + '<br>'; return li; } function printMembers(members){ const ul = document.createElement('ul'); ul.innerHTML += '<h2>Participating rowers list: </h2>'; ul.innerHTML += '<span>Please choose the member IDs you wish to remove from the booking</span><br>' + 'Separate each id with a comma (,)<br><br>'; ul.innerHTML += " <form id = \"idInput\">\n" + " <input type=\"text\" id=\"in\" placeholder=\"Enter member IDs\"><br><br>\n" + " <input type=\"submit\" value=\"Remove Rowers\">\n" + " </form>"; members.forEach(member => { ul.appendChild(createLIelement(member)); }) membersDivEL.appendChild(ul); } async function getRowersFromBooking(bookingID) { const data = {bookingID}; let options = { method: 'POST', header: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) } let response = await fetch(getRowersURL,options); return await response.json(); } window.addEventListener('load',()=>{ let form = document.querySelector('#idForm'); form.addEventListener('submit', async () =>{ event.preventDefault(); const bookingID = bookingIDValue.value; let members = await getRowersFromBooking(bookingID); printMembers(members); removeRowersEventHandler(); }) })
import Request from '@/util/request'; export default { getXXXList(param) { const uri = '/xx/city/v1'; return Request.get(uri, param); }, getSummryData() { const uri = '/yy/v1'; return Request.get(uri); }, };
/* eslint-disable jsx-a11y/no-static-element-interactions */ /* eslint-disable jsx-a11y/click-events-have-key-events */ import React from 'react'; import PropTypes from 'prop-types'; const Modal = ({ show, onClick, children }) => { return ( <> {show ? ( <> <div className="fixed top-0 right-0 left-0 mt-5 xl:inset-0 z-50 flex items-center justify-center overflow-x-hidden overflow-y-auto outline-none focus:outline-none" onClick={onClick} > <div onClick={(e) => e.stopPropagation()} className="relative w-auto "> {/* content */} <div className="relative flex flex-col bg-white border-0 rounded-lg shadow-lg outline-none focus:outline-none"> {children} </div> </div> </div> <div className="fixed inset-0 z-40 bg-black opacity-25" /> </> ) : null} </> ); }; export default Modal; Modal.propTypes = { show: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired, children: PropTypes.element.isRequired, }; export const Header = ({ onClick, title }) => { return ( <> {/* header */} <div className="flex items-start justify-between p-5 border-b border-gray-300 border-solid rounded-t"> <h3 className="text-3xl font-semibold">{title}</h3> <button type="button" className="float-right p-1 ml-auto text-3xl font-semibold leading-none text-black bg-transparent border-0 outline-none opacity-5 focus:outline-none" onClick={onClick} > <span className="block w-6 h-6 text-2xl text-black bg-transparent outline-none opacity-5 focus:outline-none"> × </span> </button> </div> </> ); }; Header.propTypes = { onClick: PropTypes.func.isRequired, title: PropTypes.string.isRequired, }; export const Body = ({ children }) => { return ( <> {/* body */} <div className="relative flex-auto p-6">{children}</div> </> ); }; Body.propTypes = { children: PropTypes.element.isRequired, }; export const Footer = ({ onClick, text }) => { return ( <> {/* footer */} <div className="flex items-center justify-end p-6 border-t border-gray-300 border-solid rounded-b"> <button className="px-6 py-2 mb-1 mr-1 text-sm font-bold text-red-500 uppercase outline-none background-transparent focus:outline-none" type="button" style={{ transition: 'all .15s ease' }} onClick={onClick} > Close </button> <button className="px-6 py-3 mb-1 mr-1 text-sm font-bold text-white uppercase bg-green-500 rounded shadow outline-none active:bg-green-600 hover:shadow-lg focus:outline-none" type="button" style={{ transition: 'all .15s ease' }} onClick={onClick} > {text} </button> </div> </> ); }; Footer.propTypes = { onClick: PropTypes.func.isRequired, text: PropTypes.string.isRequired, };
function NuevoProductoEvent(div,callback,idToModified){ this.div = div; this.callback = callback; this.pathHtml = "html/productos/nuevoProducto.html"; this.idToModified = idToModified; this.service = new NuevoProductoService(); } NuevoProductoEvent.prototype.draw = function(){ $("#formContainer").load(this.pathHtml,$.proxy(this.renderView,this)); }; NuevoProductoEvent.prototype.renderView = function(comp){ CHANGEVIEW.toggleViewForm("#formContainer"); $("#formContainer").html(comp.replace(/{{id}}/g,this.div)); if(this.idToModified != 0 && this.idToModified) var product = this.service.getProductById(this.idToModified,$.proxy(this.completeForm,this)); this.initButtons(); }; NuevoProductoEvent.prototype.completeForm = function(productData){ GETOBJETC.getJqObjectById(this.div,"titleForm").text("Visualizando producto"); GETOBJETC.getJqObjectById(this.div,"title").val(productData.title); GETOBJETC.getJqObjectById(this.div,"details").val(productData.details); GETOBJETC.getJqObjectById(this.div,"quantity").val(productData.quantity); GETOBJETC.getJqObjectById(this.div,"productType").val(productData.productType); GETOBJETC.getJqObjectById(this.div,"brand").val(productData.brand); GETOBJETC.getJqObjectById(this.div,"forVegan").attr("checked",productData.for_vegan); GETOBJETC.getJqObjectById(this.div,"forCeliac").attr("checked",productData.for_celiac); GETOBJETC.getJqObjectById(this.div,"forDietetic").attr("checked",productData.for_dietetic); GETOBJETC.getJqObjectById(this.div,"forVegetarian").attr("checked",productData.for_vegetarian); }; NuevoProductoEvent.prototype.initButtons = function(){ GETOBJETC.getJqObjectById(this.div,"btnSubmit").button().click($.proxy(this.createProduct,this)); GETOBJETC.getJqObjectById(this.div,"btnCancel").button().click($.proxy(this.closePage,this)); GETOBJETC.getJqObjectById(this.div,"disableYESbtn").button().click($.proxy(this.disableProduct,this)); }; NuevoProductoEvent.prototype.createProduct = function(){ var product = { id: (this.idToModified != 0 && this.idToModified ? this.idToModified : null), title: GETOBJETC.getJqObjectById(this.div,"title").val(), details: GETOBJETC.getJqObjectById(this.div,"details").val(), quantity: GETOBJETC.getJqObjectById(this.div,"quantity").val(), idProductType: 1, idBrand: 1, for_vegan: GETOBJETC.getJqObjectById(this.div,"forVegan").prop('checked'), for_celiac: GETOBJETC.getJqObjectById(this.div,"forCeliac").prop('checked'), for_dietetic: GETOBJETC.getJqObjectById(this.div,"forDietetic").prop('checked'), for_vegetarian: GETOBJETC.getJqObjectById(this.div,"forVegetarian").prop('checked') }; if(this.idToModified != 0 && this.idToModified) this.service.updateProduct(product,$.proxy(this.closePage,this)); else this.service.createProduct(product,$.proxy(this.closePage,this)); }; NuevoProductoEvent.prototype.disableProduct = function(){ if(this.idToModified != 0 && this.idToModified){ this.service.disableProduct(this.idToModified,$.proxy(this.closePage,this)); } }; NuevoProductoEvent.prototype.closePage = function(){ if(this.callback) this.callback(); CHANGEVIEW.toggleViewForm("#viewContainer"); }; NuevoProductoEvent.init = function(callback,productIdToModify){ var nuevoProductoEvent = new NuevoProductoEvent("nuevoProducto",callback,productIdToModify); nuevoProductoEvent.draw(); }
X.define("modules.infoManage.myResponseDetail",["model.infoManageModel", "model.userModel", "modules.common.moment"], function (infoManageModel, userModel, moment) { //初始化视图对象 var view = X.view.newOne({ el: $(".xbn-content"), url: X.config.infoManage.tpl.myResponseDetail }); //初始化控制器 var ctrl = X.controller.newOne({ view: view }); ctrl.getData = function (callback) { infoManageModel.getMyResponseDetailById(_para["myResponseId"], callback); }; ctrl.rendering = function () { var callback = function (model) { var temp = {}; var purchaseInfo = model.purchaseInfo; var responseInfo = model.responseInfo; var status = ''; for (var p in purchaseInfo) { if (p === "infoType") { if (purchaseInfo[p] === '0') { purchaseInfo[p] = "招标"; } else if (purchaseInfo[p] === '1') { purchaseInfo[p] = "询价"; } } var tempIndex = p.slice(0, 1).toUpperCase() + p.slice(1); var index = 'purchase' + tempIndex; temp[index] = purchaseInfo[p]; } for (var p in responseInfo) { var tempIndex = p.slice(0, 1).toUpperCase() + p.slice(1); var index = 'response' + tempIndex; temp[index] = responseInfo[p]; } var data = temp; return view.render(data, function () { var fileUploadController = window.X.config.PATH_FILE.path.rootUploadUrl || []; var responseAttach = data.responsePurchaseResponseAttachmentList || []; var purchaseAttach = data.purchasePurchaseInfoAttachmentList || []; ctrl.displayFile = function(content, postions){ $.each(content, function (i, item) { var filesPostion = '<div class="eeeBlock mb10 f14">' + '<a target="_blank" href=' + fileUploadController + '?fileType=4&filePath=' + item.filePath + '&fileName=' + item.fileName + ' class="underline col66">' + item.fileName + '</a>' + '</div>'; ctrl.view.el.find(postions).append(filesPostion); }); }; ctrl.displayFile(responseAttach,".js-responseAttach"); ctrl.displayFile(purchaseAttach,".js-purchaseAttach"); if (purchaseInfo.priceResponse === '1') { ctrl.view.el.find('.js-ResponsePrice').hide(); } if (responseInfo['responseResult'] === '0') { ctrl.view.el.find('.js-status').attr('src', '././images/needFeedback.png'); } else if (responseInfo['responseResult'] === '1') { ctrl.view.el.find('.js-status').attr('src', '././images/winner.png'); } else if (responseInfo['responseResult'] === '2') { ctrl.view.el.find('.js-status').attr('src', '././images/noWining.png'); } else if (responseInfo['responseResult'] === '3') { ctrl.view.el.find('.js-status').attr('src', '././images/abandon.png'); } else if (responseInfo['responseResult'] === '4') { ctrl.view.el.find('.js-status').attr('src', '././images/purpose.png'); } else if (responseInfo['responseResult'] === '5') { ctrl.view.el.find('.js-status').attr('src', '././images/notadopted.png'); } ctrl.view.el.find('.js-responseInfo').html(responseInfo['responseInfo']); ctrl.view.el.find('.js-purchaseAnnounced').html(purchaseInfo['announced']); ctrl.view.el.find('.js-purchaseSummary').html(purchaseInfo['summary']); var purchaseInfoId = model.purchaseInfo.purchaseInfoId; var callback = function(result){ if(result.statusCode == 2000000){ var list = result.data.list; list.sort(function (a, b) { return moment(a.messageTime) - moment(b.messageTime); }) for (var i = 0, len = list.length; i < len; i++) { var messageTime = list[i].messageTime.split(' ')[0]; var messageSource = ';' var messageType = ''; if (list[i].messageSource === '0') { messageSource = '供应商'; messageType = '问'; } else if (list[i].messageSource === '1') { messageSource = '采购商'; messageType = '答'; } var message = '<p class="mb10"><span class="f14 col66">' + messageSource + '</span><span class="ml20">' + messageTime + '</span></p><span class="askAnswerLabel bgcDarkOran vat">' + messageType + '</span><div class="disib ml10 bgcee lh30 w95p bsb pl10">' + list[i].message + '</div>'; ctrl.view.el.find('.js-message').append(message); } if (responseInfo['responseResult'] === '0') { ctrl.view.el.find('.js-ask').show(); } else { ctrl.view.el.find('.js-ask').hide(); } if(model.purchaseInfo["purchaseInfoId"]){ var companyId =""; userModel.getUserInfo(function(data){ companyId = data.data[0].companyId; }); $(".js-questionFontError").html( ''); $(".js-questionFont").keyup(function(e) { var length = $(".js-questionFont").val().length; if (length > 5) { $(".js-questionFontError").html(''); } }); infoManageModel.getById(model.purchaseInfo["purchaseInfoId"], function(data) { $(".js-question").click(function () { if ($(".js-questionFont").val().length <= 5) { $(".js-questionFontError").html( '请输入超过5字进行提问哦'); } else { $(".js-questionFontError").html( ''); var _data = { "businessInfoId": data.purchaseInfoId, "businessType": data.infoType, "message": $(".js-questionFont").val(), "messageSource": 0, "receiveCompanyId": companyId, "senderCompanyId": data.purchaserCompanyId } infoManageModel.setMessage(_data, function (result) { $(".js-questionFont").val(""); ctrl.load(_para); }); } }); }); }; } }; infoManageModel.findMessageByPage(purchaseInfoId, callback); }); }; ctrl.getData(callback); }; var _para; ctrl.load = function(para){ para = para || {}; _para = para ; ctrl.rendering(); }; return ctrl; });
function printString(string){ console.log(string[0]) if(string.length > 1 ){ let substring = string.substring(1, string.length) printString(substring) } else { return true } } function reverseString(string){ if (string.length > 1) { return string[string.length - 1] + reverseString(string.substring(0, string.length - 1)) } else { return string[string.length - 1] } } function isPalindrome(string){ if (string.length > 1){ if (string[0] === string[string.length -1]){ return isPalindrome(string.slice(1, -1)) } else { return false } } else { return true } } function addUpTo(array, index){ if ( array.length > index ) { return array[0] + addUpTo(array.slice(1), index) } else { return array[0] } } // function maxOf(array){ // if ( array.length > 1 ) { // if (array[0] < maxOf(array.slice(1))) { // return maxOf(array.slice(1)) // } else { // return array[0] // } // } else { // return array[0] // } // } // called 11 times instead of 4 function maxOf(array){ if (array.length > 1){ if (array[1] > array[0]){ return maxOf(array.slice(1)) } else { return maxOf(array.slice(0,1).concat(array.slice(2,array.length))) } } else { return array[0] } } function includesNumber(array, element){ if ( array.length > 1 ) { if (array[0] != element) { return includesNumber(array.slice(1), element) } else { return true } } else { return false } }
var config = require('../../config'); var link = require('../../models/link'); exports.viewLink = function(req, res, next) { link.findAll() .then(function(links) { res.render('admin/view_link', { config: config, links: links }) }) } exports.ShowCreateLink = function(req, res, next) { res.render('admin/create_link', { config: config }) } exports.createLink = function(req, res, next) { var name = req.body.name; var url = req.body.url; link.createOne({ name: name, url: url }).then(function() { res.redirect('/admin/links/view'); }); } exports.removeLink = function(req, res, next) { var id = req.params.id; link.removeById(id) .then(function() { res.redirect('/admin/links/view'); }); }
var jsutil = jsutil || {}; jsutil.Predicate = { always: function(a) { return true; }, never: function(a) { return false; }, not: function(a) { return function(v) { return !a(v); }; }, and: function(a,b) { return function(v) { return a(v) && b(v); }; }, or: function(a,b) { return function(v) { return a(v) || b(v); }; }//, };
const app = Vue.createApp({ data() { return { userName:'', enterUserName:'' }; }, methods: { enterRegisterUser (event) { this.enterUserName = event.target.value; }, registerUser (event) { this.userName = event.target.value; }, submitForm () { alert('Submitted !'); } } }); app.mount('#assignment');
const User = require('../models/User'); const ErrorResponse = require('../utils/errorResponse'); const asyncHandler = require('../middleware/async'); // @desc Register user // @route GET /api/v1/auth/register // @access Public exports.register = asyncHandler(async (req, res, next) => { const { name, email, password, role } = req.body; // Create user const user = await User.create({ name, email, password, role }); res.status(200).json({ success: true }); });
//We codin //console.log('Hello World!'); //console.log(Date()); //console.log("Hello" + " " + "World"); //console.log(`Hello World`); // //************************************* // var name = 'Jordan'; // console.log(name); // let age = 25; // console.log(age); // const isRobot = false; //console.log(isRobot); //console.log("My name is" + " " + name " " + "I am" + " " + age + " " + "years old!"); //console.log(`My name is: ${name}. I am ${age} years old!`); //console.log(2 + 6); //******************************************************* // const justiceLeague = ['Superman', 'Batman', 'Wonder Woman']; // console.log(justiceLeague); // console.log(justiceLeague[0]); // console.log(justiceLeague[1]); // console.log(justiceLeague.includes('Flash')); // const person = { // name: 'Jordan', // age: 3, // isRobot: false, // }; // console.log(person.name); // const { name, age, isRobot } = person; // console.log(name, age, isRobot); // if ( age >= 21 ) { // console.log("Getting WAsted!!"); // } else { // console.log('nahhh'); // } //************************************************** //while loop: iterates block of javascript given while condition is true // let number = 0; // while ( number <= 10 ) { // console.log (number); // number = number + 1; // } // //for loop: similar to while loops, except inside of while considition is true, loop through a block of code a number of times // //number of loops or iterations are based on variable set inside for loop // for (let i = 0; i <= 10; i++){ // console.log(`i is currently: ${i}`); // } //for every number in 100 //fizzbuzz challenge // if number is divisible by 3 print fizz // if number is divisible by 5 print buzz // if number is divisible by 3 + 5 print fizzbuzz // if number is not divisible by 3 or 5 print the number // for(let i = 0; i <= 100; i++) { // if (i % 3 === 0) { // console.log(`Fizz: ${i}`); // } // if (i % 5 === 0) { // console.log(`Buzz: ${i}`); // } // if (i % 3=== 0 && i % 5 === 0) { // console.log(`FizzBuzz: ${i}`); //} //********************************************************** // function oldAddNumbers(num1, num2) { // return num1 + num2 // } // console.log(oldAddNumbers(2, 3)); // const newAddNumbers = (num1, num2) => { // return num1 + num2; // }; // console.log(newAddNumbers(2, 3)); // JavaScript Basics Test #1 // In this test you will be putting together everything you have learned thus far // You will create a function ( either Es6 or pre-Es6 ) and the function will take in one parameter // The parameter is going to be an array, you can set this as a default using Es6 syntax // alternatively if you want to use pre-Es6 here is the array to pass when you call the function // const numberArray = [2, 5, 8, 3, 11, 4, 15] // 1. Create a function that takes an array as a parameter // 2. Loop through the array // 3. While looping through the array grab all numbers that are greater than 5 // 4. Find the sum of all the numbers that are greater than 5 // to find the length of an array you do array.length const testFunction = (array = [2, 5, 8, 3, 11, 4, 15]) => { let sum = 0; for (let i = 0; i < array.length; i++) { // console.log(array[i]); if (array[i] > 5) { sum = sum + array[i] } } return sum }; console.log(testFunction([55, 25, 66, 2, 4, 777])); //for (let i = 0; ; i++) {}
'use strict'; angular.module('SBSApp', ['angularUtils.directives.dirPagination','ngSanitize', 'ngCsv']) .constant("myConfig", { //DM::All configurations will be stored here "baseURL": "http://172.25.102.115", "port": "8086", "pSBSnoofsbs": "/api/noofpsbs", "pSBSnoofconn": "/api/noofconn_PSBS", "pSBSnoofmeta": "/api/psbsMetadata", "sSBSnoofsbs": "/api/noofsbs", "sSBSnoofconn": "/api/noofconn_SBS", "sSBSnoofmeta": "/api/sbsMetadata", "sTradeConfInfo": "/api/TradeConfInfo", "sTradeConfCount": "/api/TradeConfCount" }) .controller('dashboardCtrl', dashboardCtrl) .controller('calcCtrl', calcCtrl) .controller('authCtrl', authCtrl) .filter('trustedAudioURL', trustedAudioURL); function trustedAudioURL ($sce) { return function (audioURL) { return $sce.trustAsResourceUrl(audioURL); } } function getNoOfPSBS($scope, $http, myConfig) { //console.log("URL: " + myConfig.baseURL + ':' + myConfig.port + myConfig.pSBSnoofsbs); $scope.pSBSnoofsbs = { count : 0 }; $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.pSBSnoofsbs) }). then(function successCallback(response) { //console.log(response); $scope.pSBSnoofsbs = response; $scope.pSBSnoofsbs.count = (response.data.length) ? (response.data.length) : 0; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - No of PrimarySBS"); }); } function getNoOfConnPSBS($scope, $http, myConfig) { //console.log("URL: " + myConfig.baseURL + ':' + myConfig.port + myConfig.pSBSnoofconn); $scope.pSBSnoofconn = { count : 0 }; $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.pSBSnoofconn) }). then(function successCallback(response) { //console.log(response); $scope.pSBSnoofconn = response; $scope.pSBSnoofconn.count = response.data[0].ConSum; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - No of connections to PrimarySBS"); }); } function getMetadataPSBS($scope, $http, myConfig) { //console.log("URL: " + myConfig.baseURL + ':' + myConfig.port + myConfig.pSBSnoofmeta); $scope.pSBSnoofmeta = { count : 0 }; $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.pSBSnoofmeta) }). then(function successCallback(response) { //console.log(response); $scope.pSBSnoofmeta = response; $scope.pSBSnoofmeta.count = response.data[0].ConSum; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - Metadata of PrimarySBS"); }); } function getNoOfSSBS($scope, $http, myConfig) { //console.log("URL: " + myConfig.baseURL + ':' + myConfig.port + myConfig.sSBSnoofsbs); $scope.sSBSnoofsbs = { count : 0 }; $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.sSBSnoofsbs) }). then(function successCallback(response) { //console.log(response); $scope.sSBSnoofsbs = response; $scope.sSBSnoofsbs.count = response.data.length; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - No of SecondarySBS"); }); } function getNoOfConnSSBS($scope, $http, myConfig) { //console.log("URL: " + myConfig.baseURL + ':' + myConfig.port + myConfig.sSBSnoofconn); $scope.sSBSnoofconn = { count : 0 }; $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.sSBSnoofconn) }). then(function successCallback(response) { //console.log(response); $scope.sSBSnoofconn = response; $scope.sSBSnoofconn.count = response.data[0].ConSum; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - No of connections to SecondarySBS"); }); } function getMetadataSSBS($scope, $http, myConfig) { //console.log("URL: " + myConfig.baseURL + ':' + myConfig.port + myConfig.sSBSnoofmeta); $scope.sSBSnoofmeta = { count : 0 }; $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.sSBSnoofmeta) }). then(function successCallback(response) { //console.log(response); $scope.sSBSnoofmeta = response; $scope.sSBSnoofmeta.count = response.data[0].ConSum; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - Metadata of SecondarySBS"); }); } function getTradeConfServiceInfo($scope, $interval, $http, myConfig) { $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.sTradeConfInfo) }). then(function successCallback(response) { //console.log(response); $scope.sTradeConfInfo = response; console.log(response); console.log($scope.sTradeConfInfo); //$scope.sTradeConfInfo.count = response.length; }, function errorCallback(err) { console.log(err); //alert("Error in fetching data. - Metadata of SecondarySBS"); }); } function getTradeConfCounts($scope,$interval, $http, myConfig) { // $http({ // method: 'GET', // url: (myConfig.baseURL + ':' + myConfig.port + myConfig.sTradeConfCount) // }). // then(function successCallback(response) { // console.log(response); // $scope.sTradeConfCounts = response.data[0]; // }, // function errorCallback(err) { // console.log(err); // //alert("Error in fetching data. - Metadata of SecondarySBS"); // }); $interval(function () { $http({ method: 'GET', url: (myConfig.baseURL + ':' + myConfig.port + myConfig.sTradeConfCount) }). then( function successCallback(response) { console.log(response); if($scope.sTradeConfCounts.dLastUpdateTime != response.data[0].dLastUpdateTime) { $scope.start = 1; } else $scope.start = 0; var oldcount = $scope.sTradeConfCounts.nActiveCount; //take backup of old active calls count $scope.sTradeConfCounts = response.data[0][0]; if(oldcount != $scope.sTradeConfCounts.nActiveCount) //compare old and current active calls { getTradeConfServiceInfo($scope,$interval,$http, myConfig); //get current data } }, function errorCallback(err) { //console.log(err); //alert("Error in fetching data. - Metadata of SecondarySBS"); }); }, 1000); } function dashboardCtrl($scope, $rootScope, $interval, $http, myConfig) { console.log("Dashboard controller called"); console.log($rootScope.name); $scope.name = $rootScope.name; console.log($scope.name); $scope.sTradeConfInfo = []; $scope.currentPage = 1; // getNoOfPSBS($scope, $http, myConfig); // getNoOfConnPSBS($scope, $http, myConfig); // getMetadataPSBS($scope, $http, myConfig); // getNoOfSSBS($scope, $http, myConfig); // getNoOfConnSSBS($scope, $http, myConfig); // getMetadataSSBS($scope, $http, myConfig); getTradeConfServiceInfo($scope, $interval, $http, myConfig); getTradeConfCounts($scope, $interval, $http, myConfig); $scope.start = 0; $scope.sTradeConfCounts = []; $scope.sTradeConfCounts.dLastUpdateTime = 0; // $interval(function () { // if ($scope.start == 0) return; // getTradeConfServiceInfo($scope, $interval, $http, myConfig) // },1000); $scope.SortByMe=function(x){ if( $scope.SortBy == x ){ if ( $scope.reverse != true ){ $scope.reverse = true; $scope.SortIcon = 'fa fa-sort-desc'; } else{ $scope.reverse = false; $scope.SortIcon = 'fa fa-sort-asc' } } else{ $scope.SortBy=x; $scope.reverse=false; $scope.SortIcon = 'fa fa-sort-asc'; } } // $scope.saveJSON = angular.toJson($filter('filter')($scope.sTradeConfInfo.data,$scope.searchFilter)); } function calcCtrl() { } function authCtrl($scope, $rootScope, $http, myConfig) { //console.log("In"); var logonsuccess = function (res) { //$scope.msg = res.data.msg; if(res.data.success == true) { window.location.href = "dashboard.html"; console.log(res.data.clientname); } }; var logonerror = function (res) { $scope.msg = res.msg; $scope.msgicon = 'fa-check'; }; $scope.onlogin = function () { console.log("post"); var uri = myConfig.baseURL + ':' + myConfig.port + '/api/login'; $http.post(uri, { email: $scope.email, pwd: $scope.password }).then(logonsuccess, logonerror); }; // }
// JavaScript source code for login $(document).ready(function () { // 이미 로그인되어 있는지 확인 setInterval(function () { if ($.cookie('login_info')) { $('html').html(''); alert('이미 로그인되어있습니다.'); window.close(); } }, 1000); // 버튼 클릭 및 마우스 over $('#loginBtn').hover(function () { $('#loginBtn a').css('color', 'red'); }, function () { $('#loginBtn a').css('color', 'white'); }); $('#signUpBtn').hover(function () { $('#signUpBtn a').css('color', 'red'); }, function () { $('#signUpBtn a').css('color', 'white'); }); $('#signUpBtn').on('click', function () { window.location.href = './sign_up.html'; }); // 카카오톡 로그인 연동 Kakao.init('42470b02a188ed6fc75a1fc93063c8f7'); Kakao.Auth.createLoginButton({ container: '#kakao-login-btn', success: function (authObj) { Kakao.API.request({ url: '/v2/user/me', success: function (response) { setLoginCookie(encodeURIComponent(response.properties['nickname'])); window.close(); }, fail: function (error) { alert(JSON.stringify(error)); } }); }, fail: function(error){ alert(JSON.stringify(error)); } }); // 로그인 버튼 클릭 $('#loginBtn').on('click', function () { var idValidity = isValidId($('#userId').val()); var pwValidity = isValidPw($('#userPw').val()) if (idValidity == false) { alert('아이디를 확인해주세요.\n아이디는 숫자와 영문만 가능합니다.'); $('#userId').focus(); } else if (pwValidity == false) { alert('비밀번호는 5글자 이상이어야 합니다.'); $('#userPw').focus(); } else { //< 유효성 검사 통과 $.ajax({ url: './login.json', type: 'POST', data: $('#loginform').serializeArray(), success: function (result) { if (result['success'] == false) { if (result['idcode'] == 'password') alert('비밀번호를 다시 확인해주세요.'); else if (result['idcode'] == 'id') alert('아이디를 다시 확인해주세요.'); } else { setLoginCookie(result['idcode']); window.close(); } } }); } }); }); //! @Return //! valid -> true, invalid -> false function isValidId(value) { var validRegx = /[^a-zA-Z0-9]/g; var isValid = true; if (validRegx.test(value)) //< 특수문자가 있으면 isValid = false; if (value == '') isValid = false; return isValid; } function isValidPw(value) { if (value.length < 5) return false; else return true; } // 로그인 쿠키 함수 function setLoginCookie(value) { var name = 'login_info' $.cookie(name, value); }
const Discord = require('discord.js'); const config = require('../config.json'); const bot = new Discord.Client(); bot.login(config.token); const main = class Main { constructor() { this.partyActive = false; this.partyCreator = ''; this.maxPlayer = 0; this.activePlayer = 1; this.partyCreatorMP; this.partyPlayer = []; } createParty (type) { bot.on('message', (msg) => { if (msg.content === `${config.prefix}${config.command.create}${type}`) { msg.delete(); if (!this.partyActive) { msg.channel.send(`${msg.author} cherche des gens @everyone pour une partie ${type}.`) this.partyActive = true; this.partyCreator = msg.author.username; this.partyCreatorMP = msg.author; this.partyPlayer.push(this.partyCreator); } else { msg.channel.send(`**Une recherche ${type} a déjà été lancée. Attendez la fin du recrutement ou tapez " ${config.prefix}${config.command.join}${type} "**`); } } }); } joinParty (type) { let message; let indexOfPlayer; let newMessage; bot.on('message', (msg) => { if (msg.content === `${config.prefix}${config.command.join}${type}`) { msg.delete(); if (this.partyActive && this.activePlayer <= this.maxPlayer) { if (this.partyPlayer[this.partyPlayer.indexOf(this.partyCreator)] === msg.author.username) { msg.channel.send('Vous faites déjà parti du groupe'); } else { this.partyPlayer.push(`${msg.author.username}`); } message = `Player présent dans le groupe ${type} :\n`; for (let player of this.partyPlayer) { message += `-${player}\n`; } msg.channel.send(message); if (this.activePlayer == this.maxPlayer) { this.partyActive = false; this.activePlayer = 1; message = ''; msg.channel.send('Groupe complet.'); } } else { if (this.activePlayer == this.maxPlayer) { msg.channel.send(`**La partie ${type} est complète. Relancer une recherche avec " ${config.prefix}${config.command.create}${type}".**`); } else { msg.channel.send(`**Aucune partie ${type} a été créée, tapez " ${config.prefix}${config.command.create}${type} " pour en créer une.**`); } } ++this.activePlayer; } if (msg.content === `${config.prefix}${config.command.leave}${type}`) { indexOfPlayer = this.partyPlayer.indexOf(`${msg.author.username}`); msg.delete(); if (this.partyActive && this.partyCreator !== msg.author.username) { if (this.partyPlayer[indexOfPlayer] === msg.author.username) { if (indexOfPlayer > -1) { this.partyPlayer.splice(indexOfPlayer, 1); } msg.channel.send(`${msg.author.username} a quitté(e) le groupe.`); } else { msg.channel.send(`Vous ne faites pas partie d'un groupe, tapez " ${config.prefix}${config.command.join}${type} " pour rejoindre le groupe.`); } newMessage = `Player présent dans le groupe ${type} :\n`; for (let player of this.partyPlayer) { newMessage += `-${player}\n`; } msg.channel.send(newMessage); } else { if (!this.partyActive) { msg.channel.send(`**Aucune partie ${type} a été créée, tapez " ${config.prefix}${config.command.create}${type} " pour en créer une.**`); } else { this.partyActive = false; this.partyPlayer = []; msg.channel.send(`**La partie ${type} a été détruite par ${this.partyCreator}, tapez " ${config.prefix}${config.command.create}${type} " pour en créer une.**`); } } } }); } stopParty (type) { bot.on('message', (msg) => { if (msg.content === `${config.prefix}${config.command.stop}${type}`) { msg.delete(); if (this.partyActive && this.partyCreator === msg.author.username) { this.partyActive = false; this.activePlayer = 1; msg.channel.send(`**La recherche de groupe ${type} a été arrêtée par ${this.partyCreator}.**`); } else if (!this.partyActive) { msg.channel.send(`**Aucune partie ${type} a été créée, tapez " ${config.prefix}${config.command.create}${type} " pour en créer une.**`) } else { msg.channel.send(`**Vous ne pouvez pas arrêter la recherche car elle ne vous appartient pas. MP ${this.partyCreatorMP}.**`); } } }) } } module.exports = main;
var express = require("express"); var scrapeDolarToday = require('./scraper.js'); // Setting our server var app = express(); var port = process.env.PORT || 8000; app.use(express.static("public")); app.set("view engine", "ejs"); // Every day scrape http://dolartoday.com // (We'll call scrapeDolarToday() as soon as the server starts because Heroku... // won't let the server run 24/7) scrapeDolarToday(); setInterval(scrapeDolarToday, 1000*60*60*24) // Render our index.html page in the "/" route app.get("/", function(req, res){ res.render("index"); }); // Express starting to work app.listen(port, function(){ console.log("Server is listening on: " + port); });
X.define("modules.customerClearance.productManage", ["modules.common.routerHelper","model.productManageModel"], function (routerHelper, model) { //初始化视图对象 var view = X.view.newOne({ el: $(".xbn-content"), url: X.config.customerClearance.tpl.productManage }); //初始化控制器 var ctrl = X.controller.newOne({ view: view }); var gridColumns = [ { field:{ name:"", title:"序号", type:"int" }, width:"5%", itemRenderer: { render: function(data) { return '' + (data['_index'] + 1) } }, className:"tL" }, { field:{ name: "nameCn", title:"产品名称", type:"string" }, width:"8%" }, { field:{ name:"nameEn", title:"产品英文名称", type:"string" }, width:"8%" }, { field:{ name:"hsCode", title:"hsCode", type:"string" }, width:"8%" }, { field:{ name:"brand", title:"品牌", type:"string" }, width:"8%" }, { field:{ name:"texture", title:"材质", type:"string" }, width:"5%" }, { field:{ name:"createTime", title:"提交时间", type:"string" }, itemRenderer: { render: function(data) { return data.createTime? data.createTime.split(' ')[0]:'' } }, width:"5%" }, { field:{ name:"auditerName", title:"审核人", type:"string" }, width:"5%" }, { field:{ name:"status", title:"状态", type:"string" }, itemRenderer: { render: function(data) { return model.productStatus[data.status] } }, width:"5%" }, { field:{ name:"", title:"操作" }, itemRenderer: { render: function (data) { return '<span class="productDetail curp colBlue" id="'+ data.productId +'" status="'+ data.status +'">'+ (data.status == 1? '审核': '详情') +'</span>' } }, width:"10%" } ] var header = {}, schemas = {} var searchMeta = { schema: { simple: [ { name:"nameCn", inputName: "nameCn", title:"产品名称", ctrlType:"TextBox", placeholder :"产品名称", className : "mr30" }, { name:"status", inputName: "status", title:"状态", ctrlType:"ComboBox", className: '', dataSource: model.genAuditStatus() } ] }, search: { onSearch : function(data, searcher) { if (!data.query.status) { data.query.status = searcher.elem.parent().index() - 1 } data.query.status == 0 && delete data.query.status return data } } } var events = { init: function() { this.genSchemas() view.el.on('click', '.productDetail', function() { var id = this.id, status = this.getAttribute('status') X.router.run('m=customerClearance.productDetail&id='+id+'&status='+status) }) }, genSchemas: function() { model.auditStatus.forEach(function(item, i) { var schema = { searchMeta: searchMeta, gridMeta: {columns: gridColumns}, pageInfo: { pageSize : '10', pageNo : '1' }, url: X.config.customerClearance.api.productManage } schemas[item] = schema }) } } var getRoute = function () { var route = {panel:activeTabLiInfo,ldata:lists[activeTabLiInfo].val()}; return route; }; var lists = {}; var activeTabLiInfo = model.auditStatus[0]; function initTabPage($elem,schema,tabPage) { var list = X.controls.getControl("List",$elem,schema); list.init(); lists[tabPage] = list; }; ctrl.load =function (){ view.render(function(){ activeTabLiInfo = route.getRoute() || activeTabLiInfo; events.init() var tabPannel = X.controls.getControl("TabPanel", $('.js_tabPannel'), { activeTabInfo: activeTabLiInfo, beforeChangeTab: function (tabLiInfo, targetLi, index, tabPage) { activeTabLiInfo = tabLiInfo; // 刊登状态 不同 var page = $(tabPage); if(!page.data("hasInited")){ var schema = schemas[tabLiInfo]; if(schema){ initTabPage(page,schema,tabLiInfo); } page.data("hasInited",true); } return true; }, afterChangeTab: function (tabLiInfo, targetLi, index, tabPage,oldTab) { activeTabLiInfo = tabLiInfo; activeTabLi = targetLi; if(tabLiInfo!=oldTab){ route.setRoute({panel:tabLiInfo}); } var statusCom = $('.js-status').parent().parent() index? statusCom.hide(): statusCom.show() } }); }) }; var route = new routerHelper("customerClearance.productManage",schemas,getRoute); return ctrl })
import React, { Component } from 'react'; import classNames from 'classnames' import $ from 'jquery' import mydarktheme from './mydarktheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import DatePicker from 'material-ui/DatePicker'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import TextField from 'material-ui/TextField'; import Dialog from 'material-ui/Dialog'; import Divider from 'material-ui/Divider'; import CircularProgress from 'material-ui/CircularProgress'; import logo from '../assets/logo.png'; import './App.css'; const styles = { margin: 6, }; function formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); } class App extends Component { state = { open: false, start_date: null, end_date: null, num_pax: null, num_pax_error:'', weather: null, avg_distance: null, avg_distance_error: '', num_vehicles: null, num_vehicles_error: '', mre_per_day: null, mre_per_day_error: '', ugr_per_day: null, ugr_per_day_error: '', dialog_error: '', loading: true } setstart_date = (data: undefined, date: object) => { this.setState({start_date: formatDate(date)}) } setend_date = (data:undefined, date: object) => { this.setState({end_date: formatDate(date)}) } handleOpen = () => this.setState({open: true}) handleClose = () => this.setState({open: false}) setTemperature = (weather) => this.setState({weather: weather}) submit = () => { let newState = {} if (this.state.num_pax === null || this.state.num_pax === '') newState['num_pax_error'] = 'Fill with positive Pax count' if (this.state.avg_distance === null || this.state.avg_distance === '') newState['avg_distance_error'] = 'Fill average distance traveled' if (this.state.num_vehicles === null || this.state.num_vehicles === '') newState['num_vehicles_error'] = 'Fill number of vehicles needed' if (this.state.mre_per_day === null || this.state.mre_per_day === '') newState['mre_per_day_error'] = 'Fill number of MRE needed' if (this.state.ugr_per_day === null || this.state.ugr_per_day === '') newState['ugr_per_day_error'] = 'Fill number of UGR needed' if (this.state.weather === null) newState['dialog_error'] = 'Pick the temperature of the location that will be planned for' if (this.state.start_date === null || this.state.end_date === null || typeof this.state.start_date === 'undefined' || typeof this.state.end_date === 'undefined' ) newState['dialog_error'] = 'Fill out out start date and end date information' else if (this.state.end_date < this.state.start_date) newState['dialog_error'] = 'The start date needs to be earlier than the end date' if (Object.keys(newState).length !== 0) this.setState(newState, () => { if (newState['dialog_error'] !== null) { window.scrollTo(0,0) this.handleOpen() } }) else { let data = { start_date: this.state.start_date, end_date: this.state.end_date, num_pax: parseInt(this.state.num_pax, 10), weather: this.state.weather, avg_distance: parseFloat(this.state.avg_distance, 10), num_vehicles: parseInt(this.state.num_vehicles, 10), mre_per_day: parseInt(this.state.mre_per_day, 10), ugr_per_day: parseInt(this.state.ugr_per_day, 10) } data = JSON.stringify(data) let http = window.location.protocol let host = window.location.hostname let endpoint = `${http}//${host}:80/api/v1/form` let request = () => { $.ajax({ type: "POST", url: '/api/v1/form', data: data, success: (data) => { console.log(data) this.props.history.push(`/result/${data['id']}`) }, dataType: 'json', settings: { contentType: 'application/json; charset=UTF-8' } }); } this.setState({ loading: false }, request) } } temperatureButtons = () => { return [ {temp: 'Cold', color: '#61a8ff'}, {temp: 'Mild', color: '#ffba0a'}, {temp: 'Hot', color: '#ff6161'} ].map( temp_object => { let classes = this.state.weather !== null && this.state.weather === temp_object.temp ? ['temperature-button', 'active'] : ['temperature-button'] return <RaisedButton className={classNames(classes)} style={styles} label={temp_object.temp} onClick={() => this.setTemperature(temp_object.temp)} backgroundColor={temp_object.color} labelColor="#fff" /> }) } saveInfo = (key, value) => { let newState = { ugr_per_day_error: '', mre_per_day_error: '', num_pax_error: '', num_vehicles_error: '', avg_distance_error: '', [key]: value } this.setState(newState) } render() { const actions = <FlatButton label="Ok" primary={true} onClick={this.handleClose} /> const muiTheme = getMuiTheme(mydarktheme); return ( <div className='App-container'> {this.state.loading ? ( <div className="App"> <header className="App-header"> <center> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">IPAS-135</h1> </center> </header> <MuiThemeProvider muiTheme={muiTheme}> <List className='form'> <Subheader>Date</Subheader> <ListItem className='form-input date-input' children={ <DatePicker onChange={this.setstart_date} hintText="Start date" /> } /> <ListItem className='form-input date-input' children={ <DatePicker onChange={this.setend_date} hintText="End date" /> } /> <Subheader>Logistics</Subheader> <ListItem className='form-input' children={ <TextField floatingLabelText='Total PAX Estimate' hintText="Amount of personnel attending" type="number" min="0" onChange={(event: object, newValue: string) => this.saveInfo('num_pax', newValue)} errorText={this.state.num_pax_error} /> } /> <ListItem className='form-input' children={ <TextField floatingLabelText="Average distance traveled per day" hintText="Miles traveled per day" type="number" min="0" onChange={(event: object, newValue: string) => this.saveInfo('avg_distance', newValue)} errorText={this.state.avg_distance_error} /> } /> <ListItem className='form-input' children={ <TextField floatingLabelText="Total number of vehicles" type="number" min="0" onChange={(event: object, newValue: string) => this.saveInfo('num_vehicles', newValue)} errorText={this.state.num_vehicles_error} /> } /> <ListItem className='form-input' children={ <TextField floatingLabelText="Daily MRE count" hintText="MREs needed per person per day" type="number" min="0" onChange={(event: object, newValue: string) => this.saveInfo('mre_per_day', newValue)} errorText={this.state.mre_per_day_error} /> } /> <ListItem className='form-input' children={ <TextField floatingLabelText="UGR count" hintText="UGRs needed per person per day" type="number" min="0" onChange={(event: object, newValue: string) => this.saveInfo('ugr_per_day', newValue)} errorText={this.state.ugr_per_day_error} /> } /> </List> </MuiThemeProvider> <center> <h3 className='climate'>Climate</h3> </center> <div className='temperature-input'> {this.temperatureButtons()} </div> <Divider style={{marginBottom: '30px', marginTop: '30px', width: '80%', display: 'block', marginLeft: 'auto', marginRight: 'auto'}}/> <div> <RaisedButton primary={true} className='submit' label="Submit Plan" onClick={this.submit} /> </div> <Dialog actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > {this.state.dialog_error} </Dialog> <br></br> <center> <p> &copy; 2017 </p> </center> <br></br> </div> ) : ( <div className='loading'> <CircularProgress className='loading-item' size={80} thickness={5} /> <h1 className='loading-item'>Submitting form data</h1> </div> ) } </div> ); } } export default App;
import React, { useState, useEffect, Fragment, useRef } from 'react' import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom'; import { makeStyles } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import TextField from '@material-ui/core/TextField'; import { Grid, Button, CssBaseline, IconButton, Paper, Typography, Divider, Box, InputBase, Container, ButtonBase, Snackbar, SnackbarContent, Avatar, Fab, Hidden, Slide, AppBar, Toolbar } from '@material-ui/core'; import { Search as SearchIcon, Directions as DirectionsIcon, FilterList as FilterListIcon, Class } from '@material-ui/icons'; import Pagination from './Pagination'; import LinearLoading from '../../Components/LoadingBars/LinearLoading'; import CircularLoading from '../../Components/LoadingBars/CircularLoading'; import jobImg from '../../images/job.svg' import clsx from 'clsx'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import axios from 'axios' import JobListings from './JobListings'; import CloseIcon from '@material-ui/icons/Close'; import api from '../../api'; import FilterSelect from '../../Components/FilterSelect' import styled from 'styled-components'; import Slider from 'react-slick'; import "slick-carousel/slick/slick.css"; import "slick-carousel/slick/slick-theme.css"; import Popover from '@material-ui/core/Popover'; import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft' import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight' import './index.css'; import JobFilterSideBar from './JobFilterSideBar'; import JobsCarouselSkeletonLoading from '../../Components/SkeletonLoading/JobsCarouselSkeletonLoading'; import JobListingsSkeletonLoading from '../../Components/SkeletonLoading/JobListingsSkeletonLoading'; import { useSnackbar } from 'notistack'; import ClearIcon from '@material-ui/icons/Clear' import SortIcon from '@material-ui/icons/Sort'; const employmentTypes = [ { value: 'Permanent', label: 'Permanent' }, { value: 'Full Time', label: 'Full-Time' }, { value: 'Part Time', label: 'Part-Time' }, { value: 'Contract', label: 'Contract' }, { value: 'Flexi-work', label: 'Flexi-Work' }, { value: 'Temporary', label: 'Temporary' }] const useStyles = makeStyles(theme => ({ root: { padding: '2px 4px', display: 'flex', alignItems: 'center', flexGrow: 1, marginTop: 20, // marginBottom:0, }, input: { marginLeft: theme.spacing(1), flex: 1, }, divider: { height: 28, margin: 4, }, dialogTitle: { marginTop: '5%', marginLeft: '8%', fontWeight: 600, }, textField: { marginLeft:'10%', marginRight:'10%', width:'100%' }, dense: { marginTop: theme.spacing(2), }, container: { display: 'flex', flexWrap: 'wrap', width: 'auto', }, formControl: { margin: theme.spacing(1), minWidth: 120, }, menu: { width: 200, }, iconButton: { padding: 10, }, button: { margin: theme.spacing(1), fontWeight:"bold", }, img: { width:'100%' , height:'100%', }, close: { padding: theme.spacing(0.5), }, carouselJobTitile: { color:'#024966', marginTop:20, fontWeight:'bold', fontSize:16, whiteSpace:'normal', textAlign:'left', overflow:'hidden', textOverflow:'ellipsis', display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', lineHeight:'18px', [theme.breakpoints.down('xs')]: { marginBottom: '20px', marginTop:'20px', }, }, jobListingBox:{ backgroundColor:'white', width:'90%', textAlign: 'start', padding:15, paddingRight:0, marginBottom:5, // boxShadow:'none',        '&:hover':{ boxShadow:'0px 1px 5px 0px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)'        } }, sectionHeading: { textAlign:"justify", marginLeft:'3%', color:'#024966e', fontWeight:'bold', marginTop:'5%', marginBottom:'3%', fontSize:30 , }, sectionArea: { height:'30vh', argin:10, marginTop:10, marginLeft:'3%', marginBottom:'4%' }, sectionCaption:{ fontSize:15, fontWeight:'medium', color:'grey', marginLeft:8, [theme.breakpoints.down('xs')]: { display:'block' }, }, tagStyle:{ padding:5, paddingLeft:8, color:'white', fontSize:11, fontWeight:'bold', zIndex:100, }, segmentArea : { marginBottom:'-5%' }, margin : { textAlign:'center', // marginTop: '37%', position: "absolute", top: '46vh', left: '28vw', backgroundColor: '#112365' , color: 'white', fontWeight: 600, // width:'45%' }, extendedIcon : { marginRight:'2%' } })); const Wrapper = styled.div` width:97% `; const Page = styled.div` width:90% `; const CarouselArrowNext = (props) => { const { className, style, onClick } = props; console.log(style) if(onClick !== null){ return ( <div className={className} style={{ display: "block",zIndex:40, marginRight:'1%',}} onClick={onClick} > <Fab className={className} size='medium' style={{display: "block",zIndex:40, marginRight:'5%',backgroundColor:'black', opacity:'0.6'}} onClick={onClick} > <KeyboardArrowRightIcon style={{color:'white',marginTop:6}}/> </Fab> </div> ); } else { return(<div></div>) } } const CarouselArrowPrev = (props) => { const classes = useStyles(); const { className, onClick, style, currentSlide} = props; if(currentSlide !==0){ return ( <div className={className} style={{ ...style, display: "block",zIndex:40,content:'none'}} onClick={onClick} > <Fab size='medium' style={{backgroundColor:'black', opacity:'0.6'}} > <KeyboardArrowLeftIcon style={{color:'white',}}/> </Fab> </div> ); } else { return(<div></div>) } } const carouselSettings = { accessibiliy: true, speed:1700, slidesToShow: 6, slidesToScroll: 3, infinite:true, dots:false, //autoplay: true, arrows:true, //autoplaySpeed:8000, draggable:true, //lazyLoad: "progressive", pauseOnHover: true, nextArrow: <CarouselArrowNext />, prevArrow: <CarouselArrowPrev />, responsive: [ { breakpoint: 1920, //lg settings: { slidesToShow: 5, slidesToScroll: 2, infinite: true, } }, { breakpoint: 1280, //md settings: { slidesToShow: 4, slidesToScroll: 2, infinite: true, } }, { breakpoint: 1000, //md settings: { slidesToShow: 3, slidesToScroll: 2, infinite: true, } }, { breakpoint: 600, //sm settings: { slidesToShow: 2, slidesToScroll: 1, initialSlide: 2 } }, { breakpoint: 480, //xs settings: { slidesToShow: 1, slidesToScroll: 1 } }] }; function compareValues(key, order='asc') { // console.log('ENTERED COMPARE VALUES METHOD with key= '+ key) return function(c, d) { var a = c; var b = d; switch(key){ case 'minimum': a = c.salary b = d.salary break; case 'maximum': a = c.salary b = d.salary break; case 'newPostingDate' : a = c.metadata; b = d.metadata; break; case 'expiryDate' : a = c.schemes; b = d.schemes; break; case 'totalNumberOfView' : a = c.metadata; b = d.metadata; break; } if(a !== null && b !== null ){ if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { return 0; } // // console.log(a[key]) const varA = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key]; const varB = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key]; let comparison = 0; if (varA > varB) { comparison = 1; } else if (varA < varB) { comparison = -1; } return ( (order === 'desc') ? (comparison * -1) : comparison ); } }; } const jobUrlDefault ='https://www.mycareersfuture.sg/job/' const defaultIcon ="https://cdn.cleverism.com/wp-content/themes/cleverism/assets/img/src/logo-placeholder.png"; const Transition = React.forwardRef(function Transition(props, ref) { return <Slide direction="up" ref={ref} {...props} />; }); function Jobs (props) { // console.log("ENTERED JOB SEARCH COMPONENT"); // let location = useLocation(); // // console.log("PRINTING FROM USELOCATION METHOD") // // console.log(location) // console.log(props) var urlParams='' if(props.match !== undefined){ // console.log(props.match.params.queryString); urlParams = props.match.params.queryString; } // console.log('PROPS FOR JOBS COMPONENT') // console.log(props) const searchLimit = 100; const token= window.localStorage.getItem('authToken'); // console.log(token) const classes=useStyles(); const queueRef = useRef([]); const [open, setOpen] = useState(false); // for snackbar const [openFilter, setOpenFilter] = useState(false); const [searchResults,setSearchResults] = useState([]); const [messageInfo, setMessageInfo] = useState(undefined); const [state, setState] = useState({ open: false, minSalary: null, keyword: "", employmentType:"", categories: "", skills:[], proceed: false, queryString:"", }); const [loadingResults, setLoadingResults] = useState(false); const [loadingHome, setLoadingHome] = useState(false); const [currentPage, setCurrentPage] = useState(1); const [postsPerPage] = useState(10); const [sorted, setSorted] = useState(false); const [popularJobs, setPopularJobs] = useState([]); const [byPass, setBypass] = useState(false); const [keyword, setKeyword] = useState(''); const tagColor = { green: '#4CB593', blue: '#42A5F5', orange: '#FF7043' } const [searchHistoryJobs, setSearchHistoryJobs] = useState([]); const [skillsJobs, setSkillsJobs] = useState([]); const [jobTitles, setJobTitles] = useState([]); const [anchorEl, setAnchorEl] = useState(null); const { enqueueSnackbar, closeSnackbar } = useSnackbar(); useEffect(()=>{ if(window.location.pathname === "/jobs" && props.searchResults === null) { // console.log('Entered props.location && props.location.pathname == "/jobs" && props.searchResults === null') setSearchResults([]); } },[props]) const action = key => ( <Fragment> <IconButton onClick={() => { closeSnackbar(key) }} size="small" style={{ color:'white' }}> <ClearIcon/> </IconButton> </Fragment> ); const handlePopoverOpen = event => { setAnchorEl(event.currentTarget); }; const handlePopoverClose = () => { setAnchorEl(null); }; const openDetails = Boolean(anchorEl); useEffect(()=>{ setLoadingHome(true); if(token !== null ){ api.dailyDigest.get() .then(res=>{ const results = res.data; if(results.response_code === 200){ // console.log("> Displaying Daily Digest Information From Job Component") // console.log(results); setSkillsJobs(results.recommended_jobs_skills); setSearchHistoryJobs(results.recommended_jobs_search); } else { } }).catch( err => { enqueueSnackbar("Unable to Retrieve Recommended Jobs", { variant: "error", action } ); }); } // console.log('*** Getting Public Daily Digest NOW') api.dailyDigest.getPublic() .then(res=>{ const results = res.data // console.log(res.data) // console.log('>> Displaying Popular Jobs From DAILY DIGEST getPublic() Method') setPopularJobs(results.recommended_jobs); setLoadingHome(false); }).catch(err => { enqueueSnackbar("Unable to Retrieve Popular Jobs", { variant: "error", action } ); }); // console.log("Printing URL PARAMS") // console.log(urlParams); // console.log("Printing Pathname from javascript") // console.log( window.location.pathname); if(window.location.pathname !== "/jobs") { if(searchResults.length !== 0) { } else if (urlParams !== undefined && urlParams !== '') { // There is const params = urlParams.split('&') const keywordString = params[0].split('=') const keywordUrl = keywordString[1]; // console.log('keyword = ' + keywordUrl) setKeyword(keywordUrl); // setState({ ...state, keyword: 'Facebook'}); setBypass(true) setState({ ...state, queryString: urlParams}); getSearchResults(urlParams); } } else { //(window.location.pathname === "/jobs") // console.log("ENTERED window.location.pathname === /jobs") setBypass(false) setSearchResults([]) } },[props.refresh]) useEffect(()=>{ // console.log("ENTERED USE EFFECT FOR SORTING") // console.log(searchResults); // //get current page lisitngs const indexOfLastPost = currentPage * postsPerPage; const indexOfFirstPost = indexOfLastPost - postsPerPage; const currentPosts = searchResults.slice(indexOfFirstPost, indexOfLastPost); },[]) function getSearchResults(queryString){ // console.log("<<<<<<<< Entered GET SEARCH RESULTS") // console.log(queryString) setLoadingResults(true); if(token !== null) { // console.log("GOT TOKEN"); //axios.get(query, {headers: {"Authorization" : "Token "+token}}) api.searchJobsAcct.get(queryString) .then(res=>{ const result = res.data.results; // console.log("RESULTS FROM GET REQUEST = ") // // console.log(result) if(result!== undefined && result.length===0){ //empty results // console.log('Entered Zero Length Method'); setSearchResults(result); enqueueSnackbar("No Listings Available!", { variant: "", action } ); props.history.push({pathname: "/jobs",}) } else if (result !==undefined && result.length!==0){ //Good to go // const sortedResults = result.sort(compareValues('skills_match', 'desc')) //DEFAULT SORTING // setSearchResults(sortedResults); const sortedResults = result.sort(compareValues('minimum', 'desc')) //DEFAULT SORTING setSearchResults(sortedResults); // setSearchHistoryJobs(result); // setSkillsJobs(result); } // submitFilter('skills_match', 'desc'); setLoadingResults(false); }) .catch(err=>{ enqueueSnackbar("Unable to get Search results", { variant: "error", action } ); setLoadingResults(false); }) } else { // console.log("NO TOKEN"); api.searchJobs.get(queryString) .then(res=>{ const result = res.data.results; // console.log("RESULTS FROM GET REQUEST = ") // // console.log(result) if(result!== undefined && result.length===0){ //empty results // console.log('Entered Zero Length Method'); setSearchResults(result); enqueueSnackbar("No Listings Available!", { variant: "", action } ); // openSnackbar(); } else if (result !==undefined && result.length!==0){ //Good to go const sortedResults = result.sort(compareValues('minimum', 'desc')) //DEFAULT SORTING setSearchResults(sortedResults); } setLoadingResults(false); }).catch(err=>{ enqueueSnackbar("No Listings Available!", { variant: "", action } ); setLoadingResults(false); }) } } const handleChange = name => event => { var value = event.target.value if(name ==='minSalary' && value < 0){ value = value * -1 } setState({ ...state, [name]: (value) }); }; const handleClickOpen = () => { setState({ ...state, open: true }); }; const handleClose = () => { setState({ ...state, open: false }); }; const handleSubmit = event => { // console.log(event.target) // setLoadingResults(true); // console.log("Entered Handle Submit") setCurrentPage(1); // console.log(token) event.preventDefault(); var tempString = "" tempString += state.keyword !== "" ? ('keyword=' + state.keyword) :''; tempString += state.employmentType !== "" ? ('&employment_type=' + state.employmentType ) :''; tempString += state.minSalary ? ('&salary=' + state.minSalary) :''; tempString += (`&limit=${searchLimit}`) // console.log("Query String = " + tempString); setKeyword(state.keyword); setState({ ...state, queryString: tempString }); getSearchResults(tempString) //const query=url+tempString // //// console.log(query); // handleRedirect(); } searchResults ? console.log('searchResults.length = ' + searchResults.length) : console.log("No Results") //get current page lisitngs const indexOfLastPost = currentPage * postsPerPage; const indexOfFirstPost = indexOfLastPost - postsPerPage; const currentPosts = searchResults.slice(indexOfFirstPost, indexOfLastPost); //Change Page const paginate = pageNumber => setCurrentPage(pageNumber); // console.log("CURRENT PAGE NUMBER = " + currentPage) const submitFilter = (filter,order) => { //const sorted = searchResults.sort(compareValues(filter,order)); setSearchResults(searchResults.sort(compareValues(filter,order))) // console.log('passed setSearchResult method') setSorted(!sorted); } // console.log("search results = ") // console.log(searchResults) useEffect(()=>{ // console.log('SEARCH RESULTS HAS BEEN MODIFIED') },[searchResults]) const handleHrefClick = list => { // console.log('***** HREF CLICK *****') // console.log(list) // console.log(list.job_uuid) // console.log(token); if(token !== null){ // console.log('TRACKING CLICK') api.searchJobsAcct.click({ uuid: list.job_uuid }) .then(response => { // console.log(response.data); if(response.data.response_code===200){ console.log("Click Stored SUCCESSFULLY "); } }) .catch(error =>{ console.log(error.response); }) } else { console.log('NOT TRACKING CLICK') } const url = jobUrlDefault + list.job_uuid window.open(url,'_blank'); } const handleViewSearchHistory = () => { setSearchResults(searchHistoryJobs); } const handleViewSkill = () => { setSearchResults(skillsJobs); } const handleViewViewAgain = () => { setSearchResults(); } const handleViewPopular = () => { setSearchResults(popularJobs); } const handleOpenFullScreenFilter = () => { setOpenFilter(true); } const handleCloseFullScreenFilter = () => { setOpenFilter(false); }; const handleSidebarSubmit = (queryString) => { // console.log("*** ENTERED HANDLE SIDEBAR SUBMIT IN JOBS COMPONENT") // console.log("!!! QueryString = " + queryString) //getCurrentUrl and append then call API // console.log(props.location) // const currentPath = props.location && props.location.pathname ? props.location.pathname.slice(15) : '' // console.log(state.queryString) var currentPath = state.queryString var currentPathArray = currentPath.split("&") currentPath = currentPathArray[0] + "&" + currentPathArray[1] // console.log("!!! Current Path = " + currentPath) const newQuery = currentPath + queryString // console.log("<<< newQuery = " + newQuery) getSearchResults(newQuery) setState({ ...state, queryString: newQuery }); } const handleRedirect =() =>{ props.history.push({pathname : `/jobs/listings/${state.queryString}`}) } //// console.log('Keyword Before Render = '); // console.log('State Before Render =') // console.log(state) // console.log(jobTitles); return ( <div> <CssBaseline/> <Grid container alignContent="flex-start" style={{background: `linear-gradient(#039be5,#43BDF8 )` , height:'40vh', padding:20, paddingTop:'5%'}}> <Grid item xs={12} > <Typography variant='h4' style={{color:'#FFFFFF', fontWeight:'lighter', paddingTop:15}}> Search </Typography> </Grid> <Grid item xs={12} container justify="center"> <Grid item xs={12} sm={10} md={8} style={{textAlign:'-webkit-center'}}> <form onSubmit={handleSubmit}> <Paper elevation={1} style={{margin:50, marginTop:40,marginBottom:20,zIndex:20,maxWidth:'90vh'}}> <Box className={classes.root} style={{margin:3, padding:0, paddingInlineStart:5}}> <InputBase className={classes.input} placeholder="Type your keyword(s)..." required value={state.keyword} onChange={handleChange('keyword')} /> <Box display={{ xs: 'block', sm: 'none' }}> <IconButton color="primary" className={classes.iconButton} onClick={handleClickOpen}> <FilterListIcon /> </IconButton> </Box> <Box display={{ xs: 'none', sm: 'block' }}> <Button color="primary" onClick={handleClickOpen} style={{marginRight:10}} size="medium"> Filters </Button> </Box> <Divider className={classes.divider} orientation="vertical" /> <IconButton className={classes.iconButton} type="submit"> <SearchIcon /> </IconButton> </Box> </Paper> <Dialog // disableBackdropClick disableEscapeKeyDown open={state.open} onClose={handleClose} fullWidth maxWidth="sm" > {/* <DialogTitle disableTypography > */} <Typography variant={"h5"} className={classes.dialogTitle}> Refine Your Search </Typography> {/* </DialogTitle> */} <DialogContent > <form className={classes.container} noValidate autoComplete="off"> <TextField id="standard-number" label="Enter Min Salary" value={state.minSalary} onChange={handleChange('minSalary')} type="number" className={classes.textField} margin="dense" InputProps={{ inputProps: { min: 0, max: 10 } }} /> <br/> <TextField select label="Employment Type" className={classes.textField} value={state.employmentType} onChange={handleChange('employmentType')} SelectProps={{ MenuProps: { className: classes.menu, }, }} margin="dense" fullWidth > {employmentTypes.map(option => ( <MenuItem key={option.value} value={option.value}> {option.label} </MenuItem> ))} </TextField> </form> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Continue </Button> </DialogActions> </Dialog> </form> </Grid> </Grid> {searchResults && searchResults.length !== 0 || byPass=== true ? <Hidden smUp> <Grid item xs={12}> <Fab variant="extended" size="small" color="white" aria-label="add" className={classes.margin} onClick={()=> handleOpenFullScreenFilter()} style={{width:'45%'}} > <SortIcon className={classes.extendedIcon} /> More Filters </Fab> </Grid> </Hidden> : "" } </Grid> <div> { loadingResults || searchResults && searchResults.length !== 0 ? <div> <Grid container> <Hidden xsDown> <Grid item xs={3} style={{height:'fit-content', position:'sticky', top:'10%', overflowY:'auto', maxHeight:'80vh'}}> <JobFilterSideBar handleSidebarSubmit={handleSidebarSubmit}/> </Grid> <Grid item xs={9}> <Router> <Redirect push to={`/jobs/listings/${state.queryString}`}/> <Route path="/jobs/listings" render={()=> ( <div> { loadingResults ? <JobListingsSkeletonLoading/> : <div> <JobListings searchResults={currentPosts} keyword={keyword} submitFilter={submitFilter} handleSidebarSubmit={handleSidebarSubmit} refresh={props.refresh}/> <Pagination currentPage={currentPage} postsPerPage={postsPerPage} totalPosts={searchResults.length} paginate={paginate}/> </div> } </div> )} /> </Router> </Grid> </Hidden> <Hidden smUp> {/* Show in xs and Hide from Sm onwards */} <Grid item xs={12}> <Router> <Redirect push to={`/jobs/listings/${state.queryString}`}/> <Route path="/jobs/listings" render={()=> ( <div> { loadingResults ? <JobListingsSkeletonLoading/> : <div> <JobListings searchResults={currentPosts} keyword={keyword} submitFilter={submitFilter} handleSidebarSubmit={handleSidebarSubmit}/> <Pagination currentPage={currentPage} postsPerPage={postsPerPage} totalPosts={searchResults.length} paginate={paginate}/> </div> } </div> )} /> </Router> <Dialog fullScreen open={openFilter} onClose={handleCloseFullScreenFilter} TransitionComponent={Transition}> <AppBar className={classes.appBar}> <Toolbar> <IconButton edge="start" color="inherit" onClick={()=> handleCloseFullScreenFilter()} aria-label="close"> <CloseIcon /> </IconButton> </Toolbar> </AppBar> <div style={{height:'fit-content', position:'fixed', top:'10%', overflowY:'auto', maxHeight:'90%'}}> <JobFilterSideBar handleSidebarSubmit={handleSidebarSubmit}/> </div> </Dialog> </Grid> </Hidden> </Grid> </div> : token && byPass==false ? //USER WITH ACCOUNT <Grid container> <Grid item container xs={12}> <Grid item xs={12} className={classes.segmentArea} > {loadingHome ? <div> <Typography variant='h5' className={classes.sectionHeading}> You Might Be Interested <span className={classes.sectionCaption}> Based on your search hisory</span> </Typography> <JobsCarouselSkeletonLoading/> </div> : searchHistoryJobs.length!=0 ? <div> <Typography variant='h5' className={classes.sectionHeading}> You Might Be Interested <span className={classes.sectionCaption}> Based on your search hisory</span> </Typography> <Grid container className={classes.sectionArea} spacing={0} justify="space-between" > <Wrapper> <Slider {...carouselSettings}> { searchHistoryJobs.map((listing) => ( <Page> <Paper className={classes.jobListingBox}> <Grid container justify='space-between'> <Grid item> <Avatar alt="List" src={ listing.company_logo ? listing.company_logo : defaultIcon } style={{width:70, height:70, boxShadow:'0px 1px 5px 0px rgba(0,0,0,0.2)',margin:'2%'}} imgProps={{style:{objectFit:'contain',border:0}}} onClick={()=> handleHrefClick(listing)} /> </Grid> <Grid item style={{ }}> { listing.skills_match < 0.3 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.orange,}}> Add Skills </Typography> : listing.skills_match < 0.7 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.green,}}> Recommended </Typography> : listing.skills_match < 1 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.blue,}}> Apply Now </Typography> :'' } </Grid> </Grid> <Grid container justify='space-between' style={{height:'15vh'}}> <Grid item xs={12} style={{paddingRight:'6%'}}> <Typography gutterBottom className={classes.carouselJobTitile} style={{}}> {listing.title} </Typography> <Typography style={{fontWeight:'light', fontSize:10}}> { listing.posted_company ? listing.posted_company : "" } </Typography> </Grid> <Grid item xs={12} style={{textAlign:'right', alignSelf:'flex-end',paddingRight:'5%'}}> <Button color='primary' style={{fontSize:12,fontWeight:'bold'}} size='small' onClick={()=>handleHrefClick(listing)} > Details </Button> </Grid> </Grid> </Paper> </Page> ))} </Slider> </Wrapper> </Grid> </div> : '' } </Grid> <Grid item xs={12} className={classes.segmentArea}> {loadingHome ? <div> <Typography variant='h5' className={classes.sectionHeading}> Suitable For You <span className={classes.sectionCaption}> Based on your skills</span> </Typography> <JobsCarouselSkeletonLoading/> </div> : skillsJobs.length !== 0 ? <div> <Typography variant='h5' className={classes.sectionHeading}> Suitable For You <span className={classes.sectionCaption}> Based on your skills</span> </Typography> <Grid container className={classes.sectionArea} spacing={0} justify="space-between" > <Wrapper> <Slider {...carouselSettings}> { skillsJobs.map((listing) => ( <Page > <Paper className={classes.jobListingBox}> <Grid container justify='space-between'> <Grid item> <Avatar alt="List" src={ listing.company_logo ? listing.company_logo : defaultIcon } style={{width:70, height:70, boxShadow:'0px 1px 5px 0px rgba(0,0,0,0.2)',margin:'2%'}} imgProps={{style:{objectFit:'contain',border:0}}} onClick={()=> handleHrefClick(listing)} /> </Grid> <Grid item style={{ }}> { listing.skills_match < 0.3 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.orange,}}> Add Skills </Typography> : listing.skills_match < 0.7 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.green,}}> Recommended </Typography> : listing.skills_match < 1 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.blue,}}> Apply Now </Typography> :'' } </Grid> </Grid> <Grid container justify='space-between' style={{height:'15vh'}}> <Grid item xs={12} style={{paddingRight:'6%'}}> <Typography gutterBottom className={classes.carouselJobTitile} style={{}}> {listing.title} </Typography> <Typography style={{fontWeight:'light', fontSize:10}}> { listing.posted_company ? listing.posted_company : "" }} </Typography> </Grid> <Grid item xs={12} style={{textAlign:'right', alignSelf:'flex-end',paddingRight:'5%'}}> <Button color='primary' style={{fontSize:12,fontWeight:'bold'}} size='small' onMouseEnter={handlePopoverOpen} onMouseLeave={handlePopoverClose} onClick={()=>handleHrefClick(listing)} > Details </Button> </Grid> </Grid> </Paper> <Popover classes={{ paper: classes.paper, }} open={open} anchorEl={anchorEl} anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} transformOrigin={{ vertical: 'top', horizontal: 'left', }} onClose={handlePopoverClose} disableRestoreFocus > <Typography>I use Popover.</Typography> </Popover> </Page> ))} </Slider> </Wrapper> </Grid> </div> : '' } </Grid> <Grid item xs={12} className={classes.segmentArea}> <Typography variant='h5' className={classes.sectionHeading}> Popular <span className={classes.sectionCaption}> Trending</span> </Typography> {loadingHome ? <JobsCarouselSkeletonLoading/> :popularJobs.length !== 0 ? <div style={{marginTop:'1%'}}> <Grid container className={classes.sectionArea} spacing={0} justify="space-between" > <Wrapper> <Slider {...carouselSettings}> { popularJobs.map((listing) => ( <Page > <Paper className={classes.jobListingBox}> <Grid container justify='space-between'> <Grid item> <Avatar alt="List" src={ listing.company_logo ? listing.company_logo : defaultIcon } style={{width:70, height:70, boxShadow:'0px 1px 5px 0px rgba(0,0,0,0.2)',margin:'2%'}} imgProps={{style:{objectFit:'contain',border:0}}} onClick={()=> handleHrefClick(listing)} /> </Grid> <Grid item style={{ }}> { listing.skills_match < 0.3 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.orange,}}> Add More Skills </Typography> : listing.skills_match < 0.7 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.green,}}> Recommended </Typography> : listing.skills_match < 1 ? <Typography className={classes.tagStyle} style={{backgroundColor:tagColor.blue,}}> Apply Now </Typography> :'' } </Grid> </Grid> <Grid container justify='space-between' style={{height:'15vh'}}> <Grid item xs={12} style={{paddingRight:'6%'}}> <Typography gutterBottom className={classes.carouselJobTitile} style={{}}> {listing.title} </Typography> <Typography style={{fontWeight:'light', fontSize:10}}> { listing.posted_company ? listing.posted_company : "" }} </Typography> </Grid> <Grid item xs={12} style={{textAlign:'right', alignSelf:'flex-end', paddingRight:'5%'}}> <Button color='primary' style={{fontSize:12,fontWeight:'bold'}} size='small' onClick={()=>handleHrefClick(listing)} > Details </Button> </Grid> </Grid> </Paper> </Page> ))} </Slider> </Wrapper> </Grid> </div> : <div style={{textAlign:'center', marginLeft:'3%',}}> <Typography style={{fontWeight:'lighter', color:''}}> <span style={{fontSize:30, color:'#4B4343',fontWeight:'light',marginRight:'1%'}}>Oops...</span> There are no results at the moment </Typography> <Typography style={{fontWeight:'bold'}}> </Typography> </div> } </Grid> {/* <div> */} <Grid item xs={12} className={classes.segmentArea}> {searchHistoryJobs.length===0 ? <div> <Typography variant='h5' className={classes.sectionHeading}> You Might Be Interested <span className={classes.sectionCaption}> Based on your search hisory</span> </Typography> <div style={{textAlign:'center', marginLeft:'3%',}}> <Typography style={{fontWeight:'lighter', color:''}}> <span style={{fontSize:30, color:'#4B4343',fontWeight:'light',marginRight:'1%'}}>Oops...</span>Seems like you're new here, Start Searching To Activate This Section! </Typography> </div> </div> : '' } </Grid> <Grid item xs={12} className={classes.segmentArea}> {skillsJobs.length===0 ? <div> <Typography variant='h5' className={classes.sectionHeading}> Suitable For You <span className={classes.sectionCaption}> Based on your skills</span> </Typography> <div style={{textAlign:'center', marginLeft:'3%',}}> <Typography style={{fontWeight:'lighter', color:''}} href='/profile/skills'> <span style={{fontSize:30, color:'#4B4343',fontWeight:'light',marginRight:'1%'}}>Oops...</span>Seems like you're new here, Start <span >Adding Skills</span> to Activate This Section! </Typography> <Typography style={{fontWeight:'bold'}}> </Typography> </div> </div> :'' } {/* </div> */} </Grid> </Grid> </Grid> : token==null && byPass==false ?//USER WITHOUT ACCOUNT <Grid container> <Grid item container xs={12} className={classes.segmentArea}> <Typography variant='h5' style={{textAlign:"justify", marginLeft:30, color:'#024966e', fontWeight:'bold', marginTop:20}}> Popular Jobs </Typography> {loadingHome ? <JobsCarouselSkeletonLoading/> : popularJobs.length !== 0 ? <Grid item xs={12}> <Grid container style={{height:'35vh', margin:10, marginTop:10}} spacing={1} justify="space-between" > <Wrapper> <Slider {...carouselSettings}> { popularJobs.map((listing) => ( <Page> <Paper style={{width:'90%',textAlign: 'start', padding:15, marginBottom:5}} elevation={0}> <Avatar alt="List" src={ listing.company_logo ? listing.company_logo : defaultIcon } style={{width:70, height:70, boxShadow:'0px 1px 5px 0px rgba(0,0,0,0.2)'}} imgProps={{style:{objectFit:'contain',border:0}}} onClick={()=> handleHrefClick(listing)} /> <Grid container justify='space-between' style={{height:'15vh'}}> <Grid item xs={12}> <Typography gutterBottom className={classes.carouselJobTitile} style={{}}> {listing.title} </Typography> <Typography style={{fontWeight:'light', fontSize:10}}> { listing.posted_company ? listing.posted_company : "" } </Typography> </Grid> <Grid item xs={12} style={{textAlign:'right', alignSelf:'flex-end',paddingRight:'5%'}}> <Button color='primary' style={{fontSize:12,fontWeight:'bold'}} size='small' onClick={()=>handleHrefClick(listing)} > Details </Button> </Grid> </Grid> </Paper> </Page> ))} </Slider> </Wrapper> </Grid> </Grid> : <Grid item xs={12} style={{textAlign:'center', marginLeft:'3%',}}> <Typography style={{fontWeight:'lighter', color:''}}> <span style={{fontSize:30, color:'#4B4343',fontWeight:'light',marginRight:'1%'}}>Oops...</span>Seems like you're new here, Start Searching To Activate This Section! </Typography> <Typography style={{fontWeight:'bold'}}> </Typography> </Grid> } <Grid item xs={12} style={{ backgroundColor:'white', marginLeft:5}}> <Grid Container style={{padding:'10%', paddingLeft:'8%'}}> <Grid item xs={12} sm style={{marginBottom:'1%'}} > <Typography variant='subtitle1' color='primary' style={{fontSize:18, fontWeight:'Bold', textAlign:'left', marginBottom:'3%'}}> Be A Member Today </Typography> <Typography gutterBottom style={{fontSize:38, fontWeight:'lighter', textAlign:'left'}}> Bookmarks <span style={{fontSize:25,textAlign:'left'}}> Save a Job Listing and View Later </span> </Typography> <Typography gutterBottom style={{fontSize:38, fontWeight:'lighter', textAlign:'center'}}> Browse Again <span style={{fontSize:25,}}> Never lose track of your favourite searches </span> </Typography> <Typography style={{fontSize:38, fontWeight:'lighter', textAlign:'left'}}> Smart Search <span style={{fontSize:25,}}> we recommend Jobs that you like </span> </Typography> <Typography> </Typography> </Grid> <Grid item xs={12} sm style={{marginTop:'4%'}}> <Typography style={{fontSize:50, fontWeight:'bold',textAlign:'right',}}> SIGN UP NOW. </Typography> </Grid> </Grid> </Grid> </Grid> </Grid> :'' } </div> </div> ) } export default Jobs; /* const processQueue = () => { if (queueRef.current.length > 0) { setMessageInfo(queueRef.current.shift()); setOpen(true); } }; const openSnackbar = () => { console.log("Entered Open SnackBar") const message = "No Listings Available!" queueRef.current.push({ message, key: new Date().getTime(), }); if (open) { // immediately begin dismissing current message // to start showing new one setOpen(false); } else { processQueue(); } }; const closeSnackbarOld = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; const handleExited = () => { processQueue(); }; */ {/* <Snackbar key={messageInfo ? messageInfo.key : undefined} anchorOrigin={{ vertical: 'bottom', horizontal: 'center', }} style={{boxShadow: "none"}} open={open} autoHideDuration={5000} onClose={closeSnackbarOld} onExited={handleExited} ContentProps={{ 'aria-describedby': 'message-id', }} message={<span style={{boxShadow:"none"}} id="message-id">{messageInfo ? messageInfo.message : undefined}</span>} action={[ <IconButton key="close" aria-label="close" color="inherit" className={classes.close} onClick={closeSnackbarOld} > <CloseIcon /> </IconButton> ]} /> */}
import { Link } from 'react-router-dom'; import { BsHeartFill } from 'react-icons/bs'; import * as S from './styles'; const Photos = ({ posts }) => { return ( <S.PhotosList> {posts.length === 0 && <span>Share you first photo.</span>} {posts.map((post) => ( <S.Photo key={post.id}> <img src={post.image} alt={post.description} /> <Link to={`/p/${post.id}`}> <div> <span> <BsHeartFill size={22} /> <p>{post.comments.length}</p> </span> <span> <BsHeartFill size={22} /> <p>{post.likesCount}</p> </span> </div> </Link> </S.Photo> ))} </S.PhotosList> ); }; export default Photos;
/* * choiceTypeApi.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * Constructs the API to call the backend for code table choice. * * @author vn70516 * @since 2.12.0 */ (function () { angular.module('productMaintenanceUiApp').factory('ChoiceTypeApi', choiceTypeApi); choiceTypeApi.$inject = ['urlBase', '$resource']; /** * Constructs the API. * * @param urlBase The base URL to contact the backend. * @param $resource Angular $resource to extend. * @returns {*} The API. */ function choiceTypeApi(urlBase, $resource) { urlBase = urlBase + '/pm/codeTable/choiceType'; return $resource( urlBase, null, { 'findAllChoiceType': { method: 'GET', url: urlBase + '/findAllChoiceType', isArray: true }, 'addNewChoiceTypes': { method: 'POST', url: urlBase + '/addNewChoiceTypes', isArray: false }, 'updateChoiceTypes': { method: 'POST', url: urlBase + '/updateChoiceTypes', isArray: false }, 'deleteChoiceTypes': { method: 'POST', url: urlBase + '/deleteChoiceTypes', isArray: false } } ); } })();
/* global gapi */ import { createSlice } from "@reduxjs/toolkit"; const authSlice = createSlice({ name: "authorization", initialState: { gapiLoaded: false, authStatus: false, user: { email: "", name: "", picture: "" } }, reducers: { gapiLoad: state => { state.gapiLoaded = true; }, login: (state, action) => { state.user = action.payload; state.authStatus = true; }, logout: state => { state.user.email = ""; state.user.name = ""; state.user.picture = ""; state.authStatus = false; } } }); const { reducer, actions } = authSlice; export default reducer; const { login, logout, gapiLoad } = actions; export { gapiLoad }; export const auth = () => { return (dispatch, getState) => { if (getState().auth.authStatus) { gapi.auth2 .getAuthInstance() .signOut() .then(() => { dispatch(logout()); }) .catch(error => { console.log("error: " + error.message); }); } else { gapi.auth2 .getAuthInstance() .signIn() .then(result => { const { Au: email, Ad: name, kL: picture } = result.Rt; dispatch(login({ email, name, picture })); }) .catch(error => { console.log("error" + error.message); }); } }; }; export const fetchAuthInfo = () => { return dispatch => { if (gapi.auth2.getAuthInstance().isSignedIn.get()) { dispatch(login()); } else { dispatch(logout()); } }; };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function loadResource(player, resourceName, callback) { player.getAssetData(`resources/${resourceName}/resource.json`, "json", (err, data) => { if (err != null) { callback(err); return; } for (const behaviorName in data.behaviors) { const behavior = data.behaviors[behaviorName]; behavior.propertiesByName = {}; for (const property of behavior.properties) behavior.propertiesByName[property.name] = property; } callback(null, data); }); } exports.loadResource = loadResource;
"use strict"; var Carro = /** @class */ (function () { function Carro(modelo, placa, cor) { this.placa = placa; this.modelo = modelo; this.cor = cor; } Carro.prototype.getModelo = function () { return this.modelo; }; return Carro; }()); var Concessionaria = /** @class */ (function () { function Concessionaria(local) { this.local = local; } Concessionaria.prototype.setListCar = function (list) { this.listCar = list; }; Concessionaria.prototype.getListCar = function () { return this.listCar; }; return Concessionaria; }()); var car1 = new Carro('Gol', 'JS-212', 'preto'); var car2 = new Carro('Palio', 'JK-226', 'azul'); var list = [car1, car2]; var c = new Concessionaria("Rio de Janeiro"); c.setListCar(list); //for(let car of c.getListCar()){ // console.log(car.getModelo()); //} c.getListCar().map(function (carro) { console.log(carro.getModelo()); });
App = (function(App){ return $.extend(App, { init: function(){ var wrapper = $('.banner-wrapper').eq(0); var textObject = $('.animate-item').eq(0); var textPara = Utils.getUrlParameter('text'); var durationPara = Utils.getUrlParameter('duration'); var animation = Utils.getUrlParameter('animation'); var loop = Utils.getUrlParameter('loop'); if(!textPara || textPara.trim().length == 0){ textPara = textObject.html(); } if(!durationPara || isNaN(durationPara)) { durationPara = 2000; } else { durationPara = parseInt(durationPara); if(durationPara <= 0) durationPara = 2000; } if(!animation){ animation = "fadeInLeftBig"; } if(!loop){ loop = false; } else if(!isNaN(loop)){ loop = parseInt(loop); if(loop == 0){ loop = false; } else{ loop = true; } } var animationObject = new Animation(textPara.trim(), durationPara, animation, loop, textObject, wrapper.width(), wrapper.height()); animationObject.start(); } }); })(window.App || {}); $(document).ready(function(){ App.init(); });
///** // * Created by Kiri-AnnEgington on 12/01/2015. // */ //$(document).ready(function(){ // // $('.radio.input').click(function(){ // $(this).parent().toggleClass('selected'); // }); //}); var $radios = $('input:radio'); $radios.change(function () { $radios.parent().removeClass('selected'); $(this).parent().addClass('selected'); }); $radios.filter(':checked').parent().addClass('selected');
var hello_module = require('./hello_module.js'); hello_module();
(function () { 'use strict'; var app = angular .module('controllersModule') .controller('AreaController', ArCtrl); ArCtrl.$inject = ['$location', '$window', '$rootScope', '$scope', '$timeout', '$modal', 'FlashService', 'modalService', 'AreaSrvc']; function ArCtrl($location, $window, $rootScope, $scope, $timeout, $modal, FlashService, modalService, AreaSrvc) { var vm = this; vm.areas = null; vm.save = save; vm.del = del; function loadAreas() { vm.areas = AreaSrvc.getAll() .then(function(result){ vm.areas = result.data; }) } loadAreas(); function save(area) { $location.path('area/edit/'+area.id); } function del(area) { /* var modalOptions = { closeButtonText: 'Нет', actionButtonText: 'Да', headerText: 'Удалить территорию оветственного' + area.responsible + '?', bodyText: 'Вы действительно хотите удалить территорию?' }; modalService.showModal({}, modalOptions) .then(function(result) { vm.name = area.responsible; delId = area.id; vm.error = false; CatSrvc.getOne(delId) .then(function(result){ if (result.name) { CatSrvc.deleteOne(delId); FlashService.Success("The category is successfully deleted"); } else { FlashService.Error("Object is not found"); } }); });*/ var delId = area.id; var isDelete = confirm("Вы действительно хотите удалить территорию?"); if (isDelete) { AreaSrvc.deleteOne(delId); //FlashService.Success("The category is successfully deleted"); } loadAreas(); } } })();
import React, {Fragment} from 'react' import {Row, Spinner} from 'reactstrap' export const GrowingSpinner = ( <Fragment> <Row className='d-flex justify-content-center m-5'> <Spinner style={{width:'2rem', height: '2rem'}}type='grow' color='primary' /> </Row> </Fragment> )
import logo from './logo.svg'; import './App.css'; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; function App() { return ( <div className="App"> <Router> <Switch> {/* Authentication */} <Route path='/auth' component={AuthRoutes} /> {/* Dashboard */} <Route path='/dashboard' component={DashboardRoutes} /> {/* Redirect Routes */} <Route path='/redirect' component={RedirectRoutes} /> {/* Landing Routes */} <Route path='/service' component={LandingRoutes} /> </Switch> </Router> </div> ); } export default App;
import React from 'react' import { Row } from 'react-bootstrap' import EditIcon from '@material-ui/icons/Edit'; import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline'; import ChatBubbleOutlineIcon from '@material-ui/icons/ChatBubbleOutline'; import LockIcon from '@material-ui/icons/Lock'; import LockOpenIcon from '@material-ui/icons/LockOpen'; import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward'; import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward'; import { makeStyles } from '@material-ui/core/styles'; import Popover from '@material-ui/core/Popover'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; const useStyles = makeStyles(theme => ({ typography: { padding: 10, }, })); const VirtualTradeItem = (props) => { const classes = useStyles(); const [anchorEl, setAnchorEl] = React.useState(null); const handleClick = event => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const open = Boolean(anchorEl); const id = open ? 'simple-popover' : undefined; const { data } = props //console.log('data',data) return( <> <div style={{width:'100%',border:'1px solid #eeeeee',padding:'15px 15px 0px',marginBottom:'10px',backgroundColor:'#fff'}}> {/* <Popover id={id} open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'center', }} transformOrigin={{ vertical: 'top', horizontal: 'center', }} > <Row> <Typography className={classes.typography}>Are you sure you want to delete the trade?</Typography> </Row> <Row style={{padding:'10px',justifyContent:'flex-end',margin:'0px'}}> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleClose} style={{color:'red'}}>Delete</Button> </Row> </Popover> */} <Row style={{display:'flex',justifyContent:'space-between'}}> <div> <p style={{color:'#212121',fontSize:'16px',padding:'2px',marginBottom:'0px'}}> <strong>{data.scrip_name}&nbsp;</strong> <span style={{ height: '13px', width: '13px', backgroundColor: data.type==="OPTIONS"?'#f7c244':data.type==="CASH"?"#69e182":data.type==="FUTURE"?"#e25241":data.type==="INVESTMENT"?"#212121":"", borderRadius: '50%', display: 'inline-block', marginTop:'5px' }} /> </p> <p style={{color:'#616161',fontSize:'14px',padding:'2px',marginBottom:'0px'}}>SBIN 29 June/11</p> </div> <div > { data.status==="profit"? <p style={{color:'#00e676',padding:'5px',backgroundColor:'#C0FEE0',borderRadius:'3px',fontSize:'12px',textAlign:'center',marginBottom:'3px'}}>Profit&nbsp;<ArrowUpwardIcon style={{fontSize:'10px'}}/></p> :<p style={{color:'#F44336',padding:'5px',backgroundColor:'#FED7D4',borderRadius:'3px',fontSize:'12px',textAlign:'center',marginBottom:'3px'}}>Loss&nbsp;<ArrowDownwardIcon style={{fontSize:'10px'}}/></p> } { <p style={{color:'#212121',fontSize:'12px'}}><LockIcon style={{fontSize:'10px',color:'red'}}/>{data.post_date}</p> } </div> </Row> <Row style={{display:'flex',justifyContent:'space-between',marginTop:'10px'}}> <div> <p style={{color:'#9e9e9e',padding:'2px',marginBottom:'0px',fontSize:'12px'}}>Order Price</p> <p style={{color:'#212121',padding:'2px',marginBottom:'0px',fontSize:'12px'}}>{data.order_price}({data.value})</p> <p style={{color:'#9e9e9e',padding:'10px 2px 2px',marginBottom:'0px',fontSize:'12px'}}>Target Price</p> <p style={{color:'#212121',padding:'2px',marginBottom:'0px',fontSize:'12px'}}>{data.target_price}({data.value})</p> </div> <div> <p style={{color:'#9e9e9e',padding:'2px',marginBottom:'0px',fontSize:'12px'}}>Quantity</p> <p style={{color:'#212121',padding:'2px',marginBottom:'0px',fontSize:'12px'}}>{data.quantity}</p> <p style={{color:'#9e9e9e',padding:'10px 2px 2px',marginBottom:'0px',fontSize:'12px'}}>Stop Loss</p> <p style={{color:'#212121',padding:'2px',marginBottom:'0px',fontSize:'12px'}}>{data.stop_loss}</p> </div> <div> <div> <p style={{color:'#9e9e9e',padding:'2px',marginBottom:'0px',fontSize:'12px',textAlign:'center'}}>Gain</p> <p style={{color:'#00e676',padding:'5px',padding:'2px',marginBottom:'0px',backgroundColor:'#C0FEE0',borderRadius:'3px',fontSize:'12px'}}>{data.gain}({data.value})</p> </div> </div> </Row> <Row style={{display:'flex',justifyContent:'center'}}> <div style={{width:'95%',height:'15px',borderBottom:'1px solid #eeeeee'}}/> </Row> </div> </> ) } export default VirtualTradeItem
import React from "react" import Farming from "../src/images/farming.jpg" import Tourists from "../src/images/tourists.jpg" import TestAutomation from "../src/images/test-automation.jpg" import BusTicketing from "../src/images/bus-ticketing.jpg" import Realty from "../src/images/realty.jpg" import Finance from "../src/images/finance-2.png" const Sdata = [ { imgsrc: Realty, title: "Silver Bullet, Alekhya Homes", content: "We came up with web based microservices architecture CRM system that has proven to increase their CSAT and has help their sales and management team to keep a track of their customers and extrapolate data that would help them drive business." }, { imgsrc: Finance, title: "Quick Financials, Proactive Tech Systems Inc, USA", content: "We built a Microservices-based SaaS application that analyzes company’s financial statements and gives a better idea of the financial health of their business. This financial picture can include information about liquidity, leverage and profitability, and will better guide the management strategy for reaching company’s goals and objectives." }, { imgsrc: BusTicketing, title: "Sikkim Online Bus Ticketing System", content:"We buit Smart Tourism Platform Based on Microservice Architecture that check and consume the services to solve the specific need of Tourists. Smart tourism platforms have made it easier for travelers to plan and manage their trips and purchased bus tickets online itself." }, { imgsrc: Farming, title: "Sikkim Organic Mission, Department of Agriculture, Sikkim", content:"We have come up with a CMS based solution for disseminating useful information to the farmers regarding the practices of organic farming." }, { imgsrc: TestAutomation, title: "End-to-End Test Automation Platform", content:"Test Automation for All. Cloud Hosted, Community Powered Test Project" }, { imgsrc: Tourists, title: "Permit Tracking System", content:"The project streamlines the process of issuing Inner Line Permits for foreign nationals visiting Sikkim. The project has several modules ranging from web to mobile." }, ] export default Sdata
'use strict'; import webpack from 'webpack'; import { webpackBaseConfig, customizer } from './webpack.config.base.babel'; import pkg from './package'; import * as fp from 'lodash/fp'; export default fp.mergeWith(customizer, { output: { filename: '[name].min.js' }, devtool: '#source-map', plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false // mangle: true by default, mangle.props should be false (default) } // Property mangling might break source code }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify(pkg.config.env.prod) } }) ] }, webpackBaseConfig);
$(document).ready(function(){ var name = utility.querystr('name'); find(name); $('#btnfind').click(function(){ var name = $('#txtfind').val(); find(name); }); $('#txtfind').keyup(function(e){ if(e.keyCode == 13) { var name = $('#txtfind').val(); find(name); } }); }); function find(name) { var endpoint = "services/dealer.php"; var args = {'_':new Date().getMilliseconds(),'name':name}; utility.service(endpoint,'GET',args,setview,null); //$('#listview').html(); } function setview(resp) { try{ $('#listview').find("tr:gt(0)").remove(); var result = ""; if(resp.result!=undefined) { $.each(resp.result,function(i,val){ result += "<tr>"; result += "<td class='col-md-4' >"+val.title+"</td>"; result += "<td class='col-md-2'>"+val.province+"</td>"; result += "<td class='col-md-2'>"+val.zone+"</td>"; result += "<td class='col-md-2'>"+val.mobile+"</td>"; result += "<td class='col-md-2'><a href='"+val.link+"'><span class='glyphicon glyphicon-download-alt'></span></a></td>"; result += "</tr>"; }); } else { var rowCount = $('#listview tr').length; if(rowCount==1){ result += "<tr>"; result += "<td class='col-md-12 text-center' >"; result += "Data Not Found."; result += "</td>"; result += "</tr>"; } } $('#listview').append(result); } catch(err) { console.error(err); } }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); // Crear, borrar actualizar, buscar var prompts = require("./node_modules/prompts"); var _02_leer_archivo_1 = require("../Clases/07-Archivos/02-leer-archivo"); var _03_escribir_archivo_1 = require("../Clases/07-archivos/03-escribir-archivo"); var id = 0; var contenidoArchivo = _02_leer_archivo_1.leerArchivo('./mejoresU.txt'); var arregloUniversidadesCargadoArchivo = JSON.parse(contenidoArchivo); var id1 = 0; arregloUniversidadesCargadoArchivo .forEach(function (valorActual) { var idActual = valorActual.Id; if (idActual > id1) { id1 = idActual; } }); id1 = id1 + 1; id = id1; var bestUniverS5 = arregloUniversidadesCargadoArchivo; function main() { mejoresUniversidades().then().catch(); } function mejoresUniversidades() { return __awaiter(this, void 0, void 0, function () { var ingresandoDatosUni, respuestas, uniIngresada, arregloParseado; return __generator(this, function (_a) { switch (_a.label) { case 0: ingresandoDatosUni = [ { type: 'text', name: 'Nombre', message: 'Ingresa el nombre de la Universidad:', }, { type: 'number', name: 'NumeroEst', message: 'Ingresa el numero de estudiantes de la universidaad: ', }, { type: 'number', name: 'AnioFund', message: 'Ingresa el año de fundacion de la universidad:', }, { type: 'text', name: 'LugarDondeBebenLosEst', message: 'Ingresa en el lugar mas cerca donde ingieren alcholo sus estudiantes:', }, { type: 'text', name: 'LugarUbi', message: 'Ingresa en que ciudad esta ubicada:', } ]; return [4 /*yield*/, prompts(ingresandoDatosUni)]; case 1: respuestas = _a.sent(); uniIngresada = { Id: id, Nombre: respuestas.Nombre, NumeroEst: respuestas.NumeroEst, AnioFund: respuestas.AnioFund, LugarDondeBebenLosEst: respuestas.LugarDondeBebenLosEst, LugarUbi: respuestas.LugarUbi }; id = id + 1; bestUniverS5.push(uniIngresada); console.log('Tus universidades son', bestUniverS5); arregloParseado = JSON.stringify(bestUniverS5); _03_escribir_archivo_1.escribirArchivo('./mejoresU.txt', arregloParseado); preguntarUsuario().then().catch(); return [2 /*return*/]; } }); }); } function preguntarUsuario() { return __awaiter(this, void 0, void 0, function () { function menuEditar() { return __awaiter(this, void 0, void 0, function () { var IdAEditar, AidEncontrado, queVaAEditar, respuestaCampo, nuevoNombre, nuevonNumeroEst, nuevoAño, nuevoLugar, nuevaCiudad, nuevoRegistroStringificado; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, prompts({ type: 'number', name: 'Id', message: 'Ingrese el Id de la U cuya informacion desea editar' })]; case 1: IdAEditar = _a.sent(); AidEncontrado = bestUniverS5.findIndex(function (valorActual) { return valorActual.Id == IdAEditar.Id; }); return [4 /*yield*/, prompts({ type: 'text', name: 'campoAEditar', message: '¿Que campo desea editar,debe escribir el campo tal cual esta en su pantalla?' })]; case 2: queVaAEditar = _a.sent(); respuestaCampo = queVaAEditar.campoAEditar; if (!(respuestaCampo == 'Nombre')) return [3 /*break*/, 4]; return [4 /*yield*/, prompts({ type: 'text', name: 'nuevoNombre', message: 'Ingrese el nombre de la U' })]; case 3: nuevoNombre = _a.sent(); bestUniverS5[AidEncontrado].Nombre = nuevoNombre.nuevoNombre; return [3 /*break*/, 13]; case 4: if (!(respuestaCampo == 'NumeroEst')) return [3 /*break*/, 6]; return [4 /*yield*/, prompts({ type: 'number', name: 'nuevosEs', message: 'Ingrese el numero de estudiantes real' })]; case 5: nuevonNumeroEst = _a.sent(); bestUniverS5[AidEncontrado].NumeroEst = nuevonNumeroEst.nuevosEs; return [3 /*break*/, 13]; case 6: if (!(respuestaCampo == 'AnioFund')) return [3 /*break*/, 8]; return [4 /*yield*/, prompts({ type: 'number', name: 'añoFundacionNue', message: 'Ingrese el nuevo año de fundacion' })]; case 7: nuevoAño = _a.sent(); bestUniverS5[AidEncontrado].AnioFund = nuevoAño.añoFundacionNue; return [3 /*break*/, 13]; case 8: if (!(respuestaCampo == 'LugarDondeBebenLosEst')) return [3 /*break*/, 10]; return [4 /*yield*/, prompts({ type: 'text', name: 'nuevoBar', message: 'Ingrese el nuevo bar a donde van a beber' })]; case 9: nuevoLugar = _a.sent(); bestUniverS5[AidEncontrado].LugarDondeBebenLosEst = nuevoLugar.nuevoBar; return [3 /*break*/, 13]; case 10: if (!(respuestaCampo == 'LugarUbi')) return [3 /*break*/, 12]; return [4 /*yield*/, prompts({ type: 'text', name: 'City', message: 'Ingrese la nueva ciudad' })]; case 11: nuevaCiudad = _a.sent(); bestUniverS5[AidEncontrado].LugarUbi = nuevaCiudad.City; return [3 /*break*/, 13]; case 12: console.log('Ingrese un campo valido'); _a.label = 13; case 13: ; console.log('El registro de tus mejores universidades:', bestUniverS5); nuevoRegistroStringificado = JSON.stringify(bestUniverS5); _03_escribir_archivo_1.escribirArchivo('./mejoresU.txt', nuevoRegistroStringificado); preguntarUsuario().then().catch(); return [2 /*return*/, bestUniverS5]; } }); }); } function eliminarRegistro() { return __awaiter(this, void 0, void 0, function () { var AidAEliminar, AidEncontrado, registroBorrado; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, prompts({ type: 'number', name: 'Id', message: 'Ingrese el id de la Universidad a eliminar' })]; case 1: AidAEliminar = _a.sent(); AidEncontrado = bestUniverS5.findIndex(function (valorActual) { return valorActual.Id == AidAEliminar.Id; }); bestUniverS5.splice(AidEncontrado, 1); console.log('La mejores son:', bestUniverS5); registroBorrado = JSON.stringify(bestUniverS5); _03_escribir_archivo_1.escribirArchivo('./mejoresU.txt', registroBorrado); preguntarUsuario().then().catch(); return [2 /*return*/, bestUniverS5]; } }); }); } var decision; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, prompts({ type: 'number', name: 'siono', message: 'PRESIONA\n0-->Agregar mas universidades\n1-->Editar tus universidades\n2--->Eliminar una universidad\n3-->Salir' })]; case 1: decision = _a.sent(); if (decision.siono == 0) { mejoresUniversidades().then().catch(); } else if (decision.siono == 1) { menuEditar().then().catch(); } else if (decision.siono == 2) { eliminarRegistro().then().catch(); } else if (decision.siono == 3) { console.log('ADIOOOOOOS PRRRO'); } ; return [2 /*return*/]; } }); }); } main();
import React from 'react'; import PropTypes from 'prop-types'; import { View, FlatList, Image, StyleSheet, TouchableOpacity, } from 'react-native'; import FastImage from 'react-native-fast-image'; import {useDispatch, useSelector} from 'react-redux'; import {addFavoriteData, removeFavoriteData} from '../../redux/core/actions'; // Consts and Libs import {AppStyles, AppSizes, Colors} from '../../theme'; import {APIConfig} from '../../constants'; // component import {Icon} from '../../components'; /* Component ==================================== */ function FavoriteBtn(props) { const dispatch = useDispatch(); const favoriteList = useSelector((state) => state.core.favorite); const _favStatus = (item) => { if (favoriteList.filter((e) => e.id === item.id).length > 0) { return true; } return false; } const _FavPress = (item) => { if (_favStatus(item)) { dispatch(removeFavoriteData(item)); return; } dispatch(addFavoriteData(item)); }; return ( <> <Icon name="favorite" onPress={() => _FavPress(props.onPress())} size={20} color={_favStatus(props.itemData) ? Colors.red : Colors.disable} /> </> ); } /* Styles ==================================== */ const styles = StyleSheet.create({}); /* Component Props ==================================== */ FavoriteBtn.propTypes = {}; FavoriteBtn.defaultProps = {}; /* Export Component ==================================== */ export default FavoriteBtn;
import React, { Component } from 'react'; import Home from './home'; export class Image extends Component { render() { var imagearray = [ { name: 'heart', src: require('../../heart.png'), class: 'icon mr-2 rounded' }, { name: 'heartline', src: require('../../heartline.png'), class: 'icon mr-2 rounded' }, { name: 'heartlinewhite', src: require('../../heartline-white.png'), class: 'icon mr-2 rounded' }, { name: 'dottedline', src: require('../../dottedline.png'), class: 'icon mr-5 rounded' }, { name: 'signupicon1', src: require('../../signup-icon1.png'), class: 'signup-icon mr-5 rounded' }, { name: 'signupicon2', src: require('../../signup-icon2.png'), class: 'signup-icon mr-5 rounded' }, { name: 'signupicon3', src: require('../../signup-icon3.png'), class: 'signup-icon mr-5 rounded' }, { name: 'testimonial1', src: require('../../testimonial1.jpg'), class: 'card-img-top' }, { name: 'testimonial2', src: require('../../testimonial2.jpg'), class: 'card-img-top' }, { name: 'testimonial3', src: require('../../testimonial3.jpg'), class: 'card-img-top' } ]; /*if(this.props.name === imagearray.name) return (<img src={imagearray.src} alt="" className={imagearray.class} data-holder-rendered="true" />);*/ return null; } } export default Image;
export { default } from './Cemetery';
module.exports = { serialport: { port_name: '', baud_rate: 9600, data_bits: 8, parity: 'none', stop_bits: 1 } }
/*eslint no-console: [0]*/ 'use strict'; var fs = require('fs'), path = require('path'), blurrd = require('../blurrd'); var inputFile = path.join(__dirname, '..', 'examples', 'lazyload.html'); var options = { transformer: 'lazyload' }; fs.readFile(inputFile, 'utf8', function(err, data) { if(err) { console.log(err); } blurrd(data, options).then(function(result) { fs.writeFile(inputFile.replace('examples', 'build'), result); }, function(err) { console.log(err.stack); }); });
let wageba1 = document.getElementById("wageba1"); let countMe = 0, countVs = 0; const arr = ["guli6","guli7","guli8","guli9","guli10","guliJ","guliQ","guliK","guliA"]; const arr1 = ["aguri6","aguri7","aguri8","aguri9","aguri10","aguriJ","aguriQ","aguriK","aguriA"]; const arr2 = ["yvavi6","yvavi7","yvavi8","yvavi9","yvavi10","yvaviJ","yvaviQ","yvaviK","yvaviA"]; const arr3 = ["jvari6","jvari7","jvari8","jvari9","jvari10","jvariJ","jvariQ","jvariK","jvariA"]; //gulebi document.querySelector("#guli10").addEventListener("click", ()=>{ document.getElementById("guli10").style.opacity == "0.5" ? document.getElementById("guli10").style.opacity = "1": document.getElementById("guli10").style.opacity = "0.5" ; }) document.querySelector("#guli9").addEventListener("click", ()=>{ document.getElementById("guli9").style.opacity == "0.5" ? document.getElementById("guli9").style.opacity = "1": document.getElementById("guli9").style.opacity = "0.5" ; }) document.querySelector("#guli8").addEventListener("click", ()=>{ document.getElementById("guli8").style.opacity == "0.5" ? document.getElementById("guli8").style.opacity = "1": document.getElementById("guli8").style.opacity = "0.5" ; }) document.querySelector("#guli7").addEventListener("click", ()=>{ document.getElementById("guli7").style.opacity == "0.5" ? document.getElementById("guli7").style.opacity = "1": document.getElementById("guli7").style.opacity = "0.5" ; }) document.querySelector("#guli6").addEventListener("click", ()=>{ document.getElementById("guli6").style.opacity == "0.5" ? document.getElementById("guli6").style.opacity = "1": document.getElementById("guli6").style.opacity = "0.5" ; }) document.querySelector("#guliJ").addEventListener("click", ()=>{ document.getElementById("guliJ").style.opacity == "0.5" ? document.getElementById("guliJ").style.opacity = "1": document.getElementById("guliJ").style.opacity = "0.5" ; }) document.querySelector("#guliQ").addEventListener("click", ()=>{ document.getElementById("guliQ").style.opacity == "0.5" ? document.getElementById("guliQ").style.opacity = "1": document.getElementById("guliQ").style.opacity = "0.5" ; }) document.querySelector("#guliK").addEventListener("click", ()=>{ document.getElementById("guliK").style.opacity == "0.5" ? document.getElementById("guliK").style.opacity = "1": document.getElementById("guliK").style.opacity = "0.5" ; }) document.querySelector("#guliA").addEventListener("click", ()=>{ document.getElementById("guliA").style.opacity == "0.5" ? document.getElementById("guliA").style.opacity = "1": document.getElementById("guliA").style.opacity = "0.5" ; })//gulebi //agurebi document.querySelector("#aguri6").addEventListener("click", ()=>{ document.getElementById("aguri6").style.opacity == "0.5" ? document.getElementById("aguri6").style.opacity = "1": document.getElementById("aguri6").style.opacity = "0.5" ; }) document.querySelector("#aguri7").addEventListener("click", ()=>{ document.getElementById("aguri7").style.opacity == "0.5" ? document.getElementById("aguri7").style.opacity = "1": document.getElementById("aguri7").style.opacity = "0.5" ; }) document.querySelector("#aguri8").addEventListener("click", ()=>{ document.getElementById("aguri8").style.opacity == "0.5" ? document.getElementById("aguri8").style.opacity = "1": document.getElementById("aguri8").style.opacity = "0.5" ; }) document.querySelector("#aguri9").addEventListener("click", ()=>{ document.getElementById("aguri9").style.opacity == "0.5" ? document.getElementById("aguri9").style.opacity = "1": document.getElementById("aguri9").style.opacity = "0.5" ; }) document.querySelector("#aguri10").addEventListener("click", ()=>{ document.getElementById("aguri10").style.opacity == "0.5" ? document.getElementById("aguri10").style.opacity = "1": document.getElementById("aguri10").style.opacity = "0.5" ; }) document.querySelector("#aguriJ").addEventListener("click", ()=>{ document.getElementById("aguriJ").style.opacity == "0.5" ? document.getElementById("aguriJ").style.opacity = "1": document.getElementById("aguriJ").style.opacity = "0.5" ; }) document.querySelector("#aguriQ").addEventListener("click", ()=>{ document.getElementById("aguriQ").style.opacity == "0.5" ? document.getElementById("aguriQ").style.opacity = "1": document.getElementById("aguriQ").style.opacity = "0.5" ; }) document.querySelector("#aguriK").addEventListener("click", ()=>{ document.getElementById("aguriK").style.opacity == "0.5" ? document.getElementById("aguriK").style.opacity = "1": document.getElementById("aguriK").style.opacity = "0.5" ; }) document.querySelector("#aguriA").addEventListener("click", ()=>{ document.getElementById("aguriA").style.opacity == "0.5" ? document.getElementById("aguriA").style.opacity = "1": document.getElementById("aguriA").style.opacity = "0.5" ; })//agurebi //yvavebi document.querySelector("#yvavi6").addEventListener("click", ()=>{ document.getElementById("yvavi6").style.opacity == "0.5" ? document.getElementById("yvavi6").style.opacity = "1": document.getElementById("yvavi6").style.opacity = "0.5" ; }) document.querySelector("#yvavi7").addEventListener("click", ()=>{ document.getElementById("yvavi7").style.opacity == "0.5" ? document.getElementById("yvavi7").style.opacity = "1": document.getElementById("yvavi7").style.opacity = "0.5" ; }) document.querySelector("#yvavi8").addEventListener("click", ()=>{ document.getElementById("yvavi8").style.opacity == "0.5" ? document.getElementById("yvavi8").style.opacity = "1": document.getElementById("yvavi8").style.opacity = "0.5" ; }) document.querySelector("#yvavi9").addEventListener("click", ()=>{ document.getElementById("yvavi9").style.opacity == "0.5" ? document.getElementById("yvavi9").style.opacity = "1": document.getElementById("yvavi9").style.opacity = "0.5" ; }) document.querySelector("#yvavi10").addEventListener("click", ()=>{ document.getElementById("yvavi10").style.opacity == "0.5" ? document.getElementById("yvavi10").style.opacity = "1": document.getElementById("yvavi10").style.opacity = "0.5" ; }) document.querySelector("#yvaviJ").addEventListener("click", ()=>{ document.getElementById("yvaviJ").style.opacity == "0.5" ? document.getElementById("yvaviJ").style.opacity = "1": document.getElementById("yvaviJ").style.opacity = "0.5" ; }) document.querySelector("#yvaviQ").addEventListener("click", ()=>{ document.getElementById("yvaviQ").style.opacity == "0.5" ? document.getElementById("yvaviQ").style.opacity = "1": document.getElementById("yvaviQ").style.opacity = "0.5" ; }) document.querySelector("#yvaviK").addEventListener("click", ()=>{ document.getElementById("yvaviK").style.opacity == "0.5" ? document.getElementById("yvaviK").style.opacity = "1": document.getElementById("yvaviK").style.opacity = "0.5" ; }) document.querySelector("#yvaviA").addEventListener("click", ()=>{ document.getElementById("yvaviA").style.opacity == "0.5" ? document.getElementById("yvaviA").style.opacity = "1": document.getElementById("yvaviA").style.opacity = "0.5" ; }) //yvavebi //jvrebi document.querySelector("#jvari6").addEventListener("click", ()=>{ document.getElementById("jvari6").style.opacity == "0.5" ? document.getElementById("jvari6").style.opacity = "1": document.getElementById("jvari6").style.opacity = "0.5" ; }) document.querySelector("#jvari7").addEventListener("click", ()=>{ document.getElementById("jvari7").style.opacity == "0.5" ? document.getElementById("jvari7").style.opacity = "1": document.getElementById("jvari7").style.opacity = "0.5" ; }) document.querySelector("#jvari8").addEventListener("click", ()=>{ document.getElementById("jvari8").style.opacity == "0.5" ? document.getElementById("jvari8").style.opacity = "1": document.getElementById("jvari8").style.opacity = "0.5" ; }) document.querySelector("#jvari9").addEventListener("click", ()=>{ document.getElementById("jvari9").style.opacity == "0.5" ? document.getElementById("jvari9").style.opacity = "1": document.getElementById("jvari9").style.opacity = "0.5" ; }) document.querySelector("#jvari10").addEventListener("click", ()=>{ document.getElementById("jvari10").style.opacity == "0.5" ? document.getElementById("jvari10").style.opacity = "1": document.getElementById("jvari10").style.opacity = "0.5" ; }) document.querySelector("#jvariJ").addEventListener("click", ()=>{ document.getElementById("jvariJ").style.opacity == "0.5" ? document.getElementById("jvariJ").style.opacity = "1": document.getElementById("jvariJ").style.opacity = "0.5" ; }) document.querySelector("#jvariQ").addEventListener("click", ()=>{ document.getElementById("jvariQ").style.opacity == "0.5" ? document.getElementById("jvariQ").style.opacity = "1": document.getElementById("jvariQ").style.opacity = "0.5" ; }) document.querySelector("#jvariK").addEventListener("click", ()=>{ document.getElementById("jvariK").style.opacity == "0.5" ? document.getElementById("jvariK").style.opacity = "1": document.getElementById("jvariK").style.opacity = "0.5" ; }) document.querySelector("#jvariA").addEventListener("click", ()=>{ document.getElementById("jvariA").style.opacity == "0.5" ? document.getElementById("jvariA").style.opacity = "1": document.getElementById("jvariA").style.opacity = "0.5" ; }) //jvrebi //agoritmi document.querySelector("#wageba2").addEventListener("click", ()=>{ for (let i=0; i<arr.length; i++){ //gulebi if (document.getElementById(arr[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countMe += 0; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countMe += 10; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countMe += 2; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countMe += 3; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countMe += 4; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countMe += 11; } //agurebi if (document.getElementById(arr1[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countMe += 0; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countMe += 10; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countMe += 2; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countMe += 3; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countMe += 4; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countMe += 11; } //yvavebi if (document.getElementById(arr2[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countMe += 0; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countMe += 10; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countMe += 2; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countMe += 3; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countMe += 4; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countMe += 11; } //jvrebi if (document.getElementById(arr3[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countMe += 0; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countMe += 10; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countMe += 2; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countMe += 3; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countMe += 4; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countMe += 11; } } document.getElementById("mequla").value = countMe; }) document.querySelector("#wageba1").addEventListener("click", ()=>{ for (let i=0; i<arr.length; i++){ //gulebi if (document.getElementById(arr[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countVs += 0; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countVs += 10; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countVs += 2; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countVs += 3; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countVs += 4; } if (document.getElementById(arr[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr[i]).style.opacity=0; document.getElementById(arr[i]).style.visibility = "hidden"; countVs += 11; } //agurebi if (document.getElementById(arr1[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countVs += 0; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countVs += 10; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countVs += 2; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countVs += 3; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countVs += 4; } if (document.getElementById(arr1[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr1[i]).style.opacity=0; document.getElementById(arr1[i]).style.visibility = "hidden"; countVs += 11; } //yvavebi if (document.getElementById(arr2[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countVs += 0; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countVs += 10; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countVs += 2; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countVs += 3; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countVs += 4; } if (document.getElementById(arr2[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr2[i]).style.opacity=0; document.getElementById(arr2[i]).style.visibility = "hidden"; countVs += 11; } //jvrebi if (document.getElementById(arr3[i]).style.opacity == 0.5 && i<4){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countVs += 0; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==4){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countVs += 10; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==5){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countVs += 2; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==6){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countVs += 3; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==7){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countVs += 4; } if (document.getElementById(arr3[i]).style.opacity == 0.5 && i==8){ document.getElementById(arr3[i]).style.opacity=0; document.getElementById(arr3[i]).style.visibility = "hidden"; countVs += 11; } } document.getElementById("vsqula").value = countVs; })
/** * Created by liyangfan on 17-8-16. */ import React from 'react' import {render} from 'react-dom' import BasicExample from './modules/A' render(( <BasicExample/> ), document.getElementById('app'))
var ok = "resources/ok.png"; var bad = "resources/bad.png"; function update() { document.Form1.action = "/update"; } function add() { document.Form1.action = "/add"; } function setImg(id, isOk) { if (isOk) { document.getElementById(id).src = ok; return true; } else { var elementById = document.getElementById(id); elementById.src = bad; return false; } } function checkName(name) { var re = /^[a-zA-Z~]{1,30}$/;//todo remove '~' after testing return re.test(name); } function checkFirstName() { var s = document.getElementById("firstname").value; var test = checkName(s); return setImg("firstnameImg", test); } function checkLastName() { var s = document.getElementById("lastname").value; var test = checkName(s); return setImg("lastnameImg", test); } function checkTelephone() { var re = /^\d{6,15}$/; var s = document.getElementById("telephone").value; var test = re.test(s); return setImg("telephoneImg", test); } function checkEmail() { var re = /^[\w\+]+(\.\w-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$/; var s = document.getElementById("email").value; var test = re.test(s); return setImg("emailImg", test); } function checkFormOk() { if (checkFirstName() && checkLastName() && checkEmail() && checkTelephone()) { return true; } document.getElementById('message').innerHTML = "Please, fill all fields as required"; return false; }
var gulp = require('gulp'), sass = require('gulp-ruby-sass'), autoprefixer = require('gulp-autoprefixer'), minifycss = require('gulp-minify-css'), rename = require('gulp-rename'), replace = require('gulp-replace'), livereload = require('gulp-livereload'), lr = require('tiny-lr'), server = lr(); function replaceWithAssetURL( match, imgurl){ return 'background:url({{ "'+ imgurl + '" | asset_url }})'; } gulp.task('styles', function() { return sass('assets/_scss/') .on('error', function (err) { console.error('Error!', err.message); }) .pipe(autoprefixer()) .pipe(minifycss()) .pipe(rename({extname: '.css.liquid'})) .pipe(replace(/background:url\((.*?)\)/g, replaceWithAssetURL)) .pipe(gulp.dest('assets/')); }); gulp.task('watch', function() { // Listen on port 35729 server.listen(35729, function (err) { if (err) { return console.log(err) }; // Watch .scss files gulp.watch(['assets/_scss/*.scss','assets/_scss/**/*.scss'], ['styles']); }); });
import React, { useState } from "react"; export const AddTodo = ({ onAddTodoClicked }) => { const [value, setValue] = useState(""); const onFormSubmit = e => { e.preventDefault(); onAddTodoClicked(value); setValue(""); }; return ( <form onSubmit={onFormSubmit}> <input type="text" value={value} onChange={e => setValue(e.target.value)} placeholder="My todo title" /> </form> ); };
/* * Dashboard component. It is the initial page. * Props: * - filteredContacts: contacts state from store filtered with function in selectors/contacts.js * - contacts: unfiltered contacts state from store. Needed to display letters for filter * - filter: filter state to add active class to filter letters * - loading: loading state to decide whether display <Loading /> or contact list * - dispatchTextFilter: send filter text to store via setTextFilter action creator */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import filterContacts from '../selectors/contacts'; import ContactCard from './ContactCard'; import Loading from './Loading'; import setTextFilter from '../actions/filters'; export class Dashboard extends Component { static propTypes = { filteredContacts: PropTypes.arrayOf(PropTypes.object), contacts: PropTypes.arrayOf(PropTypes.object), filter: PropTypes.string, loading: PropTypes.bool.isRequired, dispatchTextFilter: PropTypes.func.isRequired, } static defaultProps = { filteredContacts: [], contacts: [], filter: '', } // Method for getting individual first letters from last names for filtering getFirstLettersFromLastNames = () => { const letters = this.props.contacts .map(contact => contact.lastName.charAt(0)) .sort(); return [...new Set(letters)]; } render() { const { filteredContacts, dispatchTextFilter, filter, } = this.props; return ( <div className="dashboard"> <h1 className="text-center">Contacts</h1> <div className="text-center pt-3"> { this.props.contacts.length > 0 && this.getFirstLettersFromLastNames().map(letter => ( <button type="button" className={`text-uppercase btn--filter mx-2 ${filter === letter ? 'active' : ''}`} id={`filter-${letter}`} key={letter} onClick={() => dispatchTextFilter(letter)} > { letter } </button> )) } </div> {/* Display 'Clear filter' button if contacts are filtered */} { filter.length > 0 && ( <div className="text-center py-3"> <button type="button" className="btn btn--empty btn--red-empty" onClick={() => dispatchTextFilter('')} > Clear filter </button> </div> ) } {/* If contactsAreLoading state is true display <Loading /> else display contacts */} <div className="row mt-5"> { this.props.loading ? <Loading /> : filteredContacts.map(contact => <ContactCard data={contact} key={contact.id} />) } </div> </div> ); } } /* * Get states from the Redux store to add as props to the component */ const mapStateToProps = state => ({ filteredContacts: filterContacts(state.contacts, state.filters.text), contacts: state.contacts, filter: state.filters.text, loading: state.contactsAreLoading, }); /* * Create dispatchTextFilter function to link setTextFilter action creator with the component via props */ const mapDispatchToProps = dispatch => ({ dispatchTextFilter: text => dispatch(setTextFilter(text)), }); export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
import React, { useState, useEffect, useRef } from "react"; import Container from "react-bootstrap/Container"; import Form from "react-bootstrap/Form"; import Alert from "react-bootstrap/Alert"; import Swal from "sweetalert2"; import { withRouter } from "react-router"; import { useParams } from "react-router"; import { campoRequerido, rangoValor } from "../helpers/validaciones"; const EditarProducto = ({ consultarApi, history, match }) => { const { id } = useParams(); console.log("match.params.id", match.params.id); const URL = process.env.REACT_APP_API_URL; console.log(URL); const [producto, setProducto] = useState({}); const [categoria, setCategoria] = useState(""); const nombreProductoRef = useRef(""); const precioProductoRef = useRef(0); useEffect(() => { consultarProducto(); }, []); const consultarProducto = async () => { try { const respuesta = await fetch(URL + "/" + id); console.log(respuesta); if (respuesta.status === 200) { const resultado = await respuesta.json(); setProducto(resultado); console.log(producto); } } catch (error) { console.log(error); } }; const [error, setError] = useState(false); const cambiarCategoria = (e) => { setCategoria(e.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); const categoriaSeleccionada = categoria === "" ? producto.categoria : categoria; if ( campoRequerido(nombreProductoRef.current.value) && rangoValor(parseInt(precioProductoRef.current.value)) && campoRequerido(categoriaSeleccionada) ) { const productoEditado = { nombreProducto: nombreProductoRef.current.value, precioProducto: precioProductoRef.current.value, categoria: categoriaSeleccionada, }; console.log(productoEditado); try { const respuesta = await fetch(URL + "/" + id, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(productoEditado), }); console.log(respuesta); if (respuesta.status === 200) { Swal.fire( "Producto editado ", "Los datos del producto fueron modificados", "success" ); history.push("/productos"); consultarApi(); } } catch (error) { console.log(error); } } else { console.log("ERROR NO enviar datos"); } }; return ( <div> <Container className="my-4"> <Form onSubmit={handleSubmit}> <h1 className="my-3 text-center">Editar un producto</h1> <Form.Group> {error === true ? ( <Alert variant="danger">Todos los campos son obligatorios </Alert> ) : null} <Form.Label>Nombre</Form.Label> <Form.Control type="text" placeholder="Submarino" defaultValue={producto.nombreProducto} ref={nombreProductoRef} ></Form.Control> </Form.Group> <Form.Group> <Form.Label>Precio </Form.Label> <Form.Control type="number" placeholder="$25.60" defaultValue={producto.precioProducto} ref={precioProductoRef} ></Form.Control> </Form.Group> <div className="text-center my-4"> <h3>Categoría</h3> <Form.Check type="radio" label="Bebida caliente " name="categoria" inline onChange={cambiarCategoria} value="bebida-caliente" defaultChecked={ producto.categoria && producto.categoria === "bebida-caliente" } ></Form.Check> <Form.Check type="radio" label="Bebida fria " name="categoria" value="bebida-fria" onChange={cambiarCategoria} inline defaultChecked={ producto.categoria && producto.categoria === "bebida-fria" } ></Form.Check> <Form.Check type="radio" label="Sanwich" inline value="sandwich" onChange={cambiarCategoria} name="categoria" defaultChecked={ producto.categoria && producto.categoria === "sandwich" } ></Form.Check> <Form.Check type="radio" label="Dulce" inline value="dulce" onChange={cambiarCategoria} name="categoria" defaultChecked={ producto.categoria && producto.categoria === "dulce" } ></Form.Check> <Form.Check type="radio" label="Salado" inline value="salado" onChange={(e) => setCategoria(e.target.value)} name="categoria" defaultChecked={ producto.categoria && producto.categoria === "salado" } ></Form.Check> </div> <button type="submit " className="w-100 "> {" "} Editar producto </button> </Form> </Container> </div> ); }; export default withRouter(EditarProducto);
(function() { 'use strict'; angular .module('seHablaEspanol') .directive('acmeKeyboard', acmeKeyboard); /** @ngInject */ function acmeKeyboard() { var directive = { restrict: 'E', templateUrl: 'app/components/keyboard/keyboard.html', scope: { imgSrc: '@', keyTitle: '@', keyForeginTitle: '@' }, controller: KeyboardController, controllerAs: 'vm', bindToController: true }; return directive; /** @ngInject */ function KeyboardController() { var vm = this; // "vm.creationDate" is available by directive option "bindToController: true" console.log(vm.imgSrc, vm.keyTitle, vm.keyForeginTitle); } } })();
(function () { "use strict"; angular.module('public') .component('signUpForm', { templateUrl: 'src/public/sign-up/signUpForm.html', controller: 'SignUpFormController', controllerAs: 'ctrl' }); })();
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import Main from '../template/Main'; import api from '../../config/configApi'; import './lancamentoCad.css'; const CreateLancamento = () => { const [lancamento, setLancamento] = useState({ nome: '', valor: '', tipo: '', situacao: '', dataPagamento: '' }); const [status, setStatus] = useState({ type: '', msg: '' }); const valorInput = e => setLancamento({ ...lancamento, [e.target.name]: e.target.value }); const [valorLancTarget, setValorLancTarget] = useState(''); const valorLancamento = async e => { let valorLancamentoInput = e.target.value; valorLancamentoInput = valorLancamentoInput.replace(/\D/g, ""); valorLancamentoInput = valorLancamentoInput.replace(/(\d)(\d{2})$/, "$1,$2"); valorLancamentoInput = valorLancamentoInput.replace(/(?=(\d{3})+(\D))\B/g, "."); setValorLancTarget(valorLancamentoInput); let valorSalvar = await valorLancamentoInput.replace(".", ""); valorSalvar = await valorSalvar.replace(",", "."); setLancamento({ ...lancamento, valor: valorSalvar }); } const cadLancamento = async e => { e.preventDefault(); const headers = { 'Content-Type': 'application/json' } await api.post("/cadastrar", lancamento, { headers }) .then((response) => { setStatus({ type: 'success', msg: response.data.msg }); }).catch((err) => { if (err.response) { setStatus({ type: 'error', msg: err.response.data.msg }); } else { setStatus({ type: 'error', msg: 'Erro: Conexão com o servidor foi perdida!' }); } }) } return ( <Main icon="file-text" title="Cadastrar um lançamento" subtitle="Tela de cadastro de lançamentos."> <div className="alert"> {status.type === 'error' ? <span className="spanDanger">{status.msg}</span> : ""} {status.type === 'success' ? <span className="spanSuccess">{status.msg}</span> : ""} </div> <div className="conteudoTitulo"> <h1>Formulário de Cadastro</h1> <Link to="/finanças"> <button className="btn btn-outline-secondary"> <i className="fa fa-arrow-left"></i> Voltar </button> </Link> </div> <form onSubmit={cadLancamento}> <div className="row"> <div className="col-12 col-md-6"> <div className="form-group"> <label>Nome</label> <input type="text" className="form-control" name="nome" placeholder="Conta de Água" onChange={valorInput} /> </div> </div> <div className="col-12 col-md-6"> <div className="form-group"> <label>Valor</label> <input type="text" className="form-control" name="valor" placeholder="100,00" value={valorLancTarget} onChange={valorLancamento} /> </div> </div> <div className="col-12 col-md-6"> <div className="form-group"> <label>Tipo</label> <select className="form-control" name="tipo" onChange={valorInput}> <option value="">Selecione</option> <option value="1">Pagamento</option> <option value="2">Recebido</option> </select> </div> </div> <div className="col-12 col-md-6"> <div className="form-group"> <label>Situação</label> <select className="form-control" name="situacao" onChange={valorInput}> <option value="">Selecione</option> <option value="1">Pago</option> <option value="2">Pendente</option> <option value="3">Recebido</option> </select> </div> </div> <div className="form-group"> <label>Data</label> <input type="date" className="form-control" name="dataPagamento" onChange={valorInput} /> </div> </div> <hr /> <div className="row"> <div className="col-12 d-flex justify-content-end"> <button type="submit" className="btn btn-outline-primary"> <i className="fa fa-floppy-o"></i> Cadastrar </button> </div> </div> </form> </Main> ) } export default CreateLancamento;
import React from 'react'; import styled, {keyframes} from 'styled-components'; const spin = keyframes` 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } `; const StyledSpinner = styled.div` display: inline-block; width: 80px; height: 80px; :after { content: " "; display: block; width: 64px; height: 64px; margin: 8px; border-radius: 50%; border: 6px solid #fff; border-color: blue transparent blue transparent; animation: 1.2s ${spin} linear infinite; } `; const Spinner = () => { return <StyledSpinner /> } export default Spinner;
'use strict'; class StoreContact { get rules() { return { contact_name: 'required', email: 'email|unique:contacts', pseudo_id: 'required|unique:contacts' }; } } module.exports = StoreContact;
function setMsg(ajaxMsg) { $("#ajax-msg").replaceWith( '<div id="ajax-msg">' + ajaxMsg +'</div>'); } var wikipediaHTMLResult = function(data) { var ref = data.parse.text["*"].replace(/<br \/>/g, ', ') var readData = $('<div>' + ref + '</div>'); // handle redirects var redirect = readData.find('li:contains("REDIRECT") a').text(); if(redirect != '') { callWikipediaAPI(redirect); return; } var callsign = $("#callsign").val(); var city = '', branding = ''; var format = '', webcast = '', website = ''; var reFormatOK = /(Oldies|Classic rock|Classic hits)/i; var reErrURL1 = /^http(s)?:\/\/www.iheart.com/; var reErrURL2 = /^http(s)?:\/\/player.radio.com/; var reURL1 = /(\.pls|\.m3u|\.asx)/; var reURL2 = /^http(s)?:\/\/([\w-]+\.)+[\w-]+(:[0-9]+)+(\/)?$/; var ajaxMsg = ''; //項目の取得 var box = readData.find('.infobox'); var elements = box.find('tr'); //項目の設定 elements.each(function() { if($(this).find('th').text() == 'City') { city = $(this).find('td').text(); } else if($(this).find('th').text() == 'Branding') { branding = $(this).find('td').text(); } else if($(this).find('th').text() == 'Format') { format = $(this).find('td').text(); } else if($(this).find('th').text() == 'Webcast') { webcast = $(this).find('td').find('a').first().attr('href'); } else if($(this).find('th').text() == 'Website') { website = $(this).find('td').find('a').first().attr('href'); } }); if(!reFormatOK.test(format)) { ajaxMsg = 'Format NG!'; setMsg(ajaxMsg); } else if (webcast == '') { ajaxMsg = 'Webcast None!'; setMsg(ajaxMsg); } else if (reErrURL1.test(webcast) || reErrURL2.test(webcast)) { ajaxMsg = 'Webcast were discontinued outside the United States!'; setMsg(ajaxMsg); } else { //項目の設定 $("#city").val(city); $("#branding").val(branding); $("#station_format").val(format); $("#website").val(website); if (reURL1.test(webcast) || reURL2.test(webcast)) { ajaxMsg = 'Input Webcast'; setMsg(ajaxMsg); //画面のリンクを変更 var search = '<div id="station-search">' + '<a rel="noopener" target="_blank" ' + 'href="https://tunein.com/search/?query=' + callsign + '">' + callsign + ' - Tunein Search</a></div>' $("#station-search").replaceWith(search); //項目の設定 $("#comment").val( 'Stream URL for App like iTunes\n' + webcast); } else { //項目の設定 $("#webcast_url").val(webcast); } } }; function callWikipediaAPI(wikipediaPage) { $.getJSON( 'https://en.wikipedia.org/w/api.php?action=parse&format=json&callback=?', {page:wikipediaPage, prop:'text|images', uselang:'en'}, wikipediaHTMLResult); } $(function() { $(window).on('load', function() { $("#effect").prepend( '<div id="preloader"></div>'); $("#preloader").fadeOut(2000); }); }); $(window).scroll(function() { if ($(this).scrollTop() < 50) { $('#back-to-top').fadeOut(); } else { $('#back-to-top').fadeIn(); } }); // ページ切り替え時(初回ページも対象) $(document).on({ 'turbolinks:load': function() { $('#back-to-top').click(function() { $('html, body').animate({ scrollTop: 0 }, 1000, 'easeInOutExpo'); return false; }); //子の要素を変数に入れる var $children = $('.children'); //後のイベントで、不要なoption要素を削除するため、元の内容をとっておく var originChildren = $children.html(); //親のselect要素が変更になるとイベントが発生 $('.parent').change(function() { //エラー表示されていた場合 if ($('div').is('#error_explanation')) { //表示箇所を削除 $('#error_explanation').remove(); } //選択された親のvalueを取得し変数に入れる var val1 = $(this).val(); //削除された要素をもとに戻すため.子の元の内容を入れておく $children.html(originChildren).find('option').each(function() { //data-valの値を取得 var val2 = $(this).data('val'); //valueと異なるdata-valを持つ要素を削除 if (val1 != val2) { $(this).not(':first-child').remove(); } }); //親のselect要素が未選択の場合、子をdisabledにする if ($(this).val() == "") { $children.attr('disabled', 'disabled'); } else { $children.removeAttr('disabled'); } }); //孫の要素を変数に入れる var $grandchilds = $('.grandchilds'); //後のイベントで、不要なoption要素を削除するため、元の内容をとっておく var originGrandchilds = $grandchilds.html(); //子のselect要素が変更になるとイベントが発生 $('.children').change(function() { //選択された子のvalueを取得し変数に入れる var val1 = $(this).val(); //削除された要素をもとに戻すため.孫の元の内容を入れておく $grandchilds.html(originGrandchilds).find('option').each(function() { //data-valの値を取得 var val2 = $(this).data('val'); //valueと異なるdata-valを持つ要素を削除 if (val1 != val2) { $(this).not(':first-child').remove(); } }); //子のselect要素が未選択の場合、孫をdisabledにする if ($(this).val() == "") { $grandchilds.attr('disabled', 'disabled'); } else { $grandchilds.removeAttr('disabled'); } }); //孫のselect要素が変更になるとイベントが発生 $('.grandchilds').change(function() { //選択された孫のvalueを取得し変数に入れる var cs = $(this).val(); //画面のリンクを変更 var wiki = '<div id="station-wiki">' + '<a rel="noopener" target="_blank" ' + 'href="https://en.wikipedia.org/wiki/' + cs + '">' + cs + ' - Wikipedia</a></div>' $("#station-wiki").replaceWith(wiki); //初期化 $("#station-search").replaceWith('<div id="station-search"></div>'); $("#ajax-msg").replaceWith('<div id="ajax-msg"></div>'); $("#city").val(''); $("#branding").val(''); $("#station_format").val(''); $("#webcast_url").val(''); $("#website").val(''); $("#comment").val(''); //項目の設定 $("#callsign").val(cs); //関数呼び出し callWikipediaAPI(cs); }); } });
import React, { useState, useEffect } from 'react' import fireDb from '../database/firebase' const Cadastro = () => { const [dadosAlunos, setDadosAlunos] = useState({}) useEffect(() => { fireDb.child('cadastros').on('value', dbPhoto => { if (dbPhoto.val() != null) { setDadosAlunos({ ...dbPhoto.val() }) } else { setDadosAlunos({}) } }) }, []) return ( <div> <div className="jumbotron jumbotron-fluid"> <div className="container"> <h1 className="display-4">NOTAS 2021</h1> <p className="lead"> TURMA DE MATEMÁTICA</p> </div> </div> <div className="row"> <div className="col-12"> <table className="table table-borderless table-stripped"> <thead className="thead-light"> <tr> <td>Nome</td> <td>NotaUm</td> <td>NotaDois</td> <td>NotaTres</td> <td>NotaQuatro</td> </tr> </thead> <tbody> { Object.keys(dadosAlunos).map(id => { return <tr key={id}> <td> {dadosAlunos[id].Nome}</td> <td> {dadosAlunos[id].NotaUm}</td> <td> {dadosAlunos[id].NotaDois}</td> <td> {dadosAlunos[id].NotaTres}</td> <td> {dadosAlunos[id].NotaQuatro}</td> </tr> }) } </tbody> </table> </div> </div> </div> ) } export default Cadastro
/*$Rev: 1817 $ Revision number must be in the first line of the file in exactly this format*/ /* Copyright (C) 2009 Innectus Corporation All rights reserved This code is proprietary property of Innectus Corporation. Unauthorized use, distribution or reproduction is prohibited. $HeadURL: http://info.innectus.com.cn/innectus/trunk/loom/App/app/public/jscript_dev/uicontrollers/home.js $ $Id: home.js 1817 2010-05-18 00:37:02Z gesanto $ */ var UI = { init:function init(serverData){ }, onClickSubscribe:function(){ this.win = INNECTUS.DialogBox.createWindow({ id:"enrollWin" ,width:500 ,height:400 ,modal:true ,url:'/secure/subscription' ,title:"Subscribe" }); }, subscribe:function(){ this.win.close(); }, cancel:function(){ this.win.close(); } }
const getMultiplicationTable = require('../main') describe('Check is start smaller than end', () => { it("Should return true in isStartSmallerThanEnd when call 1, 2 ", () => { expect(getMultiplicationTable.isStartSmallerThanEnd(1, 2)).toBe(true); }) it("Should return false in isStartSmallerThanEnd when call 10, 2", () => { expect(getMultiplicationTable.isStartSmallerThanEnd(10, 2)).toBe(false); }) it("Should return true in isStartSmallerThanEnd when call 2, 2", () => { expect(getMultiplicationTable.isStartSmallerThanEnd(2, 2)).toBe(true); }) }) describe('Arguments range check', () => { it("Should return true in isArgumentsInTheRange when call 1, 1000", () => { expect(getMultiplicationTable.isArgumentsInTheRange(1, 1000)).toBe(true) }) it("Should return false in isArgumentsInTheRange when call 0, 1000", () => { expect(getMultiplicationTable.isArgumentsInTheRange(0, 1000)).toBe(false) }) it("Should return false in isArgumentsInTheRange when call 1, 1001", () => { expect(getMultiplicationTable.isArgumentsInTheRange(1, 1001)).toBe(false) }) it("Should return false in isArgumentsInTheRange when call 0, 1001", () => { expect(getMultiplicationTable.isArgumentsInTheRange(0, 1001)).toBe(false) }) it("Should return false in isArgumentsInTheRange when call -1, 0", () => { expect(getMultiplicationTable.isArgumentsInTheRange(-1, 0)).toBe(false) }) it("Should return false in isArgumentsInTheRange when call 1001, 1002", () => { expect(getMultiplicationTable.isArgumentsInTheRange(1001, 1002)).toBe(false) }) }) describe('Multiplication Table Check', () => { it("Should return multipalication table when call 7, 11", () => { expect(getMultiplicationTable.getMultiplicationTableText(7, 11, true, true)).toBe( ` 7 * 7 = 49\n` + ` 8 * 7 = 56 8 * 8 = 64\n` + ` 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81\n` + `10 * 7 = 70 10 * 8 = 80 10 * 9 = 90 10 * 10 = 100\n` + `11 * 7 = 77 11 * 8 = 88 11 * 9 = 99 11 * 10 = 110 11 * 11 = 121`) }) it("Should return null table when start-end check is false", () => { expect(getMultiplicationTable.getMultiplicationTableText(3, 2, false, true)).toBe(null) }) it("Shoult return out of range when range check is false", () => { expect(getMultiplicationTable.getMultiplicationTableText(-1, 10, true, false)).toBe('Arguments out of range.') }) })
import React, { Component } from 'react'; import ApiManager from '../services/swapi'; import Spinner from './spinner' export default class RandomPlanet extends Component { swapiServer=new ApiManager() state={ planet:{}, spinner:true, interval:false, PlanetPhotoURL:'https://starwars-visualguide.com/assets/img/placeholder.jpg' } PlanetLoaded=(planet)=>{ this.setState({ planet, spinner:false }) } getPhoto(url){ const photo= fetch(url) photo.then((data)=>{ if(data.status===200){ this.setState({ PlanetPhotoURL:data.url }) }else{ this.setState({ PlanetPhotoURL:'https://starwars-visualguide.com/assets/img/placeholder.jpg' }) } }) } getPlanet(id=1){ this.swapiServer.getPlanetsById(id).then( this.PlanetLoaded, this.getPhoto(`https://starwars-visualguide.com/assets/img/planets/${id}.jpg`)) } startInterval=()=>{ if(this.state.interval===false){this.setState({ interval:true }) this.random=setInterval(() => { let rnum=Math.floor(Math.random()*20+1) this.getPlanet(rnum) }, 3000);} else{ alert('Вы не можете начать рандомайзер если он уже включен') } } finishInterval=()=>{ this.setState({ interval:false }) clearInterval(this.random) } componentDidMount(){ this.getPlanet() setTimeout(this.startInterval(), 2000) } render() { const {spinner}=this.state const loading= spinner? <Spinner />:<RandomPlanetCard planet={this.state.planet} state={this.state}/> return ( <div className='PlanetWrapper'> <div className="random-planet"> {loading} </div> <StopIntervalButton stop={this.finishInterval} start={this.startInterval}/> </div> ); } } const RandomPlanetCard=({planet, state})=>{ const photo=state.PlanetPhotoURL const {id,climate,diameter,name,numberDays,population,url}=planet return( <React.Fragment> <img className="planet-image" src={photo} /> <div> <h4 className="planet-data">{name}</h4> <ul className="list-group list-group-flush"> <li className="list-group-item planet-data"> <span className="term">Population:</span> <span>{population}</span> </li> <li className="list-group-item planet-data"> <span className="term">Number of days in a year:</span> <span>{numberDays}</span> </li> <li className="list-group-item planet-data"> <span className="term">Diameter:</span> <span>{diameter}</span> </li> <li className="list-group-item planet-data"> <span className="term">Climate:</span> <span>{climate}</span> </li> </ul> </div> </React.Fragment> ) } const StopIntervalButton=({stop, start})=>{ return ( <React.Fragment> <button type="button" className="btn btn-success start-interval" onClick={()=>start()}>Start Random</button> <button type="button" className="btn btn-warning stop-interval" onClick={()=>stop()}>Stop Random</button> </React.Fragment> ) }
import React, { useState } from 'react' import { Button, IconButton, Avatar, TextField, Alert } from 'fusion' const App = () => { const [name, setName] = useState('') const [surname, setSurname] = useState('') const [branch, setBranch] = useState('') const [txt4, setTxt4] = useState('this') const [txt5, setTxt5] = useState('is') const [txt6, setTxt6] = useState('error') return ( <> <Button color='primary' onClick={(e) => { console.log(e) }} > primary </Button> <Button color='secondary' onClick={(e) => { console.log(e) }} > secondary </Button> <Button color='inherit' textColor='textColorPrimary' // disableRipple={true} onClick={(e) => { console.log(e) }} > transparent </Button> <Button color='inherit' textColor='textColorPrimary' disableRipple={true} onClick={(e) => { console.log(e) }} > no ripple </Button> <br /> <Button onClick={(e) => { console.log(e) }} raised={true} > primary raised </Button> <Button raised={true} color='secondary' onClick={(e) => { console.log(e) }} > secondary raised </Button> <Button raised={true} color='inherit' textColor='textColorSecondary' onClick={(e) => { console.log(e) }} > transparent </Button> <Button raised={true} color='inherit' textColor='textColorSecondary' disableRipple={true} onClick={(e) => { console.log(e) }} > no ripple raised </Button> <br /> <Button color='primary' onClick={(e) => { console.log(e) }} size='small' > small </Button> <Button color='primary' onClick={(e) => { console.log(e) }} size='medium' > medium </Button> <Button color='primary' onClick={(e) => { console.log(e) }} size='large' > large </Button> <Button color='primary' href='https://google.com' onClick={(e) => { console.log(e) }} size='large' > Link </Button> <br /> <Button variant='outlined'>primary outlined</Button> <Button variant='outlined' raised={true}> primary outlined raised </Button> <Button color='secondary' variant='outlined'> secondary outlined </Button> <Button color='secondary' variant='outlined' raised={true}> secondary outlined raised </Button> <br /> <IconButton size='small'>photo</IconButton> <IconButton color='primary'>delete</IconButton> <IconButton color='secondary' size='large'> new_releases </IconButton> <br /> <IconButton onClick={(e) => alert('hell')}>library_add</IconButton> <IconButton color='primary'>lightbulb_outline</IconButton> <IconButton color='primary'>local_activity</IconButton> <IconButton color='primary'>home</IconButton> <IconButton color='primary'>chat</IconButton> <IconButton color='primary'>search</IconButton> <IconButton color='primary'>account_circle</IconButton> <IconButton color='primary'>send</IconButton> <IconButton color=''>thumb_up</IconButton> <IconButton color=''>thumb_down</IconButton> <br /> <Button color='primary' size='small' onClick={(e) => { console.log(e) }} startIcon='save' > save </Button> <Button color='primary' onClick={(e) => { console.log(e) }} startIcon='save' > save </Button> <Button color='primary' startIcon='save' size='large' onClick={(e) => { console.log(e) }} > save </Button> <Button color='inherit' textColor='textColorPrimary' startIcon='cloud_upload' onClick={(e) => { console.log(e) }} > upload </Button> <br /> <Button color='secondary' onClick={(e) => { console.log(e) }} endIcon='delete' > delete </Button> <Button color='secondary' onClick={(e) => { console.log(e) }} endIcon='send' > send </Button> <Button color='secondary' onClick={(e) => { console.log(e) }} endIcon='add' > add </Button> <Button color='secondary' variant='outlined' endIcon='cloud_upload' onClick={(e) => { console.log(e) }} > upload </Button> <br /> <Button color='primary' startIcon='save' endIcon='save'> upload </Button> <hr /> <Avatar src='https://images.unsplash.com/photo-1612869839957-b596b87356ae?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDN8NnNNVmpUTFNrZVF8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1613425269135-fb9f19ae7be8?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDR8NnNNVmpUTFNrZVF8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1489493585363-d69421e0edd3?ixid=MXwxMjA3fDB8MHx0b3BpYy1mZWVkfDh8NnNNVmpUTFNrZVF8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1585477280412-633abe639bd4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8c3Vuc2V0fGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8c3Vuc2V0fGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1470252649378-9c29740c9fa8?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Nnx8c3Vuc2V0fGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1495616811223-4d98c6e9c869?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NXx8c3Vuc2V0fGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1586348943529-beaae6c28db9?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OXx8c3Vuc2V0fGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1460627390041-532a28402358?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fHN1bnNldHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1436891620584-47fd0e565afb?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MjJ8fHN1bnNldHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <Avatar src='https://images.unsplash.com/photo-1498575637358-821023f27355?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MjN8fHN1bnNldHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60' onClick={(e) => console.log(e)} /> <br /> <br /> <Avatar src='https://randomuser.me/api/portraits/women/75.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/44.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/31.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/40.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/28.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/42.jpg' /> <Avatar src='https://randomuser.me/api/portraits/men/71.jpg' /> <Avatar src='https://randomuser.me/api/portraits/men/61.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/26.jpg' /> <Avatar src='https://randomuser.me/api/portraits/men/10.jpg' /> <Avatar src='https://randomuser.me/api/portraits/women/27.jpg' /> <br /> <br /> <Avatar src='https://freaky5.com/wp-content/uploads/2018/07/SARDAR_KHAN-1024x682.jpg' size='small' alt='sd' /> <Avatar src='https://freaky5.com/wp-content/uploads/2018/07/SARDAR_KHAN-1024x682.jpg' size='medium' alt='sd' /> <Avatar src='https://freaky5.com/wp-content/uploads/2018/07/SARDAR_KHAN-1024x682.jpg' size='large' alt='sd' /> <br /> <Avatar size='small' alt='sd'> Adarsh </Avatar> <Avatar size='medium' alt='sd'> o </Avatar> <Avatar size='large' alt='sd'> n </Avatar> <br /> <Avatar size='small' /> <Avatar size='medium' /> <Avatar size='large' /> <p>avatar group remaining</p> <hr /> <p>alerts</p> <Alert /> <hr /> <TextField value={name} onChange={(e) => setName(e.target.value)} onClick={(e) => console.log(e)} placeholder='enter your name' type='text' label='Standard' /> <TextField value={surname} onChange={(e) => setSurname(e.target.value)} onClick={(e) => console.log(e)} type='text' variant='filled' label='Filled' /> <TextField value={branch} onChange={(e) => setBranch(e.target.value)} onClick={(e) => console.log(e)} type='text' variant='outlined' label='Outlined' /> ---errors--- <TextField value={txt4} onChange={(e) => setTxt4(e.target.value)} onClick={(e) => console.log(e)} type='text' label='Error Standard' helperText='this is helper' error={true} // autoFocus={true} /> <TextField value={txt5} variant='filled' onChange={(e) => setTxt5(e.target.value)} onClick={(e) => console.log(e)} type='text' label='Error Filled' helperText='this is helper 2' error={true} // autoFocus={true} /> <TextField value={txt6} variant='outlined' onChange={(e) => setTxt6(e.target.value)} onClick={(e) => console.log(e)} type='text' label='Error Outlined' helperText='this is helper 3' error={true} // autoFocus={true} /> <hr /> endl <hr /> <br /> <br /> </> ) } export default App
export default { setPhrase(context, phrase) { context.commit('setNewPhrase', phrase) }, removePhrase({ commit }) { commit('removePhrase') } }
import React from 'react'; export const CustomerAddress = ({ address }) => ( <div className="row"> <div className="col-md-3"> <b>Address:</b> </div> <div className="col-md-4 end">{address}</div> </div> );
OC.L10N.register( "lib", { "Cannot write into \"config\" directory!" : "\"configurasiya\" direktoriyasının daxilində yazmaq mümkün deyil", "This can usually be fixed by giving the webserver write access to the config directory" : "Adətən tez həll etmək üçün WEB serverdə yazma yetkisi verilir", "See %s" : "Bax %s", "This can usually be fixed by %sgiving the webserver write access to the config directory%s." : "Bu adətən %s config qovluğuna web server üçün yazma yetkisi verdikdə, %s tərəfindən fix edilə bilir. ", "Sample configuration detected" : "Konfiqurasiya nüsxəsi təyin edildi", "Unknown filetype" : "Fayl tipi bəlli deyil.", "Invalid image" : "Yalnış şəkil", "today" : "Bu gün", "seconds ago" : "saniyələr öncə", "None" : "Heç bir", "Username" : "İstifadəçi adı", "Password" : "Şifrə", "__language_name__" : "__AZ_Azerbaijan__", "App directory already exists" : "Proqram təminatı qovluğu artıq mövcuddur.", "Can't create app folder. Please fix permissions. %s" : "Proqram təminatı qovluğunu yaratmaq mümkün olmadı. Xahiş edilir yetkiləri düzgün təyin edəsiniz. %s", "General" : "Ümumi", "Security" : "Təhlükəsizlik", "Encryption" : "Şifrələnmə", "Sharing" : "Paylaşılır", "Search" : "Axtarış", "%s enter the database username." : "Verilənlər bazası istifadəçi adını %s daxil et.", "%s enter the database name." : "Verilənlər bazası adını %s daxil et.", "Oracle connection could not be established" : "Oracle qoşulması alınmır", "Oracle username and/or password not valid" : "Oracle istifadəçi adı və/ya şifrəsi düzgün deyil", "DB Error: \"%s\"" : "DB səhvi: \"%s\"", "Set an admin username." : "İnzibatçı istifadəçi adını təyin et.", "Set an admin password." : "İnzibatçı şifrəsini təyin et.", "%s shared »%s« with you" : "%s yayımlandı »%s« sizinlə", "Sharing %s failed, because the file does not exist" : "%s yayımlanmasında səhv baş verdi ona görə ki, fayl mövcud deyil.", "You are not allowed to share %s" : "%s-in yayimlanmasına sizə izin verilmir", "Share type %s is not valid for %s" : "Yayımlanma tipi %s etibarlı deyil %s üçün", "A valid username must be provided" : "Düzgün istifadəçi adı daxil edilməlidir", "A valid password must be provided" : "Düzgün şifrə daxil edilməlidir", "Settings" : "Quraşdırmalar", "Users" : "İstifadəçilər", "Imprint" : "İşarələmək", "Application is not enabled" : "Proqram təminatı aktiv edilməyib", "Authentication error" : "Təyinat metodikası", "Token expired. Please reload page." : "Token vaxtı bitib. Xahiş olunur səhifəni yenidən yükləyəsiniz.", "Unknown user" : "Istifadəçi tanınmır ", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Bu ola bilər ki, cache/accelerator such tərəfindən cağırılıb hansi ki, Zend OPcache və eAccelerator-da olduğu kimidir." }, "nplurals=2; plural=(n != 1);");
import jwt from 'jsonwebtoken'; import 'dotenv/config'; const generateToken = (payload) => { const token = jwt.sign({ payload }, process.env.JWT_SECRET); return token; }; const verifyToken = (request, response, next) => { const token = request.headers.authorization || request.body.token; if (!token) { return response.status(403) .json({ status: 403, error: 'No token supplied', }); } jwt.verify(token, process.env.JWT_SECRET, (error, authData) => { if (error) { if (error.message.includes('signature')) { return response.status(403) .json({ status: 403, error: 'Your input is not a valid token. Please input a correct one', }); } return response.status(403) .json({ message: error, }); } request.authData = authData; return next(); }); }; const adminPass = (request, response, next) => { const userInfo = request.authData.payload; if (userInfo.isadmin !== true) { return response.status(401) .json({ status: 403, error: 'You need admin privilege to access this endpoint.', }); } next(); }; export { generateToken, verifyToken, adminPass };
import { Router, Route } from 'react-router'; import App from './components/app/app'; import React from 'react'; export default (props) => ( <Router {...props}> <Route path='/' component={App} /> </Router> )
var logistica={divclass:'anylinkmenucols', inlinestyle:'', linktarget:'_self'} //Third menu variable. Same precaution. logistica.cols={divclass:'column', inlinestyle:''} //menu.cols if defined creates columns of menu links segmented by keyword "efc" logistica.items=[ ["&raquo; Controle de Entregas", "?acao=cdentrega"]] //no comma following last entry! var operacoes={divclass:'anylinkmenucols', inlinestyle:'', linktarget:'_self'} //Third menu variable. Same precaution. operacoes.cols={divclass:'column', inlinestyle:''} //menu.cols if defined creates columns of menu links segmented by keyword "efc" operacoes.items=[ ["&nbsp; CADASTROS", "#"], ["", ""], ["&raquo; Cadastro de Pessoal", "?acao=cadpessoa"], ["&raquo; Cadastro de Manutencao", "?acao=cdmanutencao"], ["&raquo; Cadastro de Produtividade", "?acao=cdprodutividade","efc"], ["&nbsp; RELATORIOS E LISTAGENS", "#"], ["", ""], ["&raquo; Relatorio de Entregas", "?acao=showentregas"], ["&raquo; Relatorio de Produtividade", "?acao=showprodutividade"], ["&raquo; Listagem de Funcionario/Candidato", "?acao=lspessoas"], ["&raquo; Controle de Manutencao", "?acao=lsmanutencao","efc"], ["&nbsp; FINANCEIRO", "#"], ["", ""], ["&raquo; Fluxo de Caixa", "?acao=cdfluxocaixa"]] //no comma following last entry! var setores={divclass:'anylinkmenucols', inlinestyle:'', linktarget:'_self'} //Third menu variable. Same precaution. setores.cols={divclass:'column', inlinestyle:''} //menu.cols if defined creates columns of menu links segmented by keyword "efc" setores.items=[ ["&nbsp; SETOR DE RH", "#"], ["", ""], ["&raquo; Nova Tarefa", "?acao=cdservdp"], ["&raquo; Nova Rescisão", "?acao=cdrescisao"], ["&raquo; Listar Tarefas", "?acao=gerarelatservdp"], ["&raquo; Gerar Relatorios", "?acao=relatDP","efc"], ["&nbsp; SETOR FISCAL", "#"], ["", ""], ["&raquo; Novo Processo", "?acao=cdprocfiscal"], ["&raquo; Listar Processos", "?acao=gerarelatprocfiscal"], ["&raquo; Ver Processos", "#"], ["&raquo; Fluxo de Caixa", "?acao=cdfluxofiscal"], ["&raquo; Gerar Relatorios", "?acao=relatProcFiscal","efc"], ["&nbsp; SETOR JURÍDICO", "#"], ["", ""], ["&raquo; Novo Atendimento", "?acao=cdatendjur"], ["&raquo; Listar Atendimentos", "?acao=gerarelatatendjur"] ] //no comma following last entry! var config={divclass:'anylinkmenucols', inlinestyle:'', linktarget:'_self'} //Third menu variable. Same precaution. config.cols={divclass:'column', inlinestyle:''} //menu.cols if defined creates columns of menu links segmented by keyword "efc" config.items=[ ["&raquo; Novo Usuário", "?acao=cdusuario"], ["&raquo; Ver Usuários", "#"], ["&raquo; Auditoria do Sistema", "#"] ] //no comma following last entry!
module.exports = app => { const mongoose = app.mongoose const Schema = mongoose.Schema const InventorySchema = new Schema({ id: Schema.Types.ObjectId, name: String, date: Date, // 规则 // 价格 price: { type: Number, default: 0 }, unit: String, quantity: Number, datum: Number, // 基准数量 datumQuantity: Number, // 基准价格 datumPrice: Number, // 基准单位 datumUnit: String }) return mongoose.model('Inventory', InventorySchema) }
import styled from 'styled-components'; //F3FCFF const ChromeButton = styled.a` color: #fff; background-color: hsl(231, 69%, 60%); border: 2px solid hsla(231, 69%, 60%, 0); &:hover { color: hsl(231, 69%, 60%); background-color: #fff; border: 2px solid hsla(231, 69%, 60%, 1); } @media (min-width: 500px) { margin-right: 5px; } `; export default ChromeButton;
import React, { useState } from 'react'; const TodoDetail = ({ todoId, userName, userEmail, userActiveEmail, description, productName, complete, created, handleCloseTodo, userActive, }) => { // const { // // userTo: { name: userName }, // // id: todoId, // } = todo; const todoDate = new Date(parseInt(created)); return ( <tr> <td className="px-6 py-4 whitespace-nowrap"> <div className="flex items-center"> <div className=""> <div className="text-sm font-medium text-gray-900">{userName}</div> <div className="text-sm text-gray-500">{userEmail}</div> </div> </div> </td> <td className="px-6 py-4 whitespace-nowrap"> <div className="text-sm text-gray-900">{description}</div> <div className="text-sm text-gray-500">{productName}</div> </td> <td className="px-6 py-4 whitespace-nowrap"> <span className={ complete ? 'bg-green-100 text-green-800 px-2 inline-flex text-xs leading-5 font-semibold rounded-full ' : 'bg-red-100 text-red-800 px-2 inline-flex text-xs leading-5 font-semibold rounded-full ' } > {complete ? 'TERMINADO' : 'PENDIENTE'} </span> </td> <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"> {todoDate.toDateString()} </td> <td className="px-6 py-4 whitespace-nowrap"> {userActive === userActiveEmail && ( <div className="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in"> <input type="checkbox" name="toggle" id="toggle" checked={complete} onChange={() => handleCloseTodo(todoId, !complete)} className="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer" /> <label htmlFor="toggle" className="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer" ></label> </div> )} </td> </tr> ); }; export default TodoDetail;
import React, { Component } from "react"; import InfiniteScroll from "react-infinite-scroll-component"; import { Link, Redirect } from "react-router-dom"; import { SINGLE_PRODUCT_ROUTE } from "../../constants/routes"; export class TabsProducts extends Component { constructor(props) { super(props); } state = { prodId: 0, }; render() { return ( <InfiniteScroll dataLength={this.props.array == null ? 0 : this.props.array.length} next={this.props.fetchMore} hasMore={this.props.hasMore} loader={ this.props.currentFetchnig && ( <p className="infLoadingMessage">Loading...</p> ) } endMessage={ <p className="infErrorMessage"> <b>There are no more products to show.</b> </p> } > <div className="row"> <div className="col-lg-12"> <div className="row imagetiles"> {this.props.array != null && this.props.array.map( function (product) { return ( <div className="col-lg-3 col-md-3 col-sm-6 col-xs-6 tabsProductDiv" key={product.id} style={{ marginTop: "40px" }} > <Link to={{ pathname: SINGLE_PRODUCT_ROUTE.replace( ":prodId", product.id ), state: { chosenProduct: product.id, isLoggedIn: this.props.isLoggedIn, email: this.props.email, token: this.props.token, }, }} > <img className="tabProductImage" src={`data:image/png;base64, ${product.image}`} /> </Link> <div> <Link className="productNameLink" to={{ pathname: SINGLE_PRODUCT_ROUTE.replace( ":prodId", product.id ), state: { chosenProduct: product.id, isLoggedIn: this.props.isLoggedIn, email: this.props.email, token: this.props.token, }, }} > {product.name} </Link> </div> <Link className="startsFrom" to={{ pathname: SINGLE_PRODUCT_ROUTE.replace( ":prodId", product.id ), state: { chosenProduct: product.id, isLoggedIn: this.props.isLoggedIn, email: this.props.email, token: this.props.token, }, }} > Starts from ${product.startPriceText} </Link> </div> ); }.bind(this) )} </div> </div> </div> </InfiniteScroll> ); } } export default TabsProducts;
var request = require('request'); var cheerio = require('cheerio'); var tough = require('tough-cookie'); exports.fromUrl = function(url, callback) { parseUrl(url, callback); }; exports.fromHtml = function(data, callback) { callback(null, parseHtml(data)); }; var parseUrl = function(url, callback) { var useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36'; var jar = request.jar(); var options = { method: 'GET', url: url, followAllRedirects: true, rejectUnauthorized: false, headers: { 'User-Agent': useragent }, jar: jar }; request(options, function (err, resp, body) { callback(err, parseHtml(body)); }); }; var parseHtml = function(data) { var card = {}; try { $ = cheerio.load(data); var metaTags = $('meta'); var imageTags = $('img'); //Get initial card from meta tags card = parseMetas(metaTags); //If title isn't set now, grab it from the <title> tag if (!card.title || card.title.length <= 0) { card.title = $('title').text(); } //Get images card.images = parseImages(imageTags); } catch (exception) { //Do nothing } //Sanity if (!card.title) { card.title = ''; } if (!card.description) { card.description = ''; } if (!card.openGraphDescription) { card.openGraphDescription = ''; } if (!card.twitterDescription) { card.twitterDescription = ''; } if (!card.keywords) { card.keywords = []; } if (!card.image) { card.image = ''; } if (!card.images) { card.images = []; } return card; }; var parseMetas = function(metaTags) { var card = { }; var keys = Object.keys(metaTags); //Iterate throuhg all meta tags keys.forEach(function(key){ if (metaTags[key].attribs && (metaTags[key].attribs.property || metaTags[key].attribs.name)) { var metaProperty = ((metaTags[key].attribs.property) ? metaTags[key].attribs.property.toLowerCase() : ''); var metaName = ((metaTags[key].attribs.name) ? metaTags[key].attribs.name.toLowerCase() : ''); var metaContent = ((metaTags[key].attribs.content) ? metaTags[key].attribs.content : ''); if ((!card.title || card.title.length < metaContent.length) && (metaProperty === 'og:title' || metaName === 'twitter:title')) { card.title = metaContent; } else if (!card.description && metaName === 'description') { card.description = metaContent; } else if (!card.openGraphDescription && metaProperty === 'og:description') { card.openGraphDescription = metaContent; } else if (!card.twitterDescription && metaName === 'twitter:description') { card.twitterDescription = metaContent; } else if ((!card.image || card.image.length < metaContent.length) && (metaProperty === 'og:image:secure_url' || metaProperty === 'og:image')) { var temp = metaContent.toLowerCase(); if (temp.substring(0, 7) === 'http://' || temp.substring(0, 8) === 'https://') card.image = metaContent; } else if (metaName === 'keywords') { card.keywords = metaContent.split(/[\s,]+/); } } }); return card; }; var parseImages = function(imageTags) { var imageTagsArray = imageTags.toArray(); var images = []; for (var i = 0; i < imageTagsArray.length; i++) { if (imageTagsArray[i].attribs && imageTagsArray[i].attribs.src) { var src = imageTagsArray[i].attribs.src; images.push(src); } } return images; };
// import * as actions from '../actions' // const initialState = { // tabVariant: 'day', // reportsDailyIncome: [], // filtered: [], // isLoading: false, // hasErrors: false // }; // function getReportDailyIncomeReducer(state = initialState, action) { // switch (action.type) { // case actions.GET_REPORT_DAILY_INCOME: // return { // ...state, // isLoading: true // }; // case actions.GET_REPORT_DAILY_INCOME_SUCCESS: // console.log(action.payload) // return { // ...state, // filtered: action.payload, // reportsDailyIncome: action.payload, // isLoading: false // }; // case actions.GET_REPORT_DAILY_INCOME_FAILURE: // return { // ...state, // isLoading: false, // hasErrors: action.error // }; // case 'UPDATE_TAB_VARIANT': // return { // ...state, // tabVariant: action.payload // } // default: // return state; // } // } // export default getReportDailyIncomeReducer
import { Platform, StatusBar, StyleSheet, View, Text } from "react-native"; import { NavigationContainer } from "@react-navigation/native"; import { Provider } from "react-redux"; import * as eva from "@eva-design/eva"; import { PersistGate } from "redux-persist/es/integration/react"; import { ApplicationProvider } from "@ui-kitten/components"; import { registerRootComponent } from "expo"; import React from "react"; import { Message } from "./src/components"; import store, { persistor } from "./src/store/store"; import Routes from "./src/Routes"; import kittenTheme from "./src/kitten-theme.json"; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", }, }); const RootComponent = () => ( <Provider store={store}> <PersistGate persistor={persistor}> <ApplicationProvider {...eva} theme={{ ...eva.light, ...kittenTheme }}> <View style={styles.container}> {Platform.OS === "ios" && <StatusBar barStyle="default" />} <NavigationContainer> <Routes /> </NavigationContainer> <Message /> </View> </ApplicationProvider> </PersistGate> </Provider> ); function App(props) { return <RootComponent />; } export default App;
(function(){ browser.storage.local.get('autoSearchOpt', function(items){ if(items.autoSearchOpt){ browser.storage.local.get('autoSearchSet', function(items){ initiateSearch(items.autoSearchSet); }); } }); function initiateSearch(selKeySetName){ browser.storage.local.get(selKeySetName, function(items) { var keySetValues = items[selKeySetName]; $.each(keySetValues, function(index, value){ searchWord(value, 'color'+index); }); }); } function searchWord(word, css){ word = word.replace(/\s/g, '\\s'); console.log('word is: '+word); var regExp = new RegExp(word, "i"); console.log('searching for: '+regExp); console.log('highlight by: '+css); $("body").markRegExp(regExp, {'className':css, 'separateWordSearch':false, 'acrossElements':true}); //$("body").mark(word, {'className':css, 'separateWordSearch':false, 'acrossElements':true}); } })();
import React from "react"; const Trainers = (props) => { const { trainers } = props; const renderTrainers = () => { return trainers.map((trainer) => { return <h3>{trainer.name}</h3>; }); }; return ( <div> <h1>All Pokemon Trainers!</h1> {renderTrainers()} </div> ); }; export default Trainers;
var ob = ob || {}; ;(function(namespace, undefined) { namespace.hash = function() { var _s = '.'; return { separator: function(s) { _s = s; }, parse: function() { if (window.location.hash.length < 2) { return []; } var str = window.location.hash; str = str.replace("#",""); var keys = str.split(_s); return keys; }, set: function(keys) { } }; } })(ob);
import { TOGGLE_THEME, DEFAULT_COLOR } from '@/store/mutation-types' import store from 'store' import config from '../../../defaultSettings' const app = { state: { theme: config.theme, fixedHeader: false, fixSiderbar: false, autoHideHeader: false, color: config.color, }, mutations: { [TOGGLE_THEME]: (state, theme) => { store.set(TOGGLE_THEME, theme); state.theme = theme; }, [DEFAULT_COLOR]: (state, color) => { store.set(DEFAULT_COLOR, color); state.color = color } }, actions: { ToggleTheme({ commit }, theme) { commit(TOGGLE_THEME, theme) }, ToggleColor({ commit }, color) { commit(DEFAULT_COLOR, color) } } } export default app;
// Use .env.{development|production} files to set up our env variables require("dotenv").config({ path: `.env.${process.env.NODE_ENV}`, }); const { NODE_ENV, URL: NETLIFY_SITE_URL = "https://www.mealmatchup.org", DEPLOY_PRIME_URL: NETLIFY_DEPLOY_URL = NETLIFY_SITE_URL, CONTEXT: NETLIFY_ENV = NODE_ENV, } = process.env; const isNetlifyProduction = NETLIFY_ENV === "production"; const siteUrl = isNetlifyProduction ? NETLIFY_SITE_URL : NETLIFY_DEPLOY_URL; const firebasePrefix = isNetlifyProduction ? "PROD" : "DEV"; /** Export siteMetadata and plugins for Gatsby */ module.exports = { siteMetadata: { title: "Meal Matchup", description: "", siteUrl, }, plugins: [ "gatsby-plugin-typescript", "gatsby-plugin-eslint", "gatsby-plugin-sass", "gatsby-plugin-react-helmet", { resolve: "gatsby-plugin-less", options: { lessOptions: { javascriptEnabled: true, }, }, }, { resolve: "gatsby-plugin-firebase", options: { credentials: { apiKey: process.env[`${firebasePrefix}_FIREBASE_API_KEY`], authDomain: process.env[`${firebasePrefix}_FIREBASE_AUTH_DOMAIN`], databaseURL: process.env[`${firebasePrefix}_FIREBASE_DATABASE_URL`], projectId: process.env[`${firebasePrefix}_FIREBASE_PROJECT_ID`], storageBucket: process.env[`${firebasePrefix}_FIREBASE_STORAGE_BUCKET`], messagingSenderId: process.env[`${firebasePrefix}_FIREBASE_MESSAGING_SENDER_ID`], appId: process.env[`${firebasePrefix}_FIREBASE_APP_ID`], }, }, }, { resolve: "gatsby-source-wordpress", options: { baseUrl: "depts.washington.edu/mealmatchup", protocol: "https", hostingWPCOM: false, useACF: false, includedRoutes: [ "**/pages", "**/media", ], }, }, { resolve: "gatsby-source-filesystem", options: { name: "graphics", path: `${__dirname}/src/graphics/`, }, }, { resolve: "gatsby-plugin-manifest", options: { icon: "src/graphics/icon.png", }, }, ], };
import React from 'react'; import { Text, View, ImageBackground, StyleSheet } from 'react-native'; import bgImage from '../../assets/background.png' const SMTP_CONFIG = require('../config/smpt') const nodemailer = require('nodemailer') const transporter = nodemailer.createTransport({ host: SMTP_CONFIG.host, port: SMTP_CONFIG.port, secure: false, auth:{ user: SMTP_CONFIG.user, pass: SMTP_CONFIG.pass, }, tls:{ rejectUnauthorized: false } }) export default function Alerta(props){ async function run(){ const mailSent = await transporter.sendMail({ text: "Texto do email", subject: "Assunt do email", from: "Safe Girl <safegirlgps1@gmail.com>", to:['brunobispoo25@gmail.com'] }) console.log(mailSent) } return( <View style={styles.container}> <ImageBackground source={bgImage} style={styles.backgroundImage}> <Text onPress={()=>run}>Alertar</Text> </ImageBackground> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, backgroundImage:{ flex: 1, alignItems: 'center', justifyContent: 'center', resizeMode: 'cover', height: null, width:'100%', } });
/* eslint-disable react/jsx-closing-tag-location */ const React = require('react') const MetaData = require('./components/MetaData') const Restore = ({ namePage, errors, token }) => { return ( <html> <MetaData namePage={namePage} /> <body className='login_container'> <main className='login_card'> <h1 className='login_title'>Restaurar Contraseña en <img src='/images/logo.svg' alt='UpTask Logo' /></h1> <form className='form' action={token ? `/restore/${token}` : '/restore'} method='post'> {token ? <> <label className='form_label' htmlFor='password'>Nueva Contraseña</label> <input className='form_input' type='password' name='password' id='password' placeholder='Nueva Contraseña' /> </> : <> <label className='form_label' htmlFor='email'>Email</label> <input className='form_input' type='email' name='email' id='email' placeholder='Email' /> </>} {errors ? <span className='alert'>{errors}</span> : <></>} <div className='button_container'> <div className='button_item'> <span className='form_label'>¿Rescordaste tu contraseña?</span> <a className='button-black' href='/login'>Iniciar Sesión <i className='fas fa-sign-in-alt' /></a> </div> {token ? <button className='button'>Restaurar Contraseña <i className='fas fa-undo-alt' /></button> : <button className='button' type='submit'>Verificar Email <i className='fas fa-user-check' /></button>} </div> </form> </main> <script src='/dist/bundle.js' /> </body> </html> ) } module.exports = Restore
import React from "react"; import { MdAddBox } from "react-icons/md"; import { Button, Form } from "react-bootstrap"; export default function addForm({ addToDo, addSubToDo, value, hideAdd, helpText }) { const [text, setText] = React.useState(""); let handleAddToDo = (text) => { addSubToDo ? addSubToDo(value, text) : addToDo(text); setText(""); hideAdd && hideAdd(); }; return ( <Form> <Form.Group controlId="addToDo"> <Form.Label>{helpText ? helpText : "Add ToDo"}</Form.Label> <Form.Control value={text} type="text" placeholder={helpText ? helpText : "Enter ToDo"} onChange={(event) => setText(event.target.value)} /> <Form.Text className="text-muted">Add anything you want ToDo</Form.Text> <Button clasName={"addNew"} onClick={() => handleAddToDo(text)} disabled={(text.length === 0 || !text.trim()) && true} > <MdAddBox /> </Button> </Form.Group> </Form> ); }
import React from 'react'; import './Header.css'; import { NavLink } from 'react-router-dom'; const Header = props => { return ( <header className="header"> <nav className="headerMenu"> <NavLink to="/">Home</NavLink> <NavLink to="/about">About</NavLink> <NavLink to="/posts">Posts</NavLink> <NavLink to="/newpost">New Post</NavLink> </nav> </header> ); } export default Header;
import React, { Component } from 'react'; import './App.css' import RegisterPage from './components/RegisterPage' import ModifyPage from './components/ModifyPage' const liff = window.liff; class App extends Component { constructor(props) { super(props); this.state = { displayName: '', userId: '', userRegistered: false }; } // initialize() { // liff.init(async (data) => { // let profile = await liff.getProfile(); // this.setState({ // displayName: profile.displayName, // userId: profile.userId // }); // }); // } // closeApp(event) { // event.preventDefault(); // liff.sendMessages([{ // type: 'text', // text: "我填完了!" // }]).then(() => { // liff.closeWindow(); // }); // } componentDidMount() { // window.addEventListener('load', this.initialize); // this.initialize(); // fetch('/api/check-users', { // method: 'POST', // body: JSON.stringify({ userID: this.state.userId }), // headers: new Headers({ // 'Content-Type': 'application/json' // }) // }).then( // res => res.json() // ).then(data => { // console.log(data); // if (data.IDregistered === true) { // console.log("[ERROR] ID registered!") // this.setState({ userRegistered: true }) // } else { // // console.log("ID not registered yet") // this.setState({ userRegistered: false }) // } // }); } render() { if (this.state.userRegistered === false) { return ( <RegisterPage displayName={this.state.displayName} userId={this.state.userId} /> ); } else { return ( <ModifyPage displayName={this.state.displayName} userId={this.state.userId} /> ) } } } export default App; // <div className="container"> // <div className="columns m-t-10"> // <div className="column col-xs-12"> // <div className="panel"> // <div className="panel-header text-center"> // <figure className="avatar avatar-lg"> // <img src={this.state.pictureUrl} alt="Avatar" /> // </figure> // <div className="panel-title h5 mt-10">{this.state.displayName}</div> // <div className="panel-subtitle">{this.state.statusMessage}</div> // </div> // <div className="panel-footer"> // <button className="btn btn-primary btn-block" onClick={this.closeApp}>Close</button> // </div> // </div> // </div> // </div> // </div>
import React from "react"; import { Route, Switch } from "react-router-dom"; import Login from "./components/Login"; import Profile from "./components/Profile"; import PrivateRoute from "./components/PrivateRoute"; import Dashboard from "./components/Dashboard"; import ButtonAppBar from "./components/NavBar/ButtonAppBar"; import { useSelector } from "react-redux"; function App() { const token = useSelector((state) => state.userReducer.token); console.log("App -> token", token); return ( <div> <ButtonAppBar /> <Switch> {token ? ( <> <PrivateRoute exact path="/" component={Dashboard} /> <PrivateRoute exact path="/profile" component={Profile} /> </> ) : ( <Route exact path="/" component={Login} /> )} </Switch> </div> ); } export default App;
(function(){ var divFood = document.querySelector('.food'); var xhr = new XMLHttpRequest(); xhr.open('GET', './service/food', true); xhr.onload = function(){ showFood(JSON.parse(xhr.responseText)); }; xhr.onerror = function(){ alert('Service Failed'); }; xhr.send(); function showFood(foods){ var innerHTML = ''; for (var i = 0; i < foods.length; i++) { innerHTML += '<div class="product">' + '<img src="' + foods[i].thumb + '">' + '<p class="name">' + foods[i].name + '</p>' + '<p class="price">' + foods[i].price + '</p>' + '</div>'; }; divFood.innerHTML = innerHTML; } })();
let santeInit = 100; var player = { // creation du joueur setplayer: function (sante, image, placement, degat, arme, defend) { this.sante = sante; this.image = image, this.placement = placement this.degat = degat, this.arme = arme, // 1 = oui ; 0 = non this.defend = defend }, placePlayer1: function () { let numbRepeat = Math.round(Math.random() * (144 - 1) + 1); //controle si la case est dsiponible pour placement du joueur. let getElement = $(".plateau").find("#" + numbRepeat).hasClass("vide").toString(); //indication du pacement sur la grille du joueur playerGame1.placement = numbRepeat; //placement de l'image du joueur et sur la grille $(".plateau").find("#" + playerGame1.placement).css("background-image", "url(" + playerGame1.image + ")").css('background-size', 'cover').addClass('gamer1').removeClass('vide'); //initialisation de la barre de vie $(".lifeplayer1").text("Points de vie: " + playerGame1.sante); }, placePlayer2: function () { let numbRepeat = Math.round(Math.random() * (144 - 1) + 1); //controle si la case est dsiponible pour placement du joueur. let getElement = $(".plateau").find("#" + numbRepeat).hasClass("vide").toString(); playerGame2.placement = numbRepeat $(".plateau").find("#" + playerGame2.placement).css("background-image", "url(" + playerGame2.image + ")").css('background-size', 'cover').addClass('gamer2').removeClass('vide'); $(".lifeplayer2").text("Points de vie: " + playerGame2.sante); }, attack: function (id, playerSante, animImg) { //test si fin de partie en cas de vie a 0 if (playerSante <= 0) { alert('Fin de partie'); } else { $('.' + id).text("Points de vie: " + playerSante); $(animImg).effect('bounce', 700); } }, defendre: function () { }, deplacer: function (id, name, placement, image) { //on cherche l'id de personnage $(".plateau").find("#" + placement).removeAttr('style').removeClass(name).addClass('vide'); //placement nouvelle position $(".plateau").find("#" + id).css("background-image", "url(" + image + ")").css('background-size', 'cover').removeClass('vide').addClass(name); }, tourPlayer: function () { if (playerTurn == 1) { playerTurn = 2; } else { playerTurn = 1; } }, combat: function (gamepos1, gamepos2) { if ((gamepos1 == gamepos2 + 1) || (gamepos2 == gamepos1 + 1) || (gamepos1 == gamepos2 + 12) || (gamepos2 == gamepos1 + 12)) { alert('combattt'); if (playerTurn == 2) { $('.btnPlay1, .btnDefend1').attr("disabled", true); $('.btnPlay2, .btnDefend2').attr("disabled", false); } else { $('.btnPlay2, .btnDefend2').attr("disabled", true); $('.btnPlay1, .btnDefend1').attr("disabled", false); } } } }
!(function (e, t) { "use strict"; if (!Object.prototype.hasOwnProperty.call(e, "lightwidget")) { e.addEventListener( "message", function (e) { if ( -1 === [ "lightwidget.com", "dev.lightwidget.com", "cdn.lightwidget.com", "instansive.com", ].indexOf(e.origin.replace(/^https?:\/\//i, "")) ) return !1; var i = (function (e) { if (-1 < e.indexOf("{")) return JSON.parse(e); var i = e.split(":"); return { widgetId: i[2] .replace("instansive_", "") .replace("lightwidget_", ""), size: i[1], }; })(e.data); if (i.size <= 0) return !1; [].forEach.call( t.querySelectorAll( 'iframe[src*="lightwidget.com/widgets/' + i.widgetId + '"],iframe[data-src*="lightwidget.com/widgets/' + i.widgetId + '"],iframe[src*="instansive.com/widgets/' + i.widgetId + '"]' ), function (e) { e.style.height = i.size + "px"; } ); }, !1 ), (e.lightwidget = {}); } })(window, document);
import './About.css'; import img from '../assets/chandrakanth_chittappa_image.jpeg'; import Links from '../components/Links'; function About(){ return( <div className="about-container" id="about"> <div className="about-image"> <div className="image"> <img id="imageId" src={img} alt="portfolio_image"/> </div> </div> <div className="about-text"> <div className="text-animation-container"> <div className="displayText"> <div className="static-txt">Hello!<br/> I'm Chandrakanth </div> <div className="dynamic-txt-container"> <ul className="dynamic-txt"> <li><span id="front-end">Front-End Developer</span></li> <li><span id="back-end">Back-End Developer</span></li> <li><span id="full-stack">Full Stack Developer</span></li> </ul> <Links/> </div> </div> </div> </div> </div> ) } export default About;
import $ from 'jquery'; import drawer_index from './drawer/index' import drawer_sample from './drawer/sample' import promise_index from './promise/index' // pagesディレクトリ配下の各画面には"pages_{親ディレクトリ名}_{ファイル名}"でbody要素にクラス名が割り振られる // それを利用し各画面毎のjsを実行する document.addEventListener('DOMContentLoaded', () => { const classNames = $('body').attr('class').split(' '); for(let className in pagesClassMap) { if(classNames.indexOf(className) >= 0) { pagesClassMap[className](); break; } } }); const pagesClassMap = { pages_drawer_index: drawer_index, pages_drawer_sample: drawer_sample, pages_promise_index: promise_index };
import React, { Component } from "react"; import AuthService from "../../services/auth.service"; // import Navigation from "../navigation/navigation" import BurgerNavigation from "../navigation/burger-navigation" import UserService from "../../services/user.service"; import "./profile.css" import prof from "../images/developer.gif"; export default class Profile extends Component { constructor(props) { super(props); this.handleUpdate = this.handleUpdate.bind(this); this.onChangeFullname = this.onChangeFullname.bind(this); this.onChangeAddress = this.onChangeAddress.bind(this); this.onChangeContact = this.onChangeContact.bind(this); this.state = { fullname: "", contact: "", address: "", email: "", username: "", successmessage: "", errormessage: "", currentUser: AuthService.getCurrentUser() }; } onChangeFullname(e) { this.setState({ fullname: e.target.value }); } onChangeAddress(e) { this.setState({ address: e.target.value }); } onChangeContact(e) { this.setState({ contact: e.target.value }); } componentDidMount() { UserService.getUserById(this.state.currentUser.id).then((response) => { this.setState({ fullname: response.data.fullname, address: response.data.address, contact: response.data.contact, email: response.data.email, username: response.data.username, }) // console.log(response.data) }); } handleUpdate(e) { e.preventDefault(); const data = { fullname: this.state.fullname, address: this.state.address, contact: this.state.contact, }; UserService.getUserUpdate(this.state.currentUser.id, data) .then(response => { // handle success this.setState({ successmessage: response.data.message }) setTimeout(function () { window.location.reload() }, 3000); }).catch(error => { // handle error this.setState({ errormessage: "Something went wrong" }) }) } render() { return ( <div data-testid="main-profilebody"> <BurgerNavigation data-testid="header-navigation" /> <div className="container extraac"> <form> <h2 className="text-center custom-container">User Information</h2> <img src={prof} alt="profile-one" className="rounded mx-auto d-block sizing" /> <div className="alert-section-message"> <div className="alert alert-success" style={{ display: this.state.successmessage !== "" ? "" : "none" }}> {this.state.successmessage} </div> <div className="alert alert-danger" style={{ display: this.state.errormessage !== "" ? "" : "none" }}> {this.state.errormessage} </div> </div > <div className="user_card"> <div className="form-group"> <label htmlFor='fullname'>Full Name</label> <input type='text' name='fullname' id='fullname' className="form-control" value={this.state.fullname} onChange={this.onChangeFullname} /> </div> <div className="form-group"> <label htmlFor='username'>User Name</label> <input type='text' name='username' className="form-control" id='fullname' value={this.state.username} disabled /> </div> <div className="form-group"> <label htmlFor='email'>Email</label> <input type='email' name='email' id='email' className="form-control" value={this.state.email} disabled /> </div> <div className="form-group"> <label htmlFor='contact'>Contact</label> <input type='text' name='contact' className="form-control" id='lastName' value={this.state.contact} onChange={this.onChangeContact} /> </div> <div className="form-group"> <label htmlFor='address'>Address</label> <input type='text' name='address' id='address' className="form-control" value={this.state.address} onChange={this.onChangeAddress} /> </div> <button type="button" onClick={this.handleUpdate} className="btn btn-outline-success btn-lg btn-block">Update</button> </div> </form> </div> </div> ); } }
/** ** module that provides methods to intialize and run a ** single loop of the game ** ** params: ** - ctx: html5 canvas context ** - height, width: height and width of playing screen ** - snakeStartLength: length which snake starts at ** - unit: size of one side of a single square in the game **/ var SnakeGameService = (function(ctx, width, height, snakeStartLength, unit) { //helper module for generating random coordinates var random = RandomCoordModule(width, height, unit); var grid = GridModule(width, height, unit); var score = ScoreModule(); //private game state variables var snake; //x, y coords of each block in the snake's body var points; var food; //x, y coords of food //game constants const backgroundColor = "#9dc997"; const snakeColor = "black"; /** ** some helper methods for drawing a single square according to the game's ** standard unit size **/ function fillSquare(x, y) { ctx.clearRect(x * unit, y * unit, unit, unit); ctx.fillRect(x * unit, y * unit, unit, unit); } function drawSquareBorders(x, y) { ctx.strokeRect(x * unit, y * unit, unit, unit); } /** ** initialize the game screen **/ function initGame() { ctx.canvas.width = width; ctx.canvas.height = height; //initialize game state variables snake = []; dir = Direction.down; points = 0; food = {}; //setup background ctx.fillStyle = backgroundColor; ctx.fillRect(0, 0, width, height); //set up snake body ctx.fillStyle = snakeColor; ctx.strokeStyle = backgroundColor; var startX = 2; var startY = 0; snake = []; for (var i = 0; i < snakeStartLength; i++) { snake.push({x: startX, y: startY + i}); fillSquare(snake[i].x, snake[i].y); drawSquareBorders(snake[i].x, snake[i].y); grid.setFull(snake[i].x, snake[i].y); } drawFood(); score.setupScore(points); } /** ** moves the snake 1 unit in the current direction **/ function moveSnake() { var snakeHead = snake[snake.length - 1]; var newHead = {x: snakeHead.x, y: snakeHead.y}; //move new head forward switch (dir) { case Direction.up: newHead.y -= 1; break; case Direction.down: newHead.y += 1; break; case Direction.left: newHead.x -= 1; break; case Direction.right: newHead.x += 1; break; } //push new head and color the grid ctx.fillStyle = snakeColor; fillSquare(newHead.x, newHead.y); drawSquareBorders(newHead.x, newHead.y); snake.push(newHead); grid.setFull(newHead.x, newHead.y); //pop off tail and erase grid var front = 0; ctx.fillStyle = backgroundColor; fillSquare(snake[front].x, snake[front].y); grid.setEmpty(snake[front].x, snake[front].y); snake.shift(); } //draw food in random spot in grid function drawFood() { food.x = random.randX(); food.y = random.randY(); //food may have spawned within the snake body - regenerate coords while (grid.isFull(food.x, food.y)) { food.x = random.randX(); food.y = random.randY(); } ctx.fillStyle = snakeColor; fillSquare(food.x, food.y); } /** ** checker functions to be called at each interval ** to either update points or detect a game over **/ function checkFoodEaten() { var snakeHead = snake[snake.length - 1]; return snakeHead.x == food.x && snakeHead.y == food.y; } function checkSelfCollision() { var snakeHead = snake[snake.length - 1]; for (var i = 0; i < snake.length - 1; i++) { if (snake[i].x == snakeHead.x && snake[i].y == snakeHead.y) { return true; } } return false; } function checkWallCollision() { var snakeHead = snake[snake.length - 1]; return (snakeHead.x < 0 || snakeHead.y < 0 || snakeHead.x >= width / unit || snakeHead.y >= height / unit); } /** ** produces a single loop of the game **/ function runGameLoop() { moveSnake(); if (checkSelfCollision() || checkWallCollision()) { clearInterval(gameLoop); startButton.disabled = false; score.setNewHighscore(points); alert("Game Over"); return; } if (checkFoodEaten()) { points++; document.getElementById("score").innerHTML = "Score: " + points; snake.push({x: food.x, y: food.y}); drawFood(); //respawn food } } return { initGame: function() { initGame(); }, runGameLoop: function() { runGameLoop(); } } });
import React from 'react'; import Container from '@material-ui/core/Container'; import AddPerson from '../components/add-person.component'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ container: { padding: '2vh 1rem 0 1rem' } }); export default function AddPage(){ const classes = useStyles(); return( <Container className={classes.container} maxWidth="lg"> <AddPerson /> </Container> ) }
import React from 'react'; import {Navbar,Nav} from 'react-bootstrap'; import {NavLink} from 'react-router-dom'; import logo from '../image/alc-logo.png'; const Header = () => { return ( <Navbar bg="info" fixed="top" expand="lg"> <Navbar.Brand href="/"><img className="logo" src={logo} alt="logo" style={{minWidth: '8rem', height:'3rem'}}></img></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mr-auto"> <NavLink className="headerLink" to="/checklist">Checklist</NavLink> <NavLink className="headerLink" to="/questionnare">Questionnaire</NavLink> </Nav> </Navbar.Collapse> </Navbar> ) } export default Header