text
stringlengths
7
3.69M
import { StyleSheet } from 'react-native'; import { color } from '../functions/providers/ColorContext'; const resourceStyles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center' }, categoryContainer: { borderRadius: 15, padding: 5, marginTop: 10 }, category: { fontSize: 20 }, contentContainer: { width: '95%', // borderRadius: 25, padding: 5, borderTopWidth: 1 }, // unused dropdownArrow: { height: 30, width: 30, backgroundColor: color.highlight, alignItems: 'flex-end', justifyContent: 'flex-start', right: 10 }, title: { fontSize: 18 }, source: { fontSize: 16 } }); export default resourceStyles;
import gql from "graphql-tag"; export const SIGN_IN = gql` mutation ($username: String!, $password: String!) { signIn(login: $username, password: $password) { token me { id agentId username email role players { id agentId email username role } } } } `; export const SIGN_UP = gql` mutation ($username: String!, $email: String!, $password: String!, $role: String!, $agentId: ID) { signUp(username: $username, email: $email, password: $password, role: $role, agentId: $agentId) { id username email role agentId } } `; export const UPDATE_AVAILABLE = gql` mutation ($input: UpdateAvailableInput!) { updateAvailable(input: $input) { id available } } `;
frist Second third
let images = { "cube": [ loadImage("cube-red"), loadImage("cube-orange"), loadImage("cube-yellow"), loadImage("cube-green"), loadImage("cube-cyan"), loadImage("cube-blue"), loadImage("cube-indigo") ], "outline": loadImage("outline") }; function loadImage(name) { let img = new Image(); img.src = `assets/images/${name}.png`; return img; } function render(canvas) { ctx = canvas.getContext("2d"); cw = canvas.width; ch = canvas.height; ctx.clearRect(0, 0, cw, ch); const cubeSize = Math.min( Math.floor(cw / (fieldWidth + fieldHeight)*2), Math.floor(ch / (fieldWidth + fieldHeight + 2)*4) ); if ( !field[0] ) return false; const tetrominoX = fallingTetromino.x; const tetrominoY = fallingTetromino.y; for (let y = 0; y < fieldHeight; y++) { for (let x = 0; x < fieldWidth; x++) { const pos = calcPos(x, y, cubeSize); let image = images.outline; if (field[y][x] || fallingTetromino.shape[y - tetrominoY] && fallingTetromino.shape[y - tetrominoY][x - tetrominoX] ) { let imageNum = 0; if (colorMode == "normal" || colorMode == "random") { if ( field[y][x] ) imageNum = field[y][x] - 1; else imageNum = fallingTetromino.color - 1; } else if (colorMode == "rainbow") { const colorsNum = images.cube.length; imageNum = Math.floor((y + 1) / fieldHeight * colorsNum); if (imageNum >= colorsNum) imageNum = colorsNum - 1; } image = images.cube[imageNum]; } ctx.drawImage(image, pos.x, pos.y, cubeSize, cubeSize); } } } function calcPos(x, y, cubeSize) { const xShift = (x - y)/2 - (fieldWidth - fieldHeight)/4 - 1/2; const yShift = (x + y)/4 - (fieldWidth + fieldHeight)/8 - 1/4; const xPos = xShift*cubeSize + cw/2 const yPos = yShift*cubeSize + ch/2; return {"x": xPos, "y": yPos}; } function changeColorMode(mode) { colorMode = mode; render(canvas); }
export const GET_DEMO_REQUEST = 'GET_DEMO_REQUEST'; export const GET_DEMO_SUCCESS = 'GET_DEMO_SUCCESS'; export const SEARCH_MEDIA_ERROR = 'SEARCH_MEDIA_ERROR'; export const GET_OAUTH_GITHUB_TOKEN_START = 'GET_OAUTH_GITHUB_TOKEN_START'; export const GET_OAUTH_GITHUB_TOKEN_SUCCESS = 'GET_OAUTH_GITHUB_TOKEN_SUCCESS'; export const GET_OAUTH_GITHUB_TOKEN_ERROR = 'GET_OAUTH_GITHUB_TOKEN_ERROR'; export const GET_PROFILE_GITHUB_DATA_START = 'GET_PROFILE_GITHUB_DATA_START'; export const GET_PROFILE_GITHUB_DATA_SUCCESS = 'GET_PROFILE_GITHUB_DATA_SUCCESS'; export const GET_PROFILE_GITHUB_DATA_ERROR = 'GET_PROFILE_GITHUB_DATA_ERROR'; export const GET_PROFILE_GITHUB_REPOS_START = 'GET_PROFILE_GITHUB_REPOS_START'; export const GET_PROFILE_GITHUB_REPOS_SUCCESS = 'GET_PROFILE_GITHUB_REPOS_SUCCESS'; export const GET_PROFILE_GITHUB_REPOS_ERROR = 'GET_PROFILE_GITHUB_REPOS_ERROR';
import {IonContent, IonItem} from "@ionic/react"; const NavBar = props => { return ( <IonContent style = {{position:"absolute", top: "0", left: "0", height: "50px", width: "100%"}}> <IonItem > Tool </IonItem> </IonContent> ) } export default NavBar;
angular.module("app") .controller("mainCtrl", function($scope, mainService){ $scope.red = mainService.getcolor('red'); $scope.orange = mainService.getcolor('orange'); $scope.yellow = mainService.getcolor('yellow'); $scope.green = mainService.getcolor('green'); $scope.blue = mainService.getcolor('blue'); $scope.indigo = mainService.getcolor('indigo'); $scope.black = mainService.getcolor('black'); })
'use strict' const Proyecto = use('App/Models/Proyecto'); const Tarea = use('App/Models/Tarea'); const AutorizacionService = use('App/Service/AutorizacionService'); class TareaController { async index({auth, params}){ const user = await auth.getUser(); const { id } = params; const proyecto = await Proyecto.find(id); AutorizacionService.verificarPermiso(proyecto,user); return await proyecto.tareas().fetch(); } async create({auth, request, params}){ const user = await auth.getUser(); const { descripcion } = request.all(); const { id } = params; const proyecto = await Proyecto.find(id); AutorizacionService.verificarPermiso(proyecto,user); const tarea = new Tarea(); tarea.fill({ descripcion, }); await proyecto.tareas().save(tarea); return tarea; } async destroy({auth, params}){ const user = await auth.getUser(); const { id } = params; const tarea = await Tarea.find(id); const proyecto = await tarea.proyecto().fetch(); AutorizacionService.verificarPermiso(proyecto,user); await tarea.delete(); return tarea; } async update({auth,request, params}){ const user = await auth.getUser(); const { id } = params; const tarea = await Tarea.find(id); const proyecto = await tarea.proyecto().fetch(); AutorizacionService.verificarPermiso(proyecto,user); tarea.merge(request.only([ 'descripcion', 'completada' ])); await tarea.save(); return tarea; } } module.exports = TareaController
// black box goes here. var pull = require('pull-stream'); var freeze = require('pull-freezed'); var meta_match = require('metamatch'); function black_box (strategy) { if (! (this instanceof black_box)) { return new black_box (strategy); } this.meta = new meta_match (strategy); var pull_json = pull.map(function (_val) { if (typeof _val === 'string') { return JSON.parse(_val); } else { return _val; } }); var self = this; this.meta.pull = function () { return pull( pull_json, freeze, self.meta.match() ); }; return this.meta; } module.exports = black_box;
import axios from "axios"; // const END_POINT = "http://localhost:8000"; const END_POINT = "https://eain-thone.herokuapp.com/"; export default axios.create({ baseURL: END_POINT, });
import React from 'react'; import IconButton from 'material-ui/IconButton'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; const style = { margin: 20 }; class FlatButtonExampleSimple extends React.Component { constructor(props) { super(props) this.state = { count:1 } } handleCount() { this.setState({ count: this.state.count + 1 }) } render() { return ( <MuiThemeProvider> <div> 6. Button - Icon Button<br/> <IconButton tooltip="bottom-right" touch={true} tooltipPosition="bottom-right"> <ActionGrade /> </IconButton> <IconButton tooltip="bottom-center" touch={true} tooltipPosition="bottom-center"> <ActionGrade /> </IconButton> <IconButton tooltip="bottom-left" touch={true} tooltipPosition="bottom-left"> <ActionGrade /> </IconButton> <IconButton tooltip="top-right" touch={true} tooltipPosition="top-right"> <ActionGrade /> </IconButton> <IconButton tooltip="top-center" touch={true} tooltipPosition="top-center"> <ActionGrade /> </IconButton> <IconButton tooltip="top-left" touch={true} tooltipPosition="top-left"> <ActionGrade /> </IconButton> </div> </MuiThemeProvider> ) } } export default FlatButtonExampleSimple;
/** * 公用js */ /** * 服务器地址 */ var HOST_URL = "http://39.106.56.107:8888"; //var HOST_URL = "http://127.0.0.1:8888"; var IMAGE_URL = "http://39.106.56.107/images/"; function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } /** * 访问用户首页 */ function accessUser(userName){ $(window.parent.document).find("#m_Iframe").attr("src","view/userPage.html").attr("name","userPage"); }
function buildDetialBtn(article){ var detial_btn=document.createElement("button"); detial_btn.setAttribute("type","button"); detial_btn.setAttribute("class","btn btn-default btn-sm control"); detial_btn.setAttribute("data-toggle","collapse"); detial_btn.setAttribute("data-target","#demo"+ article.id); detial_btn.setAttribute("title","详情"); var span=document.createElement("span"); span.setAttribute("class","glyphicon glyphicon-list"); detial_btn.appendChild(span); return detial_btn; } function buildAddBtn(article){ var add_btn=document.createElement("button"); add_btn.setAttribute("type","button"); add_btn.setAttribute("class","btn btn-default btn-sm control"); add_btn.setAttribute("title","添加"); add_btn.setAttribute("data-dismiss","modal"); var span=document.createElement("span"); span.setAttribute("class","glyphicon glyphicon-check"); add_btn.appendChild(span); return add_btn; } function buildRead(article){ var read=document.createElement("span"); read.setAttribute("class","read"); var span1=document.createElement("span"); span1.setAttribute("class","glyphicon glyphicon-eye-open"); var span_r=document.createElement("span"); var span_r_txt=document.createTextNode(' 阅读('+article.click_cnt+') '); var span2=document.createElement("span"); span2.setAttribute("class","glyphicon glyphicon-thumbs-up"); var span_l=document.createElement("span"); var span_l_txt=document.createTextNode(' 点赞('+article.like_cnt+') '); read.appendChild(span1); read.appendChild(span_r); span_r.appendChild(span_r_txt); read.appendChild(span2); read.appendChild(span_l); span_l.appendChild(span_l_txt); return read; }
// This step in the build does a rough verification of the newly built dist file // It simply imports dist/snacks.js and tries to run a few things // This ensures we don't publish a release that will break others' code bases // This also ensures that Snacks can be imported into a node environment // basic importing works (most issues will appear here) import { execSync } from 'child_process' import * as SnacksUMD from '../../dist/snacks' import colors from '../../src/styles/colors' import zIndex from '../../src/styles/zIndex' const exec = command => execSync(command, { stdio: 'inherit' }) function verifyBuild(SnacksBuild) { // verify colors from dist equal src Object.keys(SnacksBuild.colors).forEach(color => { if (colors[color] !== SnacksBuild.colors[color]) { throw new Error( `Snacks dist file colors do not match - expect ${colors[color]}, but saw ${ SnacksBuild.colors[color] }` ) } }) // verify zIndex from dist equal src Object.keys(SnacksBuild.zIndex).forEach(zValue => { const sourceObj = zIndex[zValue] const builtObj = SnacksBuild.zIndex[zValue] if (sourceObj.zIndex !== builtObj.zIndex) { throw new Error( `Snacks dist file zIndex do not match - expect ${sourceObj.zIndex}, but saw ${ builtObj.zIndex }` ) } }) } console.log('Verifying UMD build') verifyBuild(SnacksUMD) console.log('Verifying ESM build (bundling and importing)') exec('yarn webpack --config=webpack.verify-esm.config.js') const SnacksESMBundle = require('../../tmp/esm-bundle') verifyBuild(SnacksESMBundle) console.log('Verifying typings') exec('yarn tsc -p tsconfig.verify-build.json')
const actionTable = { templateUrl: './app/components/mco/action-table/action-table.html', controller: ActionTableController }; angular.module('mco').component('actionTable', actionTable);
/*global define*/ define([ 'jquery', 'underscore', 'backbone', 'templates' ], function ($, _, Backbone, JST) { 'use strict'; var NavView = Backbone.View.extend({ template: JST['app/scripts/templates/nav.ejs'], tagName: 'section', className: 'navs', events: { //'click .btn_close': 'closeCard' }, initialize: function (options) { this.options = options; //this.listenTo(this.model, 'change', this.render); }, render: function () { this.$el.html(this.template(this.model)); $('.navbox').append(this.$el); }, }); return NavView; });
import React from 'react' import {Link} from 'react-router-dom' export default function NotFound(){ return( <> <h1>404 page not found</h1> <p>Voltar ao inicio<Link to="/">Voltar</Link></p> </> ) }
import { createStackNavigator } from "react-navigation"; import LoginScreen from "./containers/screens/LoginScreen"; import SignUpScreen from "./containers/screens/SignUpScreen"; export default createStackNavigator({ SignInScreen: { screen: LoginScreen }, SignUpScreen: { screen: SignUpScreen }, }, { headerMode: null, });
const { mockRepo } = require('../../helper'); const mockUser = mockRepo(); const mockIncident = mockRepo(); jest.mock('../../models', () => ({ User: mockUser, Incident: mockIncident })); const { incidents } = require('./incidents'); describe('/src/graphql/resolvers/raiseIncidentToUser.js', () => { beforeEach(() => { jest.resetAllMocks(); mockIncident.sort.mockReturnValue(mockIncident); mockIncident.skip.mockReturnValue(mockIncident); }); afterAll(() => { jest.restoreAllMocks(); }); it('should define resolver type', () => { expect(incidents).toHaveProperty('type', 'Query'); }); it('should fetch all incidents if dont have any input', async () => { const expectReceive = [{ a: 1 }, { b: 2 }]; mockIncident.find.mockResolvedValue(expectReceive); const ret = await incidents(null); expect(ret).toStrictEqual(expectReceive); expect(mockIncident.find).toBeCalledTimes(1); expect(mockIncident.find).toBeCalledWith(); }); describe('filter', () => { it('should support for filter', async () => { const rawQuery = { a: 1, b: 2 }; mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { filter: rawQuery }); expect(mockIncident.find).toHaveBeenCalledWith(rawQuery); }); it('should fetch all if not provide filter', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { a: 1 }); expect(mockIncident.find).toHaveBeenCalledWith({}); }); }); describe('sort', () => { it('should support for sorting', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { sort: { field: 'assignee', order: -1 } }); expect(mockIncident.sort).toHaveBeenCalledWith({ assignee: -1 }); }); it('should sort asc by default', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { sort: { field: 'assignee' } }); expect(mockIncident.sort).toHaveBeenCalledWith({ assignee: 1 }); }); it('should sort by createdAt field by default', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { a: 1 }); expect(mockIncident.sort).toHaveBeenCalledWith({ createdAt: 1 }); }); }); describe('pagination', () => { it('should support pagination by default', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { a: 1 }); expect(mockIncident.skip).toHaveBeenCalledWith((1 - 1) * 100); expect(mockIncident.limit).toHaveBeenCalledWith(100); }); it('should support use default page 1 for pageNo', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { pagination: { pageSize: 5 } }); expect(mockIncident.skip).toHaveBeenCalledWith((1 - 1) * 5); expect(mockIncident.limit).toHaveBeenCalledWith(5); }); it('should support use default page size 100', async () => { mockIncident.find.mockReturnValue(mockIncident); await incidents(null, { pagination: { pageNo: 5 } }); expect(mockIncident.skip).toHaveBeenCalledWith((5 - 1) * 100); expect(mockIncident.limit).toHaveBeenCalledWith(100); }); }); });
// Start for couruse categories // const b = document.querySelectorAll(".bg-design"); // const len = b.length; // for(var i = 0; i < len; i++) { // const result = document.querySelectorAll(".bg-design")[i]; // result.addEventListener('mouseenter' function(){ // result.style.background = 'red'; // }); // } const changeBgColor = [...document.querySelectorAll('.bg-design')] changeBgColor.forEach(item => item.addEventListener('mouseenter',() => item.style.background='red') // End for couruse categories
// Declaring Variables const menuThemeTrigger = document.getElementById("down-arrow"); const sailorDay = document.getElementById("theme-day"); const sailorNight = document.getElementById("theme-night"); const menuTheme = document.getElementById("theme-option"); const createGifosButton = document.getElementById("create-gifos-box"); const chooseThemeButton = document.getElementById("choose-theme-box"); const myGifText = document.getElementById("mygif-text"); const gifosLogo = document.getElementById("logo"); const suggestGifContainer = document.getElementById('suggest-container'); const trendGifContainer = document.getElementById("trends-gifs"); const input_box = document.getElementById("input-search"); const first_search = document.getElementById("first-search-p-tag"); const second_search = document.getElementById("second-search-p-tag"); const third_search = document.getElementById("third-search-p-tag"); const searchSuggestContainer = document.getElementById("search-suggest-text"); const first_search_div = document.getElementById("first-search-div"); const second_search_div = document.getElementById("second-search-div"); const third_search_div = document.getElementById("third-search-div"); const searchButton = document.getElementById("search-button"); const suggestSection = document.getElementById('suggest-section'); const trendBox = document.getElementById('trend-box'); const trendGifs = 'https://api.giphy.com/v1/gifs/trending?api_key=qsOjAmeDhQKoL3IW1Cnaty7Rayav17Ix&limit=12&rating=G'; const stylesTag = document.getElementById('styles-tag'); let darkIndicator = false ; window.onload = function () { let myVariable = localStorage.getItem('trueorfalse'); if( myVariable == 'true') { darkTheme(); } else { dayTheme(); } }; // declaring Functions const gettingInformation = async (url) => { const informationRetrieved = await fetch(url); return informationRetrieved.json(); }; const showingMenu = () => { if (menuTheme.style.display == "none") { menuTheme.style.display = "flex"; } else { menuTheme.style.display = "none"; }; }; const dayTheme = () => { stylesTag.setAttribute('href','./styles/light/styles.css'); searchButton.children[0].setAttribute('src','./asset/lupa_inactive.svg'); gifosLogo.setAttribute("src", "./asset/gifOF_logo.png"); darkIndicator = false; localStorage.setItem('trueorfalse',darkIndicator); }; const darkTheme = () => { stylesTag.setAttribute("href","./styles/dark/styles.css") searchButton.children[0].setAttribute('src','./asset/combined_shape.svg'); gifosLogo.setAttribute("src", "./asset/gifOF_logo_dark.png"); darkIndicator = true; localStorage.setItem('trueorfalse',darkIndicator); }; const getRandomIndex = (array) => { return Math.floor(Math.random() * array.length); }; const SuggestOptions = [ 'charlie+brown', 'phoebe+buffay', 'rachel+green', 'monica+geller', 'ross+geller', 'joey+tribbiani', 'chandler+bing', 'the+killers', 'RHCP', 'blink+182', 'rammstein' ]; const suggestion = getRandomIndex(SuggestOptions); SuggestGifs = `https://api.giphy.com/v1/gifs/search?api_key=qsOjAmeDhQKoL3IW1Cnaty7Rayav17Ix&q='${SuggestOptions[suggestion]}'&limit=4&offset=0&rating=G&lang=en`; gettingInformation(SuggestGifs).then((result) => { for (let i=0; i < suggestGifContainer.children.length; i++) { if (result.data[i].title == '' ) { suggestGifContainer.children[i].children[0].innerText = result.data[i].slug; } else { suggestGifContainer.children[i].children[0].innerText = result.data[i].title; }; suggestGifContainer.children[i].children[1].children[0].setAttribute('src',result.data[i].images.original.url); suggestGifContainer.children[i].children[1].children[0].style.width = '100%'; suggestGifContainer.children[i].children[1].children[0].style.height = '299px'; }; }).catch((error) => { console.log(error); }); gettingInformation(trendGifs).then((result) => { i = result.data.length while( i -- ) { let newImage = document.createElement('img') newImage.setAttribute('src',result.data[i].images.original.url) newImage.style.margin = '0 0 15px 3%'; newImage.style.width = '30%'; newImage.style.height = 'auto'; trendGifContainer.appendChild(newImage) }; }).catch((error) => { console.log(error); }); const gettingSuggestions = () => { const suggestedTextURL = `https://api.giphy.com/v1/gifs/search/tags?api_key=qsOjAmeDhQKoL3IW1Cnaty7Rayav17Ix&limit=2&q=${input_box.value}`; gettingInformation(suggestedTextURL).then((result) => { if (result.data.length > 1) { first_search.innerText = input_box.value; second_search.innerText = result.data[0].name; third_search.innerText = result.data[1].name; } else { first_search.innerText = input_box.value; second_search.innerText = "No suggestions to show"; third_search.innerText = "No suggestions to show"; }; }).catch((e) => { console.log(e); }); }; const checkingifEmptyInput = () => { if (input_box.value.length == 0) { searchSuggestContainer.style.display = "none"; if (darkIndicator == false ) { dayTheme(); } else { darkTheme(); }; } else { searchSuggestContainer.style.display = "flex"; if (darkIndicator == false ) { searchButton.style.background = '#F7C9F3'; searchButton.children[0].setAttribute('src','./asset/lupa.svg'); searchButton.children[1].style.color = '#110038'; } else { searchButton.style.background = '#EE3EFE'; searchButton.children[0].setAttribute('src','./asset/lupa_light.svg'); searchButton.children[1].style.color = '#FFFFFF'; searchSuggestContainer.style.background = '#B4B4B4'; var searchSuggestContainerChildren = Array.from(searchSuggestContainer.children); searchSuggestContainerChildren.forEach(element => { element.style.background = '#B4B4B4'; }); }; }; }; const selectingAnOption = (eventObj) => { input_box.value = eventObj.target.innerText; }; const searchingGifs = (eventObj) => { eventObj.preventDefault(); const searchQuery = `https://api.giphy.com/v1/gifs/search?api_key=qsOjAmeDhQKoL3IW1Cnaty7Rayav17Ix&limit=12&q=${input_box.value}`; gettingInformation(searchQuery).then( (result)=> { suggestSection.style.display = 'none'; for (let i = 0; i < trendGifContainer.children.length; i++){ trendGifContainer.children[i].setAttribute('src', result.data[i].images.original.url); // trendGifContainer.children[i].style.width = '30%'; // trendGifContainer.children[i].style.marginBottom = '20px'; }; if (searchSuggestContainer.style.display != 'none') { searchSuggestContainer.style.display = 'none'; }; if (darkIndicator == false) { searchButton.style.background = '#e6e6e6'; searchButton.children[0].setAttribute('src','./asset/lupa_inactive.svg'); searchButton.children[1].style.color = '#8F8F8F'; } else { searchButton.style.background = '#B4B4B4'; searchButton.children[0].setAttribute('src','./asset/combined_shape.svg'); searchButton.children[1].style.color = '#8F8F8F'; }; }).catch( (e)=> { console.log(e); }); }; const gettingAndRenderingGifsFromLocalStorage = () => { var listOfGifs = [] keys = Object.keys(localStorage); i = keys.length; while ( i-- ) { if (keys[i].startsWith("gif\-")) { listOfGifs.push(localStorage.getItem(keys[i])) }; }; while(trendGifContainer.firstChild) { trendGifContainer.removeChild(trendGifContainer.firstChild); }; i = listOfGifs.length; while ( i-- ) { let newChild = document.createElement('img') newChild.setAttribute('src',JSON.parse(listOfGifs[i]).images.original.url) newChild.style.margin = '0 0 15px 3%'; trendGifContainer.appendChild(newChild) }; }; const myGifos = () => { suggestSection.style.display = 'none'; trendBox.children[0].innerText = 'Mis guifos'; gettingAndRenderingGifsFromLocalStorage(); }; // Listeners menuThemeTrigger.addEventListener("click", showingMenu); sailorDay.addEventListener("click", dayTheme); sailorNight.addEventListener("click", darkTheme); input_box.addEventListener("keyup", gettingSuggestions); input_box.addEventListener("keyup", checkingifEmptyInput); input_box.addEventListener("click",checkingifEmptyInput); first_search_div.addEventListener("click", selectingAnOption); second_search_div.addEventListener("click", selectingAnOption); third_search_div.addEventListener("click", selectingAnOption); searchButton.addEventListener("click",searchingGifs); myGifText.addEventListener("click",myGifos);
const mongoose = require('mongoose'); //Schema del cliente, es el modelo de como son los objetos cliente const studentSchema = mongoose.Schema({ firstName: { type: String }, lastName: { type: String }, id: { type: String } }); //Se exporta el modelo para que pueda ser utilizado en app.js //El primer parámetro es el nombre del modelo y el otro es el schema //del modelo que se va a utilizar var Student = (module.exports = mongoose.model( 'Student', studentSchema, 'students' ));
const validBraces = (braces) => { const validBraces = []; let res = true; [...braces].map((cur) => { if (cur === "(" || cur === "{" || cur === "[") { validBraces.push(cur); } else { const pop = validBraces.pop(); if (cur === ")" && pop !== "(") { res = false; } else if (cur === "}" && pop !== "{") { res = false; } else if (cur === "]" && pop !== "[") { res = false; } } }); if (validBraces.length > 0) { res = false; } return res; };
import git from '..' import pkg from '../package.json' describe('version', () => { test('version', () => { let v = git().version() expect(v).toEqual(pkg.version) }) })
export const state = () => ({ // This is the name.js store, with all the logic containing the random name generator, // or the custom the visitor has chosen him or her self. nameCurrent: "Name Your Setup", // A database of random names saved in three parts // 📝 this will later come from a real data base, but for testing purposes I have created a small demo nameRandom: { prefix: ["Amazing", "Awesome", "Groovy"], location: ["City", "Street", "Coast"], suffix: ["Cruiser", "Destroyer", "Shredder"], }, nameCurrentRandom: { prefix: "Your", location: "Cool", suffix: "Setup", }, // The index of what name of the three parts to update nameRandomIndex: 0, // Keep state if the visitor has chosen a custom name nameUserCustom: false, }); // name.js state mutations export const mutations = { nameGenerator(state) { function randomNum(amount) { return Math.floor(Math.random() * amount); } // Get the next part of the name that should be updated const updateCurrent = Object.keys(state.nameRandom)[state.nameRandomIndex]; state.nameCurrentRandom[updateCurrent] = state.nameRandom[updateCurrent][ randomNum(state.nameRandom[updateCurrent].length) ]; const nameCombined = `${state.nameCurrentRandom.prefix} ${ state.nameCurrentRandom.location } ${state.nameCurrentRandom.suffix}`; state.nameCurrent = nameCombined; state.nameRandomIndex++; if (state.nameRandomIndex >= Object.keys(state.nameRandom).length) { state.nameRandomIndex = 0; } }, setName(state, payload) { state.nameCurrent = payload; }, setNameUser(state) { state.nameUserCustom = true; }, }; export const getters = { getName: state => { return state.nameCurrent; }, getUserBool: state => { return state.nameUserCustom; }, };
import { Navigation } from '../../../src/Navigation'; import Base from '../../../src/Base'; describe('Navigation', () => { describe('.back', () => { it('should resolve immediately if navigation is locked', () => { const navigation = new Navigation(); navigation.locked = true; expect(navigation.back()).resolves.toBeUndefined(); }); it('should lock navigation immediately and unlock at the end', async () => { const navigation = new Navigation(); const navigator = new Base.Navigator('navigator'); const scene = new Base.Scene('scene'); navigator.addScenes(scene); navigation.addNavigators(navigator); await navigation.go('navigator', 'scene'); expect(navigation.locked).toBeFalsy(); const promise = navigation.back(); expect(navigation.locked).toBeTruthy(); await promise; expect(navigation.locked).toBeFalsy(); }); it('should resolve if history is empty', async () => { const navigation = new Navigation(); const navigator = new Base.Navigator('navigator'); navigation.addNavigators(navigator); expect.assertions(1); expect(navigation.history.isEmpty()).toBeTruthy(); try { await navigation.back(); } catch (e) { expect(e).toBeUndefined(); } }); it('should call back on the navigator', async () => { const navigation = new Navigation(); const navigator = new Base.Navigator('navigator'); const scene = new Base.Scene('scene'); navigator.addScenes(scene); navigation.addNavigators(navigator); await navigation.go('navigator', 'scene'); navigator.back = jest.fn(); await navigation.back(); expect(navigator.back).toHaveBeenCalledTimes(1); }); }); });
let pageToken = {}; const endpoint='https://www.googleapis.com/youtube/v3/search'; function apiFunction(str,cb){ let formQuery = { part: 'snippet', key: 'AIzaSyBulISD75zhez62BB5L1BnZn7VllIUyAd4', q: `${str}` // pageToken: pageToken['current'] }; $.getJSON(endpoint, formQuery,cb); } // format function images(video){ let imgUrl = video['snippet']['thumbnails']['medium']['url']; let channelLink = video['snippet']['channelId']; let channelName = video['snippet']['channelTitle']; let videoName = video['snippet']['title']; let description = video['snippet']['description']; return ` <br> <a href="https://www.youtube.com/watch?v=${video['id']['videoId']}"> <img src="${imgUrl}" alt="${description}"> <h4>${videoName}</h4> </a> <p>More from <a href="https://www.youtube.com/channel/${channelLink}/videos"> ${channelName} </a> </p>`; } // $('.token').click(function(){ // pageToken['current'] = $(this).val() === 'Next' ? pageToken.nextPage : getQuery(); // console.log('token.click', pageToken); // }) // for each item function displayResults(data) { // pageToken.nextPage = data.nextPageToken; // pageToken.prevPage = data.prevPageToken; // console.log(`nextpagetoken: ${data['nextPageToken']}, prevPageToken: ${data['prevPageToken']}`); let numResults = data['pageInfo']['totalResults']; const results = data['items'].map((item) => images(item)); $('.number-of-results').html(`<p>${numResults} results</p><br><div class="results"></div>`); $('.results').html(results); } function getQuery() { $('.js-form').submit(function(event) { event.preventDefault(); let search = $(this).find('.js-query'); let searchText = search.val(); apiFunction(searchText, displayResults); }); } $(getQuery);
/* 输入二叉树和一整数,打印二叉树中结点和为整数的所有路径。 路径:从根结点开始往下直到叶结点所经过的结点 每个路径就是一个数组,最终结果为二维数组 */ function FindPath(root, expectNumber) { var result = [] var path = [] if (!root) return result // 注意为空的情况,否则会报错:返回的结果值不对 dfsFind(root, expectNumber, result, path) return result } function dfsFind(root, expectNumber, result, path) { expectNumber -= root.val path.push(root.val) if (root.left === null && root.right === null) { if (expectNumber === 0) { result.push(path.slice()) } // path = [] // 这个操作只是影响当前的引用,不影响整个递归过程的真正的值 } if (root.left !== null) { dfsFind(root.left, expectNumber, result, path) } if (root.right !== null) { dfsFind(root.right, expectNumber, result, path) } path.pop() // 这里才会引用path的值 } /* // 10,5,12,4,7 var tree = { val: 10, left: { val: 5, left: { val: 4, left: null, right: null }, right: { val: 7, left: null, right: null } }, right: { val: 12, left: null, right: null } } var result = FindPath(tree, 22) console.log(result.toString()) */
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import md5 from 'crypto-js/md5'; import { login, handleToken } from '../actions'; import '../style/login.css'; class Login extends Component { constructor(props) { super(props); this.state = { name: '', email: '', isDisabled: true, }; this.handleChange = this.handleChange.bind(this); this.verifyNameAndEmail = this.verifyNameAndEmail.bind(this); this.handleSignUp = this.handleSignUp.bind(this); } handleSignUp(event) { event.preventDefault(); const { sendUser, getToken, history } = this.props; getToken(); const { name, email } = this.state; const hash = md5(email).toString(); sendUser({ name, email, hash }); history.push('/game'); } handleChange({ target }) { const { name, value } = target; this.setState( { [name]: value, }, () => this.verifyNameAndEmail(), ); } verifyNameAndEmail() { const { name, email } = this.state; this.setState({ isDisabled: !(name !== '' && email !== '') }); } render() { const { name, email, isDisabled } = this.state; return ( <div> <p className= "title"> Trivia</p> <p className= "subtitle"> The Game</p> <div className="container"> <div className="container-login"> <form onSubmit={ this.handleSignUp }> <div className="forms"> <div className="inputs-login"> <input value={ name } name="name" placeholder="Your name" onChange={ this.handleChange } data-testid="input-player-name" className="input" /> <input value={ email } name="email" placeholder="Your email" onChange={ this.handleChange } data-testid="input-gravatar-email" className="input" /> </div> <div className="button-forms"> <button disabled={ isDisabled } type="submit" data-testid="btn-play" className="button" > Play </button> <Link to="/settings"> <button type="button" data-testid="btn-settings" className="button"> Settings </button> </Link> </div> </div> </form> </div> </div> </div> ); } } const mapDispatchToProps = (dispatch) => ({ sendUser: (dataUser) => dispatch(login(dataUser)), getToken: () => dispatch(handleToken()), }); Login.propTypes = { sendName: PropTypes.func, }.isRequired; export default connect(null, mapDispatchToProps)(Login);
/** * Copyright 2009 Society for Health Information Systems Programmes, India (HISP India) * * This file is part of Inventory module. * * Inventory module is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Inventory module 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Inventory module. If not, see <http://www.gnu.org/licenses/>. * */ var EVT = { ready : function() { /** * Page Actions */ var enableCheck = true; var pageId = jQuery("form").attr("id"); if(enableCheck && jQuery("form").attr("id") != undefined && pageId != null && pageId != undefined && eval("CHECK." + pageId)) { eval("CHECK." + jQuery("form").attr("id") + "()"); } jQuery('.date-pick').datepicker({yearRange:'c-30:c+30', dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true}); /** * Ajax Indicator when send and receive data */ if(jQuery.browser.msie) { jQuery.ajaxSetup({cache: false}); } } }; var CHECK = { inventoryStore : function() { var validator = jQuery("#inventoryStore").validate( { event : "blur", rules : { "name" : { required : true}, "code" : { required : true}, "role" : { required : true}, "isDrug" : { required : true} } }); }, drugCategory : function() { var validator = jQuery("#drugCategory").validate( { event : "blur", rules : { "name" : { required : true} } }); }, drugUnit : function() { var validator = jQuery("#drugUnit").validate( { event : "blur", rules : { "name" : { required : true} } }); }, drugFormulation : function() { var validator = jQuery("#drugFormulation").validate( { event : "blur", rules : { "name" : { required : true}, "dozage" : { required : true} } }); }, drugForm : function() { //jQuery("#drugCore").autocomplete({source: 'autoCompleteDrugCoreList.form', minLength: 3 } ); jQuery("#drugCore").autocomplete('autoCompleteDrugCoreList.form', { minChars: 3 , delay:1000, scroll: true}); var validator = jQuery("#drugForm").validate( { event : "blur", rules : { "name" : { required : true}, "category" : { required : true}, "unit" : { required : true}, "drugCore" : { required : true}, "formulations" : { required : true}, "attribute" : { required : true}, "reorderQty" : { required : true, number: true} } }); }, item : function() { var validator = jQuery("#item").validate( { event : "blur", rules : { "name" : { required : true}, "unit" : { required : true}, "subCategory" : { required : true}, "attribute" : { required : true}, "reorderQty" : { required : true, number: true} } }); }, itemCategory : function() { var validator = jQuery("#itemCategory").validate( { event : "blur", rules : { "name" : { required : true} } }); }, itemSubCategory : function() { var validator = jQuery("#itemSubCategory").validate( { event : "blur", rules : { "name" : { required : true}, "code" : { required : true}, "categoryId" : { required : true} } }); }, itemUnit : function() { var validator = jQuery("#itemUnit").validate( { event : "blur", rules : { "name" : { required : true} } }); }, itemSpecification : function() { var validator = jQuery("#itemSpecification").validate( { event : "blur", rules : { "name" : { required : true} } }); },formFinishReceipSlip : function() { var validator = jQuery("#formFinishReceipSlip").validate( { event : "blur", rules : { "description" : { required : true} } }); }, createAccountIssueDrug : function() { var validator = jQuery("#createAccountIssueDrug").validate( { event : "blur", rules : { "accountName" : { required : true} } }); }, receiptDrug : function() { //jQuery("#drugName").autocomplete({source: 'autoCompleteDrugList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); jQuery("#drugName").autocomplete('autoCompleteDrugList.form', { minChars: 3 , delay:1000, scroll: true}); var validator = jQuery("#receiptDrug").validate( { event : "blur", rules : { "category" : { required : true}, "drugId" : { required : true}, "formulation" : { required : true}, "batchNo" : { required : true}, "companyName" : { required : true}, "dateManufacture" : { required : true}, "quantity" : { required : true,digits : true,min : 1}, "unitPrice" : { required : true,number : true,min : 0}, "VAT" : { required : true,number : true,min : 0}, "dateExpiry" : { required : true}, "receiptDate" : { required : true} }, submitHandler: function(form) { var check =(jQuery("#dateManufacture").datepicker("getDate") < jQuery("#dateExpiry").datepicker("getDate")); var check1 =(jQuery("#dateManufacture").datepicker("getDate") < jQuery("#receiptDate").datepicker("getDate")); if(check && check1){ form.submit(); }else{ alert('Please make sure manufacture date < expiry date,manufacture date < receipt date'); } } }); }, receiptItem : function() { //jQuery("#itemName").autocomplete({source: 'autoCompleteItemList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); var validator = jQuery("#receiptItem").validate( { event : "blur", rules : { "category" : { required : true}, "itemId" : { required : true}, "specification" : { required : true}, "quantity" : { required : true,digits : true,min : 1}, "unitPrice" : { required : true,number : true,min : 0}, "VAT" : { required : true,number : true,min : 0}, "receiptDate" : { required : true} } }); }, subStoreIndentDrug : function() { //jQuery("#drugName").autocomplete({source: 'autoCompleteDrugList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); jQuery("#drugName").autocomplete('autoCompleteDrugList.form', { minChars: 3 , delay:1000, scroll: true}); var validator = jQuery("#subStoreIndentDrug").validate( { event : "blur", rules : { "drugId" : { required : true}, "formulation" : { required : true}, "quantity" : { required : true,digits : true} } }); }, subStoreIndentItem : function() { //jQuery("#itemName").autocomplete({source: 'autoCompleteItemList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); var validator = jQuery("#subStoreIndentItem").validate( { event : "blur", rules : { "category" : { required : true}, "itemId" : { required : true}, "specification" : { required : true}, "quantity" : { required : true,digits : true} } }); }, formMainStoreProcessIndent : function() { jQuery("#formMainStoreProcessIndent").validate(); }, formAddNameForPurchase : function() { var validator = jQuery("#formAddNameForPurchase").validate( { event : "blur", rules : { "indentName" : { required : true} } }); }, formIssueDrug : function() { //jQuery("#drugName").autocomplete({source: 'autoCompleteDrugList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); jQuery("#drugName").autocomplete('autoCompleteDrugList.form', { minChars: 3 , delay:1000, scroll: true}); var validator = jQuery("#formIssueDrug").validate( { event : "blur", rules : { "drugId" : { required : true}, "formulation" : { required : true} } }); }, formIssueDrugAccount : function() { //jQuery("#drugName").autocomplete({source: 'autoCompleteDrugList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); var validator = jQuery("#formIssueDrugAccount").validate( { event : "blur", rules : { "category" : { required : true}, "drugId" : { required : true}, "formulation" : { required : true} } }); }, formIssueItem : function() { //jQuery("#itemName").autocomplete({source: 'autoCompleteItemList.form?categoryId='+jQuery('#category').val(), minLength: 3 }); var validator = jQuery("#formIssueItem").validate( { event : "blur", rules : { "category" : { required : true}, "itemId" : { required : true}, "specification" : { required : true} } }); }, formCreateAccount : function() { var validator = jQuery("#formCreateAccount").validate( { event : "blur", rules : { "name" : { required : true} } }); }, findPatient : function() { jQuery('input#searchPatient').keypress(function(e) { if (e.keyCode == '13') { e.preventDefault(); ISSUE.onBlurPatient(jQuery('input#searchPatient')); } }); } }; /** * Pageload actions trigger */ jQuery(document).ready( function() { EVT.ready(); } );
const Fibnacci = require("./Modules/Fibonacci"); const readline = require('readline'); var rl = readline.createInterface({ input:process.stdin, output:process.stdout }); rl.question("请输入你想要的输出长度:",function(n){ console.log(Fibnacci(n)); })
import './style' import { urlFor } from '@kuba/router' import h from '@kuba/h' import Link from '@kuba/link' import text from '@kuba/text' function component () { return ( <text.Span className='createanaccount__logIn' master xxs>Already have an account? <Link href={urlFor('logIn')}>Log in</Link></text.Span> ) } export default component
$(document).ready(function () { function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) return c.substring(name.length,c.length); } return ""; } if(document.cookie!=''){ $("#rememberPassword").attr('checked','checked'); document.getElementById('loginEmail').value=getCookie('emailId'); document.getElementById('loginPassword').value=getCookie('password'); } $("#login").on('click',function () { let email=$("#loginEmail").val(); let password=$("#loginPassword").val(); let isRemember=$("#rememberPassword").is(":checked"); $.get(`/users/${email}`,function (ans) { //console.log(JSON.stringify(ans)); let user=ans; if(ans.length==0){ $("#loginPassword").val(''); let str = "<div class='alert alert-danger alert-dismissible' role='alert' style='font-size: 20px'>"+ "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>"+ "<span aria-hidden='true'>&times;</span>"+"</button>"+" WARNING&nbsp;!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Account does not exist</div>"; $("#test").empty(); $("#test").append(str); }else { //账号存在且信息正确 if(user.usrEmail==email&&user.usrPassword==password){ if(isRemember==true){ //记住密码并登录且跳到主页 document.cookie=`emailId=${email}; expires=18 Dec 2017 12:00:00 GMT`; document.cookie=`password=${password}; expires=18 Dec 2017 12:00:00 GMT`; }else { //清除cookies document.cookie=`emailId=${email}; expires=18 Dec 2016 12:00:00 GMT`; document.cookie=`password=${password}; expires=18 Dec 2016 12:00:00 GMT`; } $('#test').empty(); let str1 = "<div class='alert alert-success alert-dismissible' role='alert' style='font-size: 20px'>"+ "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>"+ "<span aria-hidden='true'>&times;</span>"+"</button>"+" SUCCESS&nbsp;!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Login successfully</div>"; $('#test').append(str1); $("#logAcount").empty(); let str=`<li><a href="/html/accountDetail.html"><span class="glyphicon glyphicon-user"></span> ${email}</a></li>`; str+=`<li><a href=""><span class="glyphicon glyphicon-log-out"></span> EXIT</a></li>` $("#logAcount").append(str); sessionStorage.setItem("emailId",email); $(location).attr('href','/html/home.html'); }else{ //密码信息错误 $("#loginPassword").val(''); $('#test').empty() let str = "<div class='alert alert-danger alert-dismissible' role='alert' style='font-size: 20px'>"+ "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>"+ "<span aria-hidden='true'>&times;</span>"+"</button>"+" WARNING&nbsp;!&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Password error</div>"; $('#test').append(str); } } }) }) })
var challengers = require('./challenge.js') function generateUUID() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random()*16)%16 | 0; d = Math.floor(d/16); return (c=='x' ? r : (r&0x3|0x8)).toString(16); }); return uuid; } exports.handler = function(event, context) { var userId = event.headers.Authorization; var recipientId = event.body.recipientId; var type = event.body.type; var fromDate = event.body.fromDate; var toDate = event.body.toDate; var forfeit = event.body.forfeit; var customizer = event.body.customizer; var data = { id: generateUUID(), challengerId: userId, recipientId: recipientId, type: type, fromDate: fromDate, toDate: toDate, forfeit: forfeit, customizer: customizer }; challengers.add(data, context); };
function reverseString(hello){ var reverse = "" for(var i = 0; i<hello.length; i++){ var char = hello[i]; reverse = char + reverse; } return reverse; } var hello = "Hello Bangladesh" var result = reverseString (hello); console.log(result);
import * as DXFSolidObjectRenderer2D from "../view/render2D/dxfSolidObjectRenderer2D"; import CustomComponent from "../core/customComponent"; import FeatureSet from "./featureSet"; import * as Basic from "./basic"; const registeredFeatureSets = {}; const typeStrings = {}; import * as Registry from "../core/registry"; // add more sets here! const requiredSets = { Basic: Basic }; registerSets(requiredSets); function registerSets(sets) { for (let key in sets) { let name = key; let set = sets[key]; let newSet = new FeatureSet(set.definitions, set.tools, set.render2D, set.render3D, name); Registry.featureSet = newSet; registeredFeatureSets[key] = newSet; Registry.featureDefaults[key] = newSet.getDefaults(); } } export function getSet(setString) { return registeredFeatureSets[setString]; } export function getDefinition(typeString, setString) { let set = getSet(setString); // console.log("Set:", set); if (set !== undefined || set !== null) { let def = set.getDefinition(typeString); return def; } else if (setString === "Custom") { return CustomComponent.defaultParameterDefinitions(); } else { return null; } } export function getTool(typeString, setString) { let set = getSet(setString); return set.getTool(typeString); } export function getRender2D(typeString, setString) { let set; if (setString === "Custom") { return DXFSolidObjectRenderer2D.renderCustomComponentFeature; } else { set = getSet(setString); return set.getRender2D(typeString); } } export function getRender3D(typeString, setString) { let set = getSet(setString); return set.getRender3D(typeString); } export function getComponentPorts(params, typeString, setString = "Basic") { let set = getSet(setString); return set.getComponentPorts(typeString); }
(function() { 'use strict'; angular.module('app.peratiende.directivas', [ ]).directive('peratiendecreate', peratiendeCreate) .directive('peratiendelist', peratiendeList) .directive('peratiendeupdate', peratiendeUpdate); function peratiendeCreate() { return { scope: {}, templateUrl: 'app/peratiende/create.html', restrict: 'EA', controller: 'PeratiendeCreateCtrl', controllerAs: 'vm' }; } function peratiendeList() { return { scope: {}, templateUrl: 'app/peratiende/list.html', restrict: 'EA', controller: 'PeratiendeListCtrl', controllerAs: 'vm' }; } function peratiendeUpdate() { return { scope: {}, templateUrl: 'app/peratiende/update.html', restrict: 'EA', controller: 'PeratiendeUpdateCtrl', controllerAs: 'vm' }; } })();
var fish = { Fish: function(){ this.realx = Math.random() * map.width; this.realy = Math.random() * map.height; this.xv= 0; this.yv= 0; this.xa= 0; this.ya= 0; this.x= 0; this.y= 0; this.space_out = Math.random() * 60; this.follower = Math.random() > 0.3; fish.fishes.push(this); // sounds fishy LERLERLERL return this; }, fishes: [], spawn: function(count){ if(!count) count = 1; for(var j = 0; j < count; j++) new fish.Fish(); }, step: function(){ for(var i = 0; i < fish.fishes.length; i++){ fish.fishes[i].step(); } }, render: function(){ for(var i = 0; i < fish.fishes.length; i++){ if(fish.fishes[i].x > viewport.x - 1 && fish.fishes[i].x < viewport.x + canvas.width + 1 && fish.fishes[i].y > viewport.y && fish.fishes[i].y < viewport.y + canvas.height) fish.fishes[i].render(); } } }; fish.Fish.prototype.render = function(){ context.fillStyle = "white"; context.fillRect(this.x - viewport.x - 1, this.y - viewport.y, 3, 1); }; fish.Fish.prototype.step = function(){ this.realx += this.xv; this.realy += this.yv; this.xv += this.xa; this.yv += this.ya; this.xv *= 0.99; // fish are slippery this.yv *= 0.90; this.xa *= 0.5; this.ya *= 0.5; var neighbour_count = 0; var neighbour_xv = 0; var neighbour_yv = 0; if(this.follower){ for(var i = Math.floor(Math.random() * 6); i < fish.fishes.length; i+=6){ if(Math.abs(this.realx - fish.fishes[i].realx) < 50 && Math.abs(this.realy - fish.fishes[i].realy) < 50 && Math.abs(fish.fishes[i].xv) > 0.1 && Math.abs(fish.fishes[i].yv) > 0.1){ neighbour_count += 1; neighbour_xv += fish.fishes[i].xv; neighbour_yv += fish.fishes[i].yv; } } if(neighbour_count != 0){ this.xa += ((neighbour_xv / neighbour_count) - this.xv)*Math.random(); this.ya += ((neighbour_yv / neighbour_count) - this.yv)*Math.random()/4; } } if(this.space_out <= 0){ this.xa = linear(Math.random(), 0, 1, -1, 1); this.ya = linear(Math.random(), 0, 1, -1, 1); this.space_out = Math.random() * 60 * ((this.follower)?30:10) } this.space_out -= 1; // swim away from the player if(Math.abs(player.x - this.x) < 30 && Math.abs(player.y - this.y) < 30){ this.xa = sign(this.x - player.x) * Math.random(); this.ya = sign(this.y - player.y) * Math.random(); } this.x = Math.floor(this.realx); this.y = Math.floor(this.realy); // collision detection if (this.x < 0) { this.xv *= -1; this.x = 0; this.realx = 0; } else if(this.x > map.width) { this.xv *= -1; this.x = map.width; this.realx = map.width; } if (this.y < 50) { this.yv *= -1; this.y = 50; this.realy = 50; } else if(this.y > map.height) { this.yv *= -1; this.y = map.height; this.realy = map.height; } };
const Validator = require("jsonschema").Validator; Validator.prototype.customFormats.isFunction = function (input) { return typeof input === "function"; }; Validator.prototype.customFormats.isFunctionOrString = function (input) { return typeof input === "function" || typeof input === "string"; }; Validator.prototype.customFormats.isFunctionOrRegexp = function (input) { return typeof input === "function" || input instanceof RegExp; }; let v = new Validator(); const Attribute = { id: "/Attribute", type: "object", required: ["type"], properties: { type: { // todo: only specific values type: ["string", "array"], // enum: ["string", "number", "boolean", "enum"], }, field: { type: "string", }, label: { type: "string", }, readOnly: { type: "boolean", }, required: { type: "boolean", }, cast: { type: "string", enum: ["string", "number"], }, default: { type: "any", format: "isFunctionOrString", }, validate: { type: "any", format: "isFunctionOrRegexp", }, get: { type: "any", format: "isFunction", }, set: { type: "any", format: "isFunction", }, }, }; const Index = { id: "/Index", type: "object", properties: { pk: { type: "object", required: true, properties: { field: { type: "string", required: true, }, facets: { type: ["array", "string"], minItems: 1, items: { type: "string", }, required: true, }, }, }, sk: { type: "object", required: ["field", "facets"], properties: { field: { type: "string", required: true, }, facets: { type: ["array", "string"], required: true, items: { type: "string", }, }, }, }, index: { type: "string", }, }, }; const Model = { type: "object", required: true, properties: { service: { type: "string", required: true, }, entity: { type: "string", required: true, }, table: { type: "string", required: true, }, version: { type: "string", }, attributes: { type: "object", patternProperties: { ["."]: { $ref: "/Attribute" }, }, }, indexes: { type: "object", minProperties: 1, patternProperties: { ["."]: { $ref: "/Index" }, }, }, filters: { $ref: "/Filters" }, }, }; const Filters = { id: "/Filters", type: "object", patternProperties: { ["."]: { type: "any", format: "isFunction", message: "Requires function", }, }, }; v.addSchema(Attribute, "/Attribute"); v.addSchema(Index, "/Index"); v.addSchema(Filters, "/Filters"); v.addSchema(Model, "/Model"); function validateModel(model = {}) { let errors = v.validate(model, "/Model").errors; if (errors.length) { throw new Error( errors .map((err) => { let message = `${err.property}`; switch (err.argument) { case "isFunction": return `${message} must be a function`; case "isFunctionOrString": return `${message} must be either a function or string`; case "isFunctionOrRegexp": return `${message} must be either a function or Regexp`; default: return `${message} ${err.message}`; } }) .join(", "), ); } } module.exports = { model: validateModel, };
/* Being a bald man myself, I know the feeling of needing to keep it clean shaven. Nothing worse that a stray hair waving in the wind. You will be given a string(x). Clean shaved head is shown as "-" and stray hairs are shown as "/". Your task is to check the head for stray hairs and get rid of them. You should return the original string, but with any stray hairs removed. Keep count of them though, as there is a second element you need to return: 0 hairs --> "Clean!" 1 hair --> "Unicorn!" 2 hairs --> "Homer!" 3-5 hairs --> "Careless!" >5 hairs --> "Hobo!" So for this head: "------/------" you should return: ["-------------", "Unicorn!"] */ function bald(x) { let counter = 0; let shavedHead = ""; let statement; for (let i = 0; i < x.length; i++) { let character = x[i]; if (character === "/") { counter++; shavedHead += "-"; } else { shavedHead += character; } } if (counter === 0) { statement = "Clean!"; } else if (counter === 1) { statement = "Unicorn!"; } else if (counter === 2) { statement = "Homer!"; } else if (counter >= 3 && counter <= 5) { statement = "Careless!"; } else { statement = "Hobo!"; } return [shavedHead, statement]; }
import React, { Component } from 'react'; import 'bulma/css/bulma.css'; import '../App.css'; class AddNewFoodForm extends Component { constructor(){ super(); this.state = { error: "", name: "", calories: 0, quantity: 0, image: "", } } handleSubmit(){ let { name, calories, quantity, image } = this.state; if(name === '') return this.setState({error:'Empty name'}); if(calories === '') return this.setState({error:'Empty calories'}); if(image === 0) return this.setState({error:'Empty Image'}); this.setState({error: '', name:'', calories: 0, quantity: 0, image: ''}); this.props.foodReady({name, calories, quantity, image }); } render() { let { name, calories, quantity, image, error} = this.state; return ( <div> <p style={{color:"red"}}>{error}</p> <label>Food Name</label> <input type="text" value={name} onChange={(e) => this.setState({name:e.target.value})} /> <label>Calories</label> <input type="text" value={calories} onChange={(e) => this.setState({calories:e.target.value})}/> <label>Image</label> <input type="text" value={image} onChange={(e) => this.setState({image:e.target.value})}/> <button onClick={this.handleSubmit.bind(this)}>Add Food</button> </div> ) } } export default AddNewFoodForm;
const path = require(`path`); exports.createPages = ({ graphql, actions }) => { const { createPage } = actions; return new Promise((resolve, reject) => { const projectTemplate = path.resolve( 'src/templates/project.js' ); resolve( graphql( ` { allAirtable { edges { node { recordId data { slug } } } } } ` ).then(result => { if (result.error) { reject(result.error); } result.data.allAirtable.edges.forEach(edge => { createPage({ path: `${edge.node.data.slug}`, component: path.resolve(`./src/templates/project.js`), context: { recordId: edge.node.recordId } }); }); }) ); }); };
import React, {Component} from "react"; import {ScrollView, StyleSheet, TouchableOpacity, View} from "react-native"; import HeaderWithBackButton from "./HeaderWithBackButton"; import {getAuthedAPI} from "../api"; import {ListItem, Text} from "react-native-elements"; import strings from "../strings"; import PropTypes from "prop-types"; import Icon from "react-native-vector-icons/FontAwesome"; import {boundMethod} from "autobind-decorator"; import {Actions} from "react-native-router-flux"; class ProviderListItem extends Component { @boundMethod onTap() { Actions.push("viewProvider", { uuid: this.props.uuid }); } render(): React.ReactNode { return ( <TouchableOpacity style={styles.providerListItemTouchableOpacity} onPress={this.onTap} > <View style={styles.providerListItemView}> <Text style={{fontWeight: "600"}}>{this.props.name}</Text> <Icon name="chevron-right" /> </View> </TouchableOpacity> ); } } ProviderListItem.propTypes = { name: PropTypes.string, uuid: PropTypes.string } class ProviderList extends Component { constructor(props) { super(props); this.state = { providers: [], loading: true } } componentDidMount(): void { getAuthedAPI() .listProviders() .then((response) => { this.setState({ providers: response.providers, loading: false }) }); } render(): React.ReactNode { return ( <View style={{flex: 1}}> <HeaderWithBackButton headerText={strings.pages.selectProvider.headerText} /> {!this.state.loading ? <ScrollView style={{flex: 1}}> {this.state.providers.map((provider, i) => ( <ListItem key={i} Component={ProviderListItem} name={provider.full_name} uuid={provider.uuid} /> ))} </ScrollView> : <View> <Text>Loading please wait.</Text> </View> } </View> ); } } const styles = StyleSheet.create({ providerListItemTouchableOpacity: { borderBottomWidth: StyleSheet.hairlineWidth, paddingTop: 20, paddingBottom: 20 }, providerListItemView: { display: "flex", justifyContent: "space-between", flexDirection: "row", marginLeft: 15, marginRight: 15, alignItems: "center" } }); export default ProviderList;
const defaultState = { search_data:[] } export default (state=defaultState,action)=>{ switch(action.type){ case "SEARCH_ACT": let searchState = JSON.parse(JSON.stringify(state)); searchState.data=action.data; return searchState; } return state; }
import React, {Component} from "react"; import Grid from "@material-ui/core/Grid"; import Button from "@material-ui/core/Button"; import StatusGraphsGrid from "./StatusGraphsGrid"; class ServiceStatus extends Component { constructor(props) { super(props); this.state = { serviceData: {status: [], summary: [], service: {},}, isLoading: false, dashboard: props.dashboard, name: props.name, countdownValue: process.env.REACT_APP_REFRESH_RATE, }; } countdown() { this.setState({countdownValue: this.state.countdownValue-1}) if (this.state.countdownValue === 0) { this.fetchServiceStatusData() } } componentDidMount() { this.fetchServiceStatusData() this.interval = setInterval(() => this.countdown(), 1000) } componentWillUnmount() { clearInterval(this.interval) } fetchServiceStatusData() { const name = this.state.name; this.setState({isLoading: true}); let requestUrl = process.env.REACT_APP_QUOKKA_HOST + '/service/status?name=' + name + '&datapoints=' + process.env.REACT_APP_NUM_DATAPOINTS fetch(requestUrl) .then(res => res.json()) .then((data) => { console.log(data) this.setState({serviceData: data, isLoading: false}); this.setState({countdownValue: process.env.REACT_APP_REFRESH_RATE}) }) .catch((e) => { console.log(e) this.setState({countdownValue: process.env.REACT_APP_REFRESH_RATE}) }); } renderServices(dashboard) { dashboard.setState({show: "services"}) } render() { return ( <Grid container direction="column"> <Grid container direction="row" style={{paddingTop: '10px'}}> <Grid item style={{width: '15%', paddingLeft: '10px'}}> <b>SERVICE NAME</b>:<br/>{this.state.serviceData.service.name} <br/><br/> <b>TARGET</b>:<br/>{this.state.serviceData.service.target} <br/><br/> <b>DATA</b>:<br/>{this.state.serviceData.service.data} <br/><br/> <b>LAST HEARD</b>:<br/>{this.state.serviceData.service.last_heard} <br/><br/> <br/><br/> <b>REFRESH IN</b>:<br/>{this.state.countdownValue} seconds <br/><br/> <br/><br/> <Button variant="contained" style={{width: '100%'}} onClick={() => this.renderServices(this.state.dashboard)}>Return to Services</Button> </Grid> <Grid item style={{width: '85%', paddingRight: '10px'}}> <StatusGraphsGrid data={this.state.serviceData.status} summary={this.state.serviceData.summary} sla={{availability: this.state.serviceData.service.sla_availability, response_time: this.state.serviceData.service.sla_response_time}}> </StatusGraphsGrid> </Grid> </Grid> </Grid> ); } } export default ServiceStatus
const schedule = require('node-schedule'); const stripe = require('stripe')(process.env.STRIPE_SKEY); const User = require('../models/User'); const { USER_STATUSES } = require('../models/User'); const mailer = require('../helpers/mailer'); const CHARGE_DEFAULT_AMOUNT = 51; const CHARGE_DIFF_DAYS = 7; const CHARGE_TIMEOUT_DAYS = 1; function chargeUser(user, { amount }) { const promises = []; user.cards.forEach((cardId) => { promises.push(stripe.charges.create({ amount, currency: 'usd', customer: user.customer, source: cardId, description: 'Charge for jenny.rosen@example.com', })); }); return Promise .all(promises) .then(async () => { await user.set({ status: { code: USER_STATUSES.SUCCESS } }); await user.save(); return user; }); } function createChargeAfter24H(user) { const date = new Date(); date.setDate(date.getDate() + CHARGE_TIMEOUT_DAYS); schedule.scheduleJob(date, () => { chargeUser(user).catch(() => user.remove()); }); } function isCanCharge(user) { const { code, date } = user.status; const diffDate = Math.floor(new Date() - date) / (60 * 60 * 24 * 1000); if (code === USER_STATUSES.SUCCESS || code === USER_STATUSES.FAILED) { return diffDate >= CHARGE_DIFF_DAYS; } return true; } exports.postCharge = async (req, res, next) => { const { amount = CHARGE_DEFAULT_AMOUNT } = req.body; try { const users = await User.find({}); if (!users.length) { return res.status(400).json({ message: 'No users yet' }); } await Promise.all(users.map(async (user) => { if (!user.cards.length) { return user.remove(); } if (!isCanCharge(user)) { return; } try { await chargeUser(user, { amount }); } catch (err) { mailer.sendMail({ to: user.email, subject: 'Error during charge', message: 'An error occurred during сharge. We will try again in 24 hours', }); createChargeAfter24H(user); user.set({ status: { code: USER_STATUSES.FAILED } }); } })); res.status(200).json({ message: 'successful сharged' }); } catch (err) { next(err); } };
const getSchema = require('../../src/lib/get-schema'); const schema = { type: 'string' }; test('should return the first type if there is content', () => { expect( getSchema({ requestBody: { content: { 'application/json': { schema, }, 'text/xml': { schema: { type: 'number' }, }, }, }, }), ).toEqual({ type: 'application/json', schema }); expect( getSchema({ requestBody: { content: { 'text/xml': { schema, }, 'application/json': { schema: { type: 'number' }, }, }, }, }), ).toEqual({ type: 'text/xml', schema }); }); test('should return undefined', () => { expect(getSchema({})).toBe(undefined); });
import logo from './logo.svg'; import './App.css'; import {Button, TextField} from '@mui/material' import { useState } from 'react'; import { supplyChainDeliveryMan, supplyChainWareHouse } from './config/ethersUtil'; import { deliveryManAddress, receiverAddress } from './config/vars'; function App() { const [state, setState] = useState({ cid: "", cid2: "", status: 2 }) const onChangeInputFields = (e) => { setState({...state, [e.target.name]: e.target.value}) } const receiveByWareHouse = () => { supplyChainWareHouse.receiveByWareHouse(state.cid).then(res => { console.log(res) supplyChainWareHouse.productStatus(state.cid).then(res => { setState({...state, status: Number(res)}) }) }) } const readyForDelivery = () => { supplyChainWareHouse.makeReadyForDelivery(state.cid, deliveryManAddress, receiverAddress).then(res => { console.log(res) supplyChainWareHouse.productStatus(state.cid).then(res => { setState({...state, status: Number(res)}) }) }) } const pickUpForDelivery = () => { supplyChainDeliveryMan.pickUpProduct(state.cid2).then(res => { console.log(res) supplyChainWareHouse.productStatus(state.cid2).then(res => { setState({...state, status: Number(res)}) }) }) } return ( <div className="App"> <TextField id="filled-basic" label="Product Cid" variant="filled" name = "cid" value = {state.cid} onChange = {onChangeInputFields}/> <Button onClick = {receiveByWareHouse} disabled = {state.status !== 2}>Receive by WareHouse</Button> <Button onClick = {readyForDelivery} disabled = {state.status !== 3}>Product Ready For Delivery</Button> <br /> <TextField id="filled-basic" label="Product Cid" variant="filled" name = "cid2" value = {state.cid2} onChange = {onChangeInputFields}/> <Button onClick = {pickUpForDelivery} disabled = {state.status !== 4}>Pick up for delivery</Button> </div> ); } export default App;
'use strict'; const fs = require('fs'); const readline = require('readline'); const rs = fs.ReadStream('./popu-pref.csv'); const rl = readline.createInterface({ 'input': rs, 'output': {} }); const prefectureDataMap = new Map(); // key: 都道府県名 value: 集計データのオブジェクト rl.on('line', (line) => { const columns = line.split(','); const year = columns[0]; const prefecture = columns[2]; const population = columns[7]; if (year === '2010' || year === '2015') { let value = prefectureDataMap.get(prefecture); if (!value) { value = { population_2010: 0,//2010年の人口 population_2015: 0,//2015年の人口 ratio_2010To2015: null//2015年人口の2010年人口に対する比 }; } if (year === '2010') { value.population_2010 += parseInt(population); } if (year === '2015') { value.population_2015 += parseInt(population); } prefectureDataMap.set(prefecture, value); } }); rl.on('close', () => { for (let [key, value] of prefectureDataMap) { value.ratio_2010To2015 = value.population_2015 / value.population_2010; } const rankingArray = Array.from(prefectureDataMap).sort((pair1, pair2) => { return pair2[1].ratio_2010To2015 - pair1[1].ratio_2010To2015; }); const rankingStrings = rankingArray.map(([key, value]) => { return key + ': ' + value.population_2010 + '=>' + value.population_2015 + ' 変化率:' + value.ratio_2010To2015; }); console.log(rankingStrings); });
import React from 'react'; import Header from './header'; import Login from './login'; import Dashboard from './dashboard'; import ModifyProfile from './modify-profile'; import SwitchProfile from './switch-profile'; import CreatePost from './create-post'; import Settings from './settings'; import ViewPost from './view-post'; import ViewComment from './view-comment'; export default class App extends React.Component { constructor(props) { super(props); this.state = { viewStack: [{ name: 'login', params: {} }], profile: null, posts: [], error: null }; this.abortCon = new AbortController(); } login(user, pass) { fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user, pass }), signal: this.abortCon.signal }).then(res => res.json()) .then(data => { this.pushView('dashboard'); this.setState({ profile: data.profile }); }).catch(err => console.error(err)); } logout() { fetch('/api/logout', { signal: this.abortCon.signal }) .then(() => { this.setState({ viewStack: [{ name: 'login', params: {} }], profile: null, posts: [] }); }).catch(err => console.error(err)); } fetchProfiles() { return fetch('/api/profiles', { signal: this.abortCon.signal }) .then(res => res.json()) .catch(err => console.error(err)); } modifyProfile(data) { const formData = new FormData(); for (const key in data) formData.append(key, data[key]); fetch('/api/profile/modify', { method: 'PATCH', body: formData, signal: this.abortCon.signal }).then(res => res.json()) .then(data => { this.setState({ profile: data }); this.resetToDashboard(); }).catch(err => console.error(err)); } createProfile() { fetch('/api/profile/create', { method: 'POST', signal: this.abortCon.signal }).then(res => res.json()) .then(data => this.setState({ profile: data })) .catch(err => console.error(err)); } setCurrentProfile(index) { fetch(`/api/profile/${index}`, { signal: this.abortCon.signal }) .then(res => res.json()) .then(data => { this.setState({ profile: data }); this.resetToDashboard(); }).catch(err => console.error(err)); } deleteProfile(index) { fetch(`/api/profile/${index}`, { method: 'DELETE', signal: this.abortCon.signal }).then(() => this.setCurrentProfile(0)) .catch(err => console.error(err)); } fetchAccounts() { return fetch('/api/accounts', { signal: this.abortCon.signal }) .then(res => res.json()) .catch(err => console.error(err)); } linkAccount(platform) { fetch(`/api/account/link/${platform}`, { signal: this.abortCon.signal }) .then(res => res.json()) .then(data => window.open(data.url, '_blank')) .catch(err => console.error(err)); } removeAccount(index) { fetch(`/api/account/${index}`, { method: 'DELETE', signal: this.abortCon.signal }).catch(err => console.error(err)); } createLink(index) { fetch(`/api/link/${index}`, { method: 'POST', signal: this.abortCon.signal }).catch(err => console.error(err)); } deleteLink(index) { fetch(`/api/link/${index}`, { method: 'DELETE', signal: this.abortCon.signal }).catch(err => console.error(err)); } fetchPosts() { fetch('/api/posts', { signal: this.abortCon.signal }) .then(res => res.json()) .then(data => this.setState({ posts: data })) .catch(err => console.error(err)); } createPost(data) { const formData = new FormData(); for (const key in data) formData.append(key, data[key]); fetch('/api/post', { method: 'POST', body: formData, signal: this.abortCon.signal }).then(res => res.json()) .then(data => { this.setState({ posts: [...this.state.posts, data] }); this.resetToDashboard(); this.pushView('post', { post: data, index: this.state.posts.length - 1, canPublish: true }); }).catch(err => console.error(err)); } deletePost(index) { fetch(`/api/post/${index}`, { method: 'DELETE', signal: this.abortCon.signal }).then(() => { this.setState(state => { state.posts.splice(index, 1); return state; }); this.resetToDashboard(); }).catch(err => console.error(err)); } fetchPublications(index) { return fetch(`/api/post/${index}/publications`, { signal: this.abortCon.signal }) .then(res => res.json()) .catch(err => console.error(err)); } publishPost(index) { return fetch(`/api/post/publish/${index}`, { method: 'POST', signal: this.abortCon.signal }) .then(() => this.setState(state => { state.posts[index].isPublished = true; return state; })).catch(err => console.error(err)); } toggleLike(accountIndex, id, value) { return fetch('/api/comment/like', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ accountIndex, id, value }), signal: this.abortCon.signal }).catch(err => console.error(err)); } publishReply(accountIndex, id, value) { return fetch('/api/comment/reply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ accountIndex, id, value }), signal: this.abortCon.signal }).then(res => res.json()) .catch(err => console.error(err)); } healthCheck() { fetch('/api/health-check', { signal: this.abortCon.signal }) .then(() => this.setState({ error: false })) .catch(err => this.setState({ error: err })); } pushView(name, params = {}) { this.setState(state => { state.viewStack.push({ name, params }); return state; }); } popView() { this.abortCon.abort(); this.abortCon = new AbortController(); if (this.peekView().name === 'dashboard') return this.logout(); this.setState(state => { state.viewStack.pop(); return state; }); } peekView() { return this.state.viewStack.length ? this.state.viewStack.slice(-1)[0] : {}; } resetToDashboard() { this.setState({ viewStack: [ { name: 'login', params: {} }, { name: 'dashboard', params: {} } ] }); } componentDidMount() { this.healthCheck(); } render() { let page = null; switch (this.peekView().name) { case 'login': page = ( <Login login={(user, pass) => this.login(user, pass)}/> ); break; case 'dashboard': page = ( <Dashboard profile={this.state.profile} posts={this.state.posts} viewModifyProfile={() => this.pushView('profile')} viewSwitchProfile={() => this.pushView('profiles')} viewCreatePost={() => this.pushView('create post')} viewSettings={() => this.pushView('settings')} viewViewPost={params => this.pushView('post', params)} fetchPosts={() => this.fetchPosts()} fetchAccounts={() => this.fetchAccounts()}/> ); break; case 'profile': page = ( <ModifyProfile profile={this.state.profile} resetToDashboard={() => this.resetToDashboard()} fetchAccounts={() => this.fetchAccounts()} modifyProfile={data => this.modifyProfile(data)} createLink={index => this.createLink(index)} deleteLink={index => this.deleteLink(index)}/> ); break; case 'profiles': page = ( <SwitchProfile viewModifyProfile={() => this.pushView('profile')} resetToDashboard={() => this.resetToDashboard()} fetchProfiles={() => this.fetchProfiles()} createProfile={() => this.createProfile()} setCurrentProfile={index => this.setCurrentProfile(index)} deleteProfile={index => this.deleteProfile(index)}/> ); break; case 'create post': page = ( <CreatePost createPost={data => this.createPost(data)}/> ); break; case 'settings': page = ( <Settings fetchAccounts={() => this.fetchAccounts()} linkAccount={platform => this.linkAccount(platform)} removeAccount={index => this.removeAccount(index)}/> ); break; case 'post': // eslint-disable-next-line no-case-declarations const { post, index, canPublish } = this.peekView().params; page = ( <ViewPost post={post} canPublish={canPublish} viewViewComment={params => this.pushView('comment', params)} deletePost={() => this.deletePost(index)} publishPost={() => this.publishPost(index)} fetchPublications={() => this.fetchPublications(index)} toggleLike={(accountIndex, id, value) => this.toggleLike(accountIndex, id, value)}/> ); break; case 'comment': // eslint-disable-next-line no-case-declarations const { comment, replies } = this.peekView().params; page = ( <ViewComment comment={comment} replies={replies} viewViewComment={params => this.pushView('comment', params)} toggleLike={(accountIndex, id, value) => this.toggleLike(accountIndex, id, value)} publishReply={(accountIndex, id, value) => this.publishReply(accountIndex, id, value)}/> ); break; default: break; } if (this.state.error === null) { return ( <h2>Loading...</h2> ); } else if (this.state.error) { return ( <h2>An error has occured.</h2> ); } return ( <div className="app container bg-transparent mx-auto mb-5 pb-5"> {this.peekView().name !== 'login' && ( <Header name={this.peekView().name} popView={() => this.popView()} /> )} {page} </div> ); } }
$(document).ready(function() { adminicaUi(); adminicaForms(); adminicaMobile(); adminicaDataTables(); adminicaCalendar(); adminicaCharts(); adminicaGallery(); adminicaWizard(); adminicaVarious(); }); $(window).load(function(){ adminicaInit(); }); function pjaxToggle() { if ( $.cookie('pjax_on') === "true" ){ $('#pjax_switch #dynamic_on').trigger("click"); $("a.pjax").addClass("pjax_on"); } }
import _ from 'romanize'; const transform = (numbers) => { if (numbers === 10) { return "X"; } }; const transformRomanize = (numbers) => { return _(numbers); } export { transform, transformRomanize }
const arr = []; console.log(`현재 arr : ${arr}`) setTimeout(() => { console.log("데이터를 1개 추가합니다. push()") arr.push("오은하"); console.log(`현재 arr : ${arr}`) }, 1000); setTimeout(() => { console.log("데이터를 1개 추가합니다. push()") arr.push("정예림"); console.log(`현재 arr : ${arr}`) }, 2000); setTimeout(() => { console.log("데이터를 1개 추가합니다. push()") arr.push("홍민기"); console.log(`현재 arr : ${arr}`) }, 3000);
var sites = require('./shuffle.js') var images = require('./images.js') var menu = require('./menu.js') var overlay = require('./overlay.js') sites.shuffleSites() images.handleImagesLoad() menu.addListeners() overlay.addListeners('[info]', '[info-button]')
const siteName = 'WEBNOWNG'; const phoneNumbers = ['08138754586', '07018382371']; const email = 'info@example.com'; const address = '20 Allen Avenue, Ikeja, Lagos State.'; const social = { facebook:'https://www.facebook.com/IBM/', twitter: 'https://twitter.com/IBM', instagram: 'https://www.instagram.com/ibm/' } module.exports = {siteName, phoneNumbers, address, social, email};
import React, { Component, Fragment } from 'react'; //import Dropdown from 'react-dropdown'; import 'react-dropdown/style.css'; import Content from './Content'; class BodyContainer extends Component { constructor() { super(); this.state = { usersData: null, currentContainerView:'' }; } //GET Fetch call for all of users 1's Data...may need to adjust this on AUTH setup componentDidMount() { fetch('http://localhost:3000/api/v1/users/1') .then(response => response.json()) .then(usersData => this.setState({ usersData })); } //based on users input on relationship drop down screen this function set's state to update to the appropriate view. relationshipView = (event) =>{ this.setState({ currentContainerView: event.value }) } //function to call render of EditContactForm handleEditClick =() =>{ this.setState({ currentContainerView: "edit" }) } //callback function to setState of usersData to reflect the usersData minus the deleted object onDelete = (deletedCard) =>{ var filtContacts = this.state.usersData.contacts.filter(contact=>{ return contact.id !== deletedCard.id }) this.setState({ usersData: {...this.state.usersData, contacts:filtContacts}, currentContainerView:deletedCard.category }) } onDeleteEvent = (deletedEvent) =>{ console.log(deletedEvent) var filtEvents = this.state.usersData.events.filter(event=>{ return event.id !== deletedEvent }) console.log(filtEvents) this.setState({ usersData: {...this.state.usersData, events:filtEvents} }) } onAdd = (addedContact) =>{ var addContacts = this.state.usersData.contacts addContacts.push(addedContact) this.setState({ usersData: {...this.state.usersData, contacts:addContacts}, currentContainerView:`${addedContact.category}` }) } onAddEvent = (addedEvent) =>{ console.log(addedEvent) var addEvents = this.state.usersData.events addEvents.push(addedEvent) console.log(addEvents) this.setState({ usersData: {...this.state.usersData, events:addEvents} }) console.log(this.state.usersData) } onEdit = (editedContact) =>{ var editContacts = this.state.usersData.contacts editContacts.forEach(editcontact=>{ if (editcontact.id === editedContact.id){ var a = editContacts.indexOf(editcontact) return editContacts[a] = editedContact } }) this.setState({ usersData: {...this.state.usersData, contacts:editContacts}, currentContainerView:`${editedContact.category}` }) } onUpdateLastEventDay = (updatedEvent,currentCard) =>{ console.log(updatedEvent) console.log(currentCard) var updateContactsLastEvent = this.state.usersData.events updateContactsLastEvent.forEach(contactToUpdate=>{ if (contactToUpdate.id === updatedEvent.id){ return currentCard.last_event_date = updatedEvent.event_date } }) this.setState({ usersData: {...this.state.usersData, events:updateContactsLastEvent}, // currentContainerView:`${currentCard.category}` }) fetch(`http://localhost:3000/api/v1/contacts/${currentCard.id}`, { method: "PATCH", headers: { "Content-type" : "application/json" }, body: JSON.stringify({ last_event_date: currentCard.last_event_date, status: updatedEvent.status }) }) fetch(`http://localhost:3000/api/v1/events/${updatedEvent.id}`, { method: "PATCH", headers: { "Content-type" : "application/json" }, body: JSON.stringify({ status: updatedEvent.status }) }) } contactView = (contactObject) =>{ this.setState({ currentContainerView: contactObject }) } handleAddButton = () =>{ this.setState({ currentContainerView: "add contact" }) } handleClick = (event) =>{ this.setState({ currentContainerView:event.currentTarget.innerText }) } render(){ /*const options = ['Select a Relationship Type','Family', 'Friends', 'Associates']*/ return( <Fragment> <div className="ui five item menu" > <button className="item" onClick={this.handleClick}>Home</button> <button className="item" onClick={this.handleClick}>Family</button> <button className="item" onClick={this.handleClick}>Friends</button> <button className="item" onClick={this.handleClick}>Associates</button> <button className="item" onClick={this.handleClick}>Add Contact</button> </div> {/*<Dropdown options={options} onChange={this.relationshipView} placeholder="Select a Relationship Type" value={this.state.currentContainerView}/>*/} <Content relationshipView={this.state.currentContainerView} userInfo={this.state.usersData} contactView={this.contactView} onDelete={this.onDelete} onAdd={this.onAdd} onAddEvent={this.onAddEvent} onDeleteEvent={this.onDeleteEvent} onEdit={this.onEdit} handleEditClick={this.handleEditClick} onUpdateLastEventDay={this.onUpdateLastEventDay} optimisticRemove={this.optimisticRemove}/> {/* <button className="ui black button" onClick={this.handleAddButton} >Add A Connection</button>*/} </Fragment> ) } } export default BodyContainer;
import { shallow } from 'enzyme'; import HeaderTabs from './../../../src/components/HeaderTabs'; describe('HeaderTabs-spec', () => { // TODO add click test, add style test describe('render', () => { it('should render HeaderTabs', () => { const wrapper = shallow(<HeaderTabs />); expect( wrapper.children().first().text() ).to.eql('<FlatButton />'); expect( wrapper.children().at(1).text() ).to.eql('<FlatButton />'); }); }); });
goog.provide('SB.Camera'); goog.require('SB.SceneComponent'); SB.Camera = function(param) { param = param || {}; SB.SceneComponent.call(this, param); this.active = param.active || false; var position = param.position || SB.Camera.DEFAULT_POSITION; this.position.copy(position); } goog.inherits(SB.Camera, SB.SceneComponent); SB.Camera.prototype.realize = function() { SB.SceneComponent.prototype.realize.call(this); this.addToScene(); if (this.active) { SB.Graphics.instance.camera = this.object; } } SB.Camera.prototype.setActive = function(active) { this.active = active; if (this._realized && this.active) { SB.Graphics.instance.camera = this.object; } } SB.Camera.prototype.lookAt = function(v) { this.object.lookAt(v); } SB.Camera.DEFAULT_POSITION = new THREE.Vector3(0, 0, 10);
function isf(imghash){ if(!imghash){ return ""; } var s1 = imghash.slice(0,1); var s2 = imghash.slice(1,3); var s3 = imghash.slice(3); var s4 = imghash.slice(32); return "http://fuss10.elemecdn.com/"+s1+"/"+s2+"/"+s3+"."+s4; } function addPrefix(part){ if(!part){ return ""; } return "//fuss10.elemecdn.com"+part; } function distanceFilter(dis){ return (dis/1000).toFixed(2); } function blured(u){ return u+"?imageMogr/thumbnail/!40p/blur/50x40/"; } export {isf,addPrefix,distanceFilter,blured}
import {getResourse} from "../services/services"; function cards() { //Меню рационов class OneMenuTabElemet { constructor(src, menuName, menuText, prise, alt, parentSelector, ...classes) { this.src = src; this.menuName = menuName; this.menuText = menuText; this.prise = prise; this.alt = alt; this.classes = classes; this.parent = document.querySelector(parentSelector); this.transfer = 27; this.changeToUAH(); } changeToUAH() { this.prise = this.prise * this.transfer; } render() { const element = document.createElement('div'); if (this.classes.length === 0) { this.element = 'menu__item'; element.classList.add(this.element); } else { this.classes.forEach(className => element.classList.add(className)); } element.innerHTML = ` <img src="${this.src}" alt="${this.alt}"> <h3 class="menu__item-subtitle">Меню "${this.menuName}"</h3> <div class="menu__item-descr">${this.menuText}</div> <div class="menu__item-divider"></div> <div class="menu__item-price"> <div class="menu__item-cost">Цена:</div> <div class="menu__item-total"><span>${this.prise}</span> грн/день</div> </div>`; this.parent.append(element); } } getResourse('http://localhost:3000/menu'). then (data =>{ data.forEach(({img ,title ,descr ,price, altimg}) => { new OneMenuTabElemet(img , title , descr , price , altimg , ".menu .container").render(); }); }); // axios.get('http://localhost:3000/menu') // .then(data => { // data.data.forEach(({ img, title, descr, price, altimg }) => { // new OneMenuTabElemet(img, title, descr, price, altimg, ".menu .container").render(); // }); // }); } export default cards;
import React, { Component } from 'react'; import '../App.css'; class componentwillMount extends Component { componentWillMount() { console.log("Hey this is Ronald Namwanza, am happy to be a software Engineer") } render() { return ( <div className="page"> <h1>React: Use the Lifecycle Method </h1> <p className="cycle"> The componentWillMount() method is called before the render() method when a component is being mounted to the DOM. </p> <h3>Here is a list of some of the main lifecycle methods:</h3> <p className="cycle"> componentWillMount() </p> <p className="cycle"> componentDidMount()  Use componentDidMount when you want to set something up </p> <p className="cycle"> componentWillReceiveProps() </p> <p className="cycle"> shouldComponentUpdate() </p> <p className="cycle"> componentWillUpdate() </p> <p className="cycle"> componentDidUpdate() </p> <p className="cycle"> componentWillUnmount()  Use componentWillUnmount when you need to clear that something, your event listener. </p> </div> ); } } export default componentwillMount;
/* FASTGAP https://github.com/FastGap/FastGap */ (function (window) { // page load object var PageLoad = window.PageLoad = { ajxHandle: null }; //load ajax PageLoad.load = function (page) { PageLoad.ajxHandle = $.get("pages/" + page, PageLoad.success); }; //sucess load PageLoad.success = function (content) { if (FG.currentController != null) { // unset everything in the previous controller // prevent memory leaks FG.currentController.destroy(); } // add content in #page FG.$contentLoad.html(content); // create new controller switch (Navigator.currentPage) { case 'home.html': FG.currentController = new HomeController(); break; case 'page1.html': FG.currentController = new Page1Controller(); break; case 'connection.html': FG.currentController = new ConnectionController(); break; case 'device.html': FG.currentController = new DeviceController(); break; case 'notification.html': FG.currentController = new NotificationController(); break; case 'accelerometer.html': FG.currentController = new AccelerometerController(); break; case 'geolocation.html': FG.currentController = new GeolocationController(); break; case 'localstorage.html': FG.currentController = new LocalStorageController(); break; case 'appinbrowser.html': FG.currentController = new AppInBrowserController(); break; case 'contacts.html': FG.currentController = new ContactsController(); break; case 'json.html': FG.currentController = new JsonController(); break; case 'camera.html': FG.currentController = new CameraController(); break; case 'nativeevents.html': FG.currentController = new NativeEvents(); break; case 'carrousel.html': FG.currentController = new CarrouselController(); break; default: alert('No controller found.'); break; } // once new controller created, initialize it if (FG.currentController != null) { FG.currentController.initialize(); } //hide my menu Transition.hideMenu(); //remove transition in my app FG.$content.removeClass(Transition.class); }; })(window);
alert("Todos estan Muertos"); var Arma = prompt("Mira, un almacen, al parecer solo hay un hacha y una pistola, rapido toma un objeto"); var numeroAlazar = Math.round(Math.random()); alert("Un Zombie salvaje aparece, rapido utiliza tu " + " " + Arma); if(numeroAlazar === 0 ){ alert("Tu "+ Arma + " fallo y el Zombie te hizo suyo. Perdiste!!!"); } else if (numeroAlazar === 1 ){ alert("Perfecto que le haz dado un critico con tu " + " " + Arma + ". Sigues Vivo!!"); }
/* You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that "the" is doubled in the first sentence of this description? As as aS you can see, it's not easy to spot those errors, especially if words differ in case, like "as" at the beginning of the sentence. Write a function countAdjacentPairs that counts the number of adjacent pairs in a string. It should be case-insensitive. A word in this kata is a sequence of non-whitespace characters enclosed by whitespace, so the string "dog dog." contains the two words "dog" and "dog.", which differ. The occurence of two or more equal words next after each other count as one. Example: countAdjacentPairs "dog cat" == 0 countAdjacentPairs "dog dog cat" == 1 countAdjacentPairs "apple dog cat" == 0 countAdjacentPairs "pineapple apple dog cat" == 0 countAdjacentPairs "apple apple dog cat" == 1 countAdjacentPairs "apple dog apple dog cat" == 0 countAdjacentPairs "dog dog dog dog dog dog" == 1 countAdjacentPairs "dog dog dog dog cat cat" == 2 countAdjacentPairs "cat cat dog dog cat cat" == 3 //returns 0 countAdjacentPairs('') // returns 1 countAdjacentPairs('cat dog dog') // returns 1 (The first pair has been matched, and will be ignored from then on). countAdjacentPairs('dog dog dog') // returns 2 countAdjacentPairs('cat cat dog dog cat') */ function countAdjacentPairs(searchString) { let counter = 0; let words = searchString.toLowerCase().split(' '); if (words.length <= 1) { return 0; } let arr = []; for (let i = 0; i < words.length - 1; i++) { let curr = words[i]; let folo = words[i+1]; if (arr[0] === curr || curr === ' ') { continue; } if (arr[0] !== curr) { arr.pop(); } if (curr === folo) { arr.push(curr); counter += 1; i += 1; } } return counter; }
import React, {Component} from 'react'; import style from './index.module.scss'; class Point extends Component { render() { const cl = [style.default]; if (this.props.active) { cl.push(style.active); } return ( <div className={cl.join(` `)}> Point </div> ); } } export default Point;
import './style.css'; import React, { useEffect, useState } from 'react'; import { db } from './../../db'; import firebase from 'firebase/app'; import validator from 'validator'; import ReCAPTCHA from 'react-google-recaptcha'; export const FormMap = () => { const [name, setName] = useState(''); const [select, setSelect] = useState('bankéř'); const [email, setEmail] = useState(''); const [phone, setPhone] = useState(''); const [address, setAddress] = useState(''); const [comment, setComment] = useState(''); const [response, setResponse] = useState(''); const [coordinates, setCoordinates] = useState([]); const [town, setTown] = useState(''); const [recaptcha, setRecaptcha] = useState(false); const onChange = () => { setRecaptcha(true); }; const handleSubmit = (event) => { event.preventDefault(); if (responseEmail && name && comment && address && recaptcha === true) { db.collection('poradci') .add({ name: name, select: select, allowed: false, email: email, address: address, town: town, comment: comment, phone: phone, datumVytvoreni: firebase.firestore.FieldValue.serverTimestamp(), latitude: coordinates.latitude, longitude: coordinates.longitude, }) .then(() => { setResponse( `Formulář byl úspěšně odeslán, po schválení bude vložen do mapy.`, ); }) .catch(() => { setResponse(`Jejda, něco se nepovedlo. Zadej znovu.`); }); setName(''); setSelect(''); setEmail(''); setPhone(''); setAddress(''); setComment(''); } else { setResponse( 'Dopňte chybějící požadované údaje a zaškrtněte, že nejste robot.', ); } }; const [responseEmail, setResponseEmail] = useState(true); const validEmail = responseEmail !== true ? 'Zatejte platný email' : ''; useEffect(() => { setResponseEmail(validator.isEmail(email)); }, [email]); const [responsePhone, setResponsePhone] = useState(true); const validPhone = responsePhone !== true ? 'Zatejte platný telefon' : ''; useEffect(() => { setResponsePhone(validator.isMobilePhone(phone)); }, [phone]); useEffect(() => { let center = window.SMap.Coords.fromWGS84(14.1, 50.1); let m = new window.SMap(window.JAK.gel('m'), center); m.addDefaultLayer(window.SMap.DEF_BASE).enable(); m.addDefaultControls(); // naseptavac let inputEl = document.querySelector('#naseptavac'); let suggest = new window.SMap.Suggest(inputEl, { provider: new window.SMap.SuggestProvider({ updateParams: (params) => { /* tato fce se vola pred kazdym zavolanim naseptavace, params je objekt, staci prepsat/pridat klic a ten se prida do url */ let c = m.getCenter().toWGS84(); params.lon = c[0].toFixed(5); params.lat = c[1].toFixed(5); params.zoom = m.getZoom(); // omezeni pro celou CR params.bounds = '48.5370786,12.0921668|51.0746358,18.8927040'; // nepovolime kategorie, ale takto bychom mohli //params.enableCategories = 1; // priorita jazyku, oddelene carkou params.lang = 'cs,en'; }, }), }); suggest.addListener('suggest', (suggestData) => { // vyber polozky z naseptavace setTimeout(function () { /*alert(JSON.stringify(suggestData, null, 4));*/ setCoordinates({ latitude: suggestData.data.latitude, longitude: suggestData.data.longitude, }); setTown(suggestData.data.secondRow); }, 0); }); }, []); return ( <> <form className="form-map" onSubmit={handleSubmit}> <p className="required right">* Povinné údaje</p> <label className="form-map__select"> Osoba je: <select name="Vyber poradce" value={select} onChange={(event) => setSelect(event.target.value)} > <option value="bankéř">Pracovník banky</option> <option value="poradce">Finanční poradce</option> </select> </label> <label className="form-map__name"> Jméno bankéře/poradce <span className="required">*</span> </label> <input value={name} onChange={(event) => setName(event.target.value)} /> <div className="valid"> <label className="form-map__phone"> Telefonní kontakt bankéře/poradce </label> <span> {validPhone}</span> </div> <input value={phone} onChange={(event) => setPhone(event.target.value.trim())} /> <div className="valid"> <label className="form-map__email"> E-mail bankéře/poradce <span className="required">*</span> </label> <span> {validEmail}</span> </div> <input value={email} onChange={(event) => setEmail(event.target.value.trim())} /> <label className="form-map__address"> Zadej adresu <span className="required">*</span> </label> <input id="naseptavac" value={address} onChange={(event) => setAddress(event.target.value)} /> <div id="parent"> <div id="m"></div> </div> <label> Zadej komentář se zkušeností <span className="required">*</span> </label> <textarea className="form-map__comment" value={comment} onChange={(event) => setComment(event.target.value)} rows={5} /> <ReCAPTCHA sitekey="6LfeONEbAAAAALQzCl3o22xBWND0mj3UBERgzv7S" onChange={onChange} value={recaptcha} /> <button className="button--large">Odeslat</button> <p>{response}</p> </form> </> ); };
"use strict"; var React = require('react'); ; function Form(_a) { var _b = _a.children, children = _b === void 0 ? null : _b, handleSubmit = _a.handleSubmit; return (<form onSubmit={function (e) { e.preventDefault(); handleSubmit(); }}> {children} </form>); } exports.__esModule = true; exports["default"] = Form;
/** * * Created by yunge on 16/10/28. */ const api = '/api'; const requestPath = (entityType) => { const values = Object.keys(entityTypeConfig).map(key => entityTypeConfig[key].value); if (values.indexOf(entityType) === -1) { throw new Error(`unknown entityType: ${entityType}`); } return `${api}/${entityType}`; }; //{entityType...} const entityTypeConfig = { users: { name: '用户信息表', value: 'user', path: '/users', show: false, }, entry: { name: '分录明细列表', value: 'entrys', path: '/entry', show: true, }, }; export default { entityTypeConfig, requestPath }
const filter = document.querySelector('.filter') const sort = document.querySelector('.sort-box') const box = document.querySelectorAll('.foods > .food-category') let foodWithPrice = [] for (const item of box) { foodWithPrice.push([item.querySelector('.food-name').innerHTML, item.querySelector('.price').innerHTML.split('$').join('')]) } filter.addEventListener('click', () => { if (!sort.classList.contains('active')) { sort.classList.add('active') let btn = sort.querySelectorAll('.btn') btn[0].addEventListener('click', () => { let current_category_index = Array.prototype.slice.call(document.querySelector('.menu-nav > .nav').children).indexOf(document.querySelector('.menu-nav > .nav > .active')); asc(current_category_index) }) btn[1].addEventListener('click', () => { let current_category_index = Array.prototype.slice.call(document.querySelector('.menu-nav > .nav').children).indexOf(document.querySelector('.menu-nav > .nav > .active')); desc(current_category_index) }) } else if (sort.classList.contains('active')) { sort.classList.remove('active') } }) function asc(index) { const len = box[index].querySelectorAll('.food-box').length for (let i = 0; i < len; i++) { let price1 = box[index].querySelectorAll('.price')[i].innerHTML.split('$').join('') for (let j = i; j < len; j++) { let price2 = box[index].querySelectorAll('.price')[j].innerHTML.split('$').join('') if (price1 > price2) { let temp = box[index].querySelectorAll('.food-box')[i].innerHTML box[index].querySelectorAll('.food-box')[i].innerHTML = box[index].querySelectorAll('.food-box')[j].innerHTML box[index].querySelectorAll('.food-box')[j].innerHTML = temp } } } } function desc(index) { const len = box[index].querySelectorAll('.food-box').length for (let i = 0; i < len; i++) { let price1 = box[index].querySelectorAll('.price')[i].innerHTML.split('$').join('') for (let j = i; j < len; j++) { let price2 = box[index].querySelectorAll('.price')[j].innerHTML.split('$').join('') if (price1 < price2) { let temp = box[index].querySelectorAll('.food-box')[i].innerHTML box[index].querySelectorAll('.food-box')[i].innerHTML = box[index].querySelectorAll('.food-box')[j].innerHTML box[index].querySelectorAll('.food-box')[j].innerHTML = temp } } } }
Page({ data: { currentTab: 0 //预定的位置 }, //点击滑动 bindchange: function (e) { let that = this; that.setData({ currentTab: e.detail.current }) }, //点击切换,滑块index赋值 clickTab: function (e) { let that = this; if (that.data.currentTab === e.currentTarget.dataset.current) { return false; } else { that.setData({ currentTab: e.currentTarget.dataset.current }) } } })
module.exports = function (grunt) { // load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), express: { options: {}, web: {options: {script: 'app.js'}} }, watch: { frontend: { options: {livereload: true}, files: [ 'public/*.html', 'public/views/*.html', 'public/styles/*.css', 'public/scripts/*.js', 'public/images/*.{png,jpg,jpeg}' ] }, web: { files: [ '*.js', 'routes/*.js'], tasks: ['express:web'], options: { nospawn: true, atBegin: true, } } }, parallel: { web: { options: {stream: true}, tasks: [ { grunt: true, args: ['watch:frontend'] }, { grunt: true, args: ['watch:web'] } ] } } }); grunt.registerTask('web', ['parallel:web']); grunt.registerTask('default', ['web']); }
var VisualizarRuta = (function () { var sesion = false; var listaPermisos; var Ruta = new Array(); var con = 0; var poly; var markers = new Array(); var poly2; var markers2 = new Array(); var map; var lRutas; var recorridos; var lEsDto; var velocimetro = 'images/bus.png' var time; var _addHandlers = function () { $("#cboRuta").change(function () { clearTimeout(time); clearMarkers(); initializeMap(); puntosCtr(); markers = new Array(); VerInformacionRuta($(this).val()); VerBusesRuta($(this).val()); }); $("#btnCerrarSesion").click(function () { varLocal.removeUser(); varLocal.removeRol(); window.location.href = "index.html"; }); }; var _createElements = function () { TraerRutas(); puntosCtr(); }; var _VerificarPermisos = function () { var user = varLocal.getUser(); var rol = varLocal.getRol(); if ((user != null) && (rol != null) && (rol == 3)) { $("#dvdUser").html('<i class="fa fa-user"></i> ' + user + ' <b class="caret">'); listaPermisos = Permisos.Get(rol); $.each(listaPermisos, function (index, item) { $("#" + item).fadeIn(); }); return true; } else return false; }; var initializeMap = function () { var haightAshbury = new google.maps.LatLng(10.466606, -73.252523); var mapOptions = { zoom: 14, center: haightAshbury, disableDefaultUI: true }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); }; var puntosCtr = function () { //Puntos de control $(function () { DatosBasicosDAO.Get(function (result) { DatosBasicos = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d; markers2 = new Array(); $.each(DatosBasicos.lPctrlDto, function (index, item) { addReloj((new google.maps.LatLng(item.Latitud, item.Longitud)), item.Nombre); }); }); }); }; var addReloj = function (location, title) { var marker = new google.maps.Marker({ position: location, map: map, title: title, icon: 'images/chronometer.png' }); markers2.push(marker); }; var addMarker = function (location, title) { var marker = new google.maps.Marker({ position: location, map: map, icon: velocimetro, title: title }); markers.push(marker); }; var setAllMap = function (map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } }; var clearMarkers = function () { setAllMap(null); }; var showMarkers = function () { setAllMap(map); }; var deleteMarkers = function () { clearMarkers(); markers = []; }; var removeLine = function () { poly.setMap(null); var polyOptions = { strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 2 }; poly = new google.maps.Polyline(polyOptions); poly.setMap(map); }; var setMarkerPosition = function (marker, position) { //alert(marker); marker.setPosition(position); //map.panTo(marker.getPosition()); //alert("cambio"); }; var VerBusesRuta = function (nombreRuta) { HistorialMovimientoDAO.GetCoordTodayBuses(nombreRuta, function (result) { var ban; lHmDto = []; lHmDto = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d; $("#lBuses").empty(); if (lHmDto != null) { $.each(lHmDto, function (index, item) { ban = false; $.each(markers, function (ind, ite) { if (ite.title == item.Vial) { ///cambio ubicación setMarkerPosition(ite, (new google.maps.LatLng(item.Latitud, item.Longitud))); ban = true; return false; } }); if (!ban) { addMarker((new google.maps.LatLng(item.Latitud, item.Longitud)), item.Vial); } //Cargar Buses $("#lBuses").append("<div class='col-md-4 col-centered' style='color:white;text-align:left; '>" + item.Vial + "</div>" + "<div class='col-md-6 col-centered' style='color:white;'>" + item.Velocidad+" Km/h"+ "</div>"); }); } }); time = setTimeout(function () { VerBusesRuta(nombreRuta); }, 5000); }; var TraerRutas = function () { RutasDAO.Gets(function (result) { lRutas = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d; $("#cboRuta").byaCombo({ DataSource: lRutas, placeHolder: 'Seleccione...', Display: "NomRuta", Value: "NomRuta" }); }); }; var VerInformacionRuta = function (NombreRutaActual) { $.each(lRutas, function (index, item) { if (item.NomRuta == NombreRutaActual) { DibujarRutaInfo(item.lCoordenadas); } }); }; var DibujarRutaInfo = function (listaCoordenadas) { initializeMap(); var polyOptions = { strokeColor: "#00A800", strokeOpacity: 1.0, strokeWeight: 2, }; var poly = {}; poly = new google.maps.Polyline(polyOptions); poly.setMap(map); $.each(listaCoordenadas, function (index, item) { var path = poly.getPath(); path.push(new google.maps.LatLng(item.Latitud, item.Longitud)); }); }; var DibujarRecorrido = function (hMDto) { var polyOptions2 = { strokeColor: "#FF3100", strokeOpacity: 1.0, strokeWeight: 2, }; var poly2 = {}; poly2 = new google.maps.Polyline(polyOptions2); poly2.setMap(map); markers = new Array(); $.each(hMDto, function (index, item) { var path = poly2.getPath(); path.push(new google.maps.LatLng(item.Latitud, item.Longitud)); if (parseInt(item.Velocidad) > 62) { addMarker((new google.maps.LatLng(item.Latitud, item.Longitud)), item.Velocidad + "Km/h"); } }); }; return { init: function () { if (_VerificarPermisos()) { _createElements(); _addHandlers(); initializeMap(); } else window.location.href = "index.html"; } }; }()); $(document).ready(function () { VisualizarRuta.init(); });
const parent = document.getElementById('parent') console.log([parent]) const children = document.querySelectorAll('.child') console.log('children', children) const kids = document.getElementsByClassName('child') console.log('kids', kids) const third = document.querySelector('.child:nth-child(3)') console.log(third) // third.remove() console.log('children', children) console.log('kids', kids) for (const child of children) { child.classList.add('grow') } third.classList.remove('grow') third.style.flexGrow = 3 third.href = 'http://google.ca' third.target = '_blank'
var Nano = require('nano'), Promise = require('bluebird'), program = require('commander'), fs = Promise.promisifyAll(require('fs')); program .version('0.0.1') .usage('[options] <file> <database>') .option('-U, --url <url>', 'Couchdb url eg. http://username:password@domain:port') .option('-F, --force', 'Delete database if it exists') .parse(process.argv); if (program.args.length < 2) { program.help(); } var fileName = program.args[0]; var dbName = program.args[1]; var force = program.force === true; // Grab couchdb username/password from .couch file or --username/--password args var getCouchConfig = function() { return new Promise(function(resolve, reject) { if (program.url) { return resolve({ url: program.url }); } fs.readFileAsync('.couch').then(function(data) { resolve(JSON.parse(data)); }, function(err) { switch (err.code) { case 'ENOENT': reject(Error('.couch config not found')); break; } }); }); }; // Load backup var loadBackup = function(config) { return new Promise(function(resolve, reject) { fs.readFileAsync(fileName).then(function(data) { resolve({ config: config, backup: JSON.parse(data) }); }, function(err) { switch (err.code) { case 'ENOENT': reject(Error(fileName + ' not found')); break; } }); }); }; var verfiyDatabase = function(opts) { return new Promise(function(resolve, reject) { var nano = Nano(opts.config.url); opts.db = nano.use(dbName); var createDatabase = function() { nano.db.create(dbName, function(err, body) { if (err) { return reject(Error('Couldn\'t create database, reason: ' + err.reason)); } return resolve(opts); }); }; nano.db.get(dbName, function(err, body) { if (err) { if (err.statusCode === 404) { return createDatabase(); } reject(Error('Couldn\'t verify database, reason: ' + err.reason)); } else { var empty = body.doc_count === 0 && body.doc_del_count === 0; if (empty) { return resolve(opts); } if (!empty) { if (force) { return nano.db.destroy(dbName, function(err, body) { if (err) { return reject(Error('Couldn\'t destroy database, reason: ' + err.reason)); } createDatabase(); }); } else { return reject(Error('Database exists and is not empty, try using --force to destroy it')); } } } }); }); }; // Restore docs to database var restoreDatabase = function(opts) { return new Promise(function(resolve, reject) { var docs = opts.backup.rows.map(function(row) { var doc = row.doc; delete doc._rev; return doc; }); opts.db.bulk({ docs: docs }, function(err, body) { if (err) { return reject(Error('Failed to restore database, reason: ' + err.reason)); } reject('Succesfully restored database'); }); }); }; // Perform task getCouchConfig() .then(loadBackup) .then(verfiyDatabase) .then(restoreDatabase) .then(function(result) { console.log(result); }) .catch(function(error) { console.error('%s', error); });
import React from 'react'; const defaultProps = { name: true, }; class Droid extends React.Component { renderName() { if (!this.props.name) { return <noscript />; } return ( <p className="text-center"> <span name="droid-name" className="label label-info"> { this.props.droid.name } </span> </p> ); } render() { return ( <li> <img className="img-circle" style={{ width: '80px' }} src={ this.props.droid.avatar } /> <span>{ this.renderName() }</span> </li> ); } } Droid.defaultProps = defaultProps; export default Droid;
import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { fetchBooks } from "../actions/booksActions"; import { Card, CardImg, CardText, CardBody, CardTitle, CardSubtitle, Button } from "reactstrap"; class FetchBooks extends Component { componentWillMount(){ this.props.fetchBooks() } render() { const bookItem = this.props.books.map(book => ( <Card> <CardImg src={book.image} /> <CardBody> <CardTitle>{book.title}</CardTitle> <CardSubtitle>{book.subtitle}</CardSubtitle> <CardText>{book.price}</CardText> <Button>more details</Button> </CardBody> </Card> )); return <div>{bookItem}</div>; } } export default connect(null, {fetchBooks})(FetchBooks);
var num1 var rs = require('readline-sync') num1 = rs.question('Senha de acesso?') if (num1 != 1234){ console.log('Acesso Negado') } else{ console.log('Acesso Liberado') }
/* eslint-disable react/prop-types */ /* eslint-disable no-unused-vars */ import React from 'react'; import styled from 'styled-components'; import Social from './Social'; const AboutStyle = styled.div` text-align:center; `; const AboutAvatar = styled.div` padding: 2em 0 0 0; `; const AboutImage = styled.img` border-radius:100%; width: 160px; height: 160px; border: 2px solid #40E0D0; margin: 0 auto; display: block; box-shadow: 0 0 10px rgb(0,0,0,0.6); `; const AboutName = styled.div` text-align:center; `; const AboutNameH2 = styled.h2` font-family: 'Roboto', sans-serif; font-weight: 400; letter-spacing: 1.2px; margin:.5em 0 0 0; color: #00CED1; `; const AboutOcupation = styled.p` margin: .2em .1em 0; letter-spacing: 1.6px; font-weight: 300; color: #08a4a7; `; const AboutDesc = styled.p` color: #757575; font-size: 1em; font-weight: 300; `; const AboutLocation = styled.p` color: #757575; font-size: 1em; font-weight: 400; `; const About = ({avatar,name,ocupation,desc,address,social}) => ( <AboutStyle> <div className="About-container"> <AboutAvatar> <figure> <AboutImage src={avatar} alt={name}/> </figure> </AboutAvatar> <AboutName> <AboutNameH2>{name}</AboutNameH2> </AboutName> <div className = "About-ocupation"> <AboutOcupation>{ocupation}</AboutOcupation > </div> <div className = "About-desc"> <AboutDesc>{desc}</AboutDesc> </div> <div className = "About-address"> <AboutLocation>{address}</AboutLocation> </div> <div className = "About-social" > <Social social ={social}/> </div> </div> </AboutStyle> ); export default About;
import React, { Component } from 'react'; import Container from 'react-bootstrap/Container'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import AddProductToMenu from '../AddProductToMenu'; import ShowProducts from '../ShowProducts'; import NavBar from '../NavBar'; const INITIAL_STATE = { item: '', price: '', category: '', img: '', menu: [], error: null, }; class Admin extends Component { constructor() { super(); this.state = { menu: [], } } fetchApi = (url, data, meth) => { fetch(url, { method: meth, body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }).then(res => res.json()) .then(response => console.log('aquí la respuesta', JSON.stringify(response))) .catch(error => console.log('Error ', error)); } onSubmit = event => { const { item, category, img } = this.state; const toNumber = Number(this.state.price); const url = 'https://backbq.herokuapp.com/product'; const addProductToDB = { "category": category, "img": img, "price": toNumber, "product": item, }; this.fetchApi(url, addProductToDB, 'POST'); console.log(addProductToDB); event.preventDefault(); } onChange = event => { this.setState({ [event.target.name]: event.target.value }); } componentDidMount() { fetch("https://backbq.herokuapp.com/product") .then(res => res.json()) .then((orderAsJson) => { this.setState({ menu: orderAsJson }, console.log(orderAsJson)) }); } render() { return ( <Container> <Row> <Col> <NavBar /> </Col> </Row> <Row> <Col> {this.state.menu ? <ShowProducts menu={this.state.menu} /> : <ShowProducts />} </Col> <Col> <div className="addproduct-form"> <h3>Add Products</h3> <AddProductToMenu onChange={this.onChange} onSubmit={this.onSubmit} /> </div> </Col> </Row> </Container> ); } } export default Admin;
import React, { useState, useEffect } from "react"; import ChallengeCard from "./challengeCard"; import Tasks from "../challenges.json"; import { Button } from "antd"; import CreateForm from "./createForm"; const List = () => { const [list, setList] = useState(Tasks); const [voteOrder, setVoteOrder] = useState(false); const [dateOrder, setDateOrder] = useState(true); const [visible, setVisible] = React.useState(false); const clonedList = [...list]; useEffect(() => { sortDate(); }, []); const sortDate = () => { dateOrder ? setDateOrder(true) : setDateOrder(true); setVoteOrder(false); const sortByDate = clonedList.sort((a, b) => { var aa = a.createdDt.split("-").reverse().join(), bb = b.createdDt.split("-").reverse().join(); return aa > bb ? -1 : aa < bb ? 1 : 0; }); setList(sortByDate); }; const voteToggle = () => { voteOrder ? setVoteOrder(true) : setVoteOrder(true); setDateOrder(false); const sortByVote = clonedList.sort((a, b) => { if (b.upVotes > a.upVotes) { return 1; } else { return -1; } }); setList(sortByVote); }; const onCreate = (values) => { clonedList.push(values); setList(clonedList); setVisible(false); }; return ( <div> <div style={{ alignContent: "center" }}> <div className="d-flex justify-content-center" style={{ marginLeft: "29vw" }} > <Button onClick={() => { setVisible(true); }} style={{ marginRight: "10px" }} > ADD IDEAS </Button> <div type="button" className={dateOrder ? "fw-bolder" : "fw-light"} onClick={sortDate} style={{ marginTop: "5px", marginLeft: "6px" }} > NEWEST </div> <div type="button" className={voteOrder ? "fw-bolder" : "fw-light"} onClick={voteToggle} style={{ marginTop: "5px", marginLeft: "4px" }} > POPULAR </div> </div> <div style={{ maxHeight: "calc(125vh - 325px)", overflowX: "hidden" }}> {list.map((value, key) => { return <ChallengeCard key={value.id} value={value} />; })} </div> </div> <CreateForm visible={visible} onCreate={onCreate} onCancel={() => { setVisible(false); }} /> </div> ); }; export default List;
import React from 'react' const Input = ({ val, callback, keyVal, placeholder, className, id, validateThis }) => { /** * Handles onChange * @param value * @private */ const _onChange = ({ target: { value } }) => { callback(value, keyVal) } return ( <input type="text" onChange={_onChange} value={val} placeholder={placeholder} className={className} id={id} /> ) } export default Input
$.backstretch(["https://via.placeholder.com/2000X1333//88929f/5a6270C/O https://placeholder.com/", "https://via.placeholder.com/2000X1333//88929f/5a6270C/O https://placeholder.com/", "https://via.placeholder.com/2000X1333//88929f/5a6270C/O https://placeholder.com/"], { duration: 3000, fade: 1000, });
import React from "react" import "./input.css" class Input extends React.Component{ state = {number: 100} handleSubmit = (e) =>{ e.preventDefault() this.props.sendInput(parseInt(this.state.number)) } componentDidMount(){ this.setState({number: parseInt(this.props.placeHolder)}) } render(){ return ( <form onSubmit={this.handleSubmit}> <input className="input" value={this.state.number} onChange={e => this.setState({number: e.target.value})} type="text" /> </form> ) } } export default Input
export function toggle () { return { type: 'TEST_ACTION' } }
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import copy from 'copy-to-clipboard'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import cx from 'classnames'; import { Modal as BSModal, FormGroup, FormControl, InputGroup, Button, } from 'react-bootstrap'; import { faCopy, faInfoCircle } from '@fortawesome/free-solid-svg-icons'; import { toastr } from 'react-redux-toastr'; import { validate2FAToken, disableGoogleAuthenticator, } from '../../actions/authentication'; import C from '../../constants/actions'; // import qrIcon from './qr.png'; import VerifySmsIcon from './verifyPhoneNumber.svg'; import s from './TwoFactorAuthenticationModal.css'; import Modal from '../Modal'; /* eslint-disable css-modules/no-undef-class */ class TwoFactorAuthenticationModal extends React.Component { constructor(props) { super(props); this.state = { showEnterToken: false, }; this.handleInputChange = this.handleInputChange.bind(this); this.enableAuthenticator = this.enableAuthenticator.bind(this); this.validateToken = this.validateToken.bind(this); } handleInputChange(event) { const { target } = event; const { value } = target; const { name } = target; this.setState({ [name]: value, }); } enableAuthenticator() { this.setState({ showEnterToken: true }); } validateToken() { if (!this.state.token) { toastr.error('Validation Error!', 'You are not entered token!'); return; } this.props.validateToken(this.state.token); } render() { return ( <Modal show={this.props.show} onHide={() => { this.setState({ showEnterToken: false }); this.props.showToggle(); }} > <BSModal.Header closeButton /> <BSModal.Body style={{ paddingBottom: 30 }}> {!this.props.isTwoFactorAuthenticationEnable ? ( <div> {this.state.showEnterToken ? ( <div> <p className={s.headerTitle}> Enter the 2-step verification token </p> <div className={s.formContainer}> <br /> <p className={s.description}> Enter the 2-step verification code provided by your authentication app </p> <br /> <div className={s.formInline}> <img alt="enter token icon" src={VerifySmsIcon} /> &nbsp; <FormGroup className={s.customInput} style={{ marginTop: 10, width: '90%' }} controlId="TokenInput" > <FormControl type="text" onChange={this.handleInputChange} name="token" placeholder="Enter token" /> </FormGroup> </div> <br /> <Button style={{ width: '80%' }} onClick={this.validateToken} className={s.customBtn} block > Enable </Button> </div> </div> ) : ( <div> <p className={s.headerTitle}>Setup Authenticator</p> <br /> <div className={s.formContainer}> <div className={cx(s.formInline, s.left)}> <div className={s.circleNum}>1</div> <p className={cx(s.description, s.left)} style={{ margin: 0, width: '80%' }} > Install{' '} <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en_US" // eslint-disable-next-line react/jsx-no-target-blank target="_blank" > Google authenticator </a>{' '} app on yor mobile device if you don’t already have one. </p> </div> <br /> <div className={cx(s.formInline, s.left)}> <div className={s.circleNum}>2</div> <p className={cx(s.description, s.left)} style={{ margin: 0, width: '80%' }} > Scan QR code with authenticator (or tap it in mobile browser) </p> </div> <br /> <div className={cx(s.formInline, s.left)}> <div className={s.circleNum}>3</div> <p className={cx(s.description, s.left)} style={{ margin: 0, width: '80%' }} > Please write down or print a copy of the secret code and put it in a safe place. </p> </div> <div className={cx(s.formInline, s.left)} style={{ marginTop: 20 }} > <img alt="qrcode" height={100} width={100} src={this.props.qrCode} /> <div className={s.formContainer} style={{ marginLeft: '10%' }} > <FormGroup className={s.customInput} controlId="selectCountry" > <p className={cx(s.description, s.left)}> Authenticator Secret Code </p> <InputGroup> <FormControl value={this.props.authenticatorSecret} type="text" name="secret" readOnly /> <InputGroup.Button> <Button onClick={() => { copy(this.props.authenticatorSecret); toastr.info('copied!'); }} style={{ height: 45 }} > <FontAwesomeIcon icon={faCopy} /> </Button> </InputGroup.Button> </InputGroup> </FormGroup> <br /> </div> </div> <div className={cx(s.formInline, s.left)}> <p className={cx(s.description, s.left)} style={{ fontSize: 12, marginTop: 20 }} > <FontAwesomeIcon icon={faInfoCircle} style={{ fontSize: 16 }} /> &nbsp; Once an authenticator app is enabled, all other 2FA methods will not be accepted. </p> </div> <Button style={{ width: '80%' }} onClick={this.enableAuthenticator} className={s.customBtn} block > Enter Token </Button> </div> </div> )} </div> ) : ( <div> <p className={s.headerTitle}>Disable the 2-step verification</p> <div className={s.formContainer}> <br /> <p className={s.description}> Enter the 2-step verification code provided by your <br />{' '} authentication app </p> <br /> <div className={s.formInline}> <img alt="enter token icon" src={VerifySmsIcon} /> &nbsp; <FormGroup className={s.customInput} style={{ marginTop: 10, width: '80%' }} controlId="TokenInput" > <FormControl type="text" onChange={this.handleInputChange} name="disableToken" placeholder="Enter token" /> </FormGroup> </div> <br /> <Button onClick={() => { this.setState({ showEnterToken: false }); this.props.disableAuthenticator(this.state.disableToken); }} style={{ width: '80%' }} className={s.customBtn} block > Disable </Button> </div> </div> )} </BSModal.Body> </Modal> ); } } TwoFactorAuthenticationModal.propTypes = { isTwoFactorAuthenticationEnable: PropTypes.bool, qrCode: PropTypes.string, // eslint-disable-line authenticatorSecret: PropTypes.string.isRequired, disableAuthenticator: PropTypes.func.isRequired, validateToken: PropTypes.func.isRequired, show: PropTypes.bool, showToggle: PropTypes.func, }; TwoFactorAuthenticationModal.defaultProps = { isTwoFactorAuthenticationEnable: false, // qrCode: qrIcon, show: false, showToggle: () => {}, }; const mapState = state => ({ isTwoFactorAuthenticationEnable: state.userInfo.authStatus.twoFAEnabled, qrCode: state.userInfo.authStatus.qrUrl, authenticatorSecret: state.userInfo.authStatus.twoFactorAuthSecret, show: state.showGoogleAuthenticationModal, }); const mapDispatch = dispatch => ({ showToggle() { dispatch({ type: C.TOGGLE_SHOW_GOOGLE_AUTHENTICATION_MODAL }); }, validateToken(token) { dispatch(validate2FAToken(token)); }, disableAuthenticator(token) { dispatch(disableGoogleAuthenticator(token)); }, }); export default connect( mapState, mapDispatch, )(withStyles(s)(TwoFactorAuthenticationModal)); export const WithoutRedux = withStyles(s)(TwoFactorAuthenticationModal);
frappe.require('/assets/css/charts.css'); frappe.require('/assets/js/charts.js').then(() => { window.chart = new frappe.Chart("#my-chart", { 'data': { 'title': 'My Awesome Data Analytics', 'labels': ['Monday', 'Tuesday', 'Wednesday', 'Thursday'], 'datasets': [ { 'name': 'One', 'values': [10.0, 2, 3, 4], }, { 'name': 'Two', 'values': [43.5, 6, 31, 14], } ] }, 'type': 'bar', 'barOptions': { 'stacked': true } }); console.log(chart); });
var express = require('express'); var router = express.Router(); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var session = require('express-session'); var expressValidator = require('express-validator'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var flash = require('connect-flash'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; //var mongo = require('mongodb'); //var mongoose = require('mongoose'); var url = require('url'); var nodemailer = require('nodemailer'); var async = require('async'); var crypto = require('crypto'); var bcrypt = require('bcryptjs'); var PDFDocument = require('pdfkit'); var fs = require('fs'); var PdfTable = require('voilab-pdf-table'); // var xoauth2 = require('xoauth2'); // var nodemailersmtptransport=require('nodemailer-smtp-transport'); //var sleep=require('sleep'); //mongoose.connect('mongodb://localhost/NodeDemo'); //var db = mongoose.connection; var User = require('../models/user'); var Profile = require('../models/profilemodel'); var Award = require('../models/award'); var Graduation = require('../models/graduation'); var Hobby = require('../models/hobby'); var Interest = require('../models/interest'); var Project = require('../models/project'); var Publication = require('../models/publication'); var SSCResult = require('../models/sschscresult'); // var Profiles=[]; // var Awards=[]; // var Garduations=[]; // var Projects=[]; // var Publications=[]; // var SSCResults=[]; function calculate(result) { var cgpa = 0.0; var credit = 0.0; var total = 0.0; for (i = 0; i < result.length; i++) { if (parseFloat(result[i].gradepoint) > 0.0) { var coursecredit = parseFloat(result[i].coursecredit); var gradepoint = parseFloat(result[i].gradepoint); console.log('-------coursecredit----->' + coursecredit); console.log('-------coursecredit----->' + gradepoint); credit = credit + coursecredit; total = total + gradepoint * coursecredit; console.log(credit); console.log(total); } } if (credit > 0) cgpa = total / credit; return cgpa; } /* GET users listing. */ router.get('/', function(req, res, next) { var fullname = req.user.firstname + ' ' + req.user.lastname; res.render('generatecv', { fullname: fullname, photo: req.session.photo }); }); router.post('/', function(req, res, next) { var fullname = req.user.firstname + ' ' + req.user.lastname; var filepath = req.body.filepath; var path = filepath + ''; var l = path.length; if (path[l - 1] != '/') path = filepath + '/'; var query1 = { username: req.user.username }; console.log('inside post generatecvs'); Profile.find(query1, function(err1, profile) { if (err1) throw err1; else { Award.find(query1, function(err2, award) { if (err2) throw err2; else { Graduation.find(query1, function(err3, graduation) { if (err3) throw err3; else { SSCResult.find(query1, function(err4, sschscresult) { if (err4) throw err4; else { Project.find(query1, function(err5, project) { if (err5) throw err5; else { Publication.find(query1, function(err6, publication) { if (err6) throw err6; else { Interest.find(query1, function(err7, interest) { if (err7) throw err7; else { Hobby.find(query1, function(err8, hobby) { if (err8) throw err8; else { var cgpa = calculate(graduation); console.log('your cgpa-------->' + cgpa); console.log(sschscresult); console.log(hobby); console.log(interest); console.log(publication); console.log(project); console.log(award); var nameheader = 19; var localheader = 12; var height = 11; var localdata = 10; var i = 0; var doc = new PDFDocument(); doc.pipe(fs.createWriteStream(path + '' + fullname + '.pdf')); if (profile.length > 0) { var l = fullname.length; doc.fontSize(nameheader); doc.font('Times-Roman') .text('' + profile[0].profilename, { align: 'center' }); doc.fontSize(localdata); doc.font('Times-Roman') .text(' Address: ' + profile[0].temporaryaddress + ' Email: ' + profile[0].email + ' Contact No: ' + profile[0].phonenumber, { align: 'center', }); doc.moveDown(2); doc.fontSize(localheader); doc.font('Times-Roman') .text('Personal Profile', { align: 'left', underline: true }); var overview = profile[0].overview; doc.fontSize(localdata); doc.font('Times-Roman') .text('' + overview, { align: 'left' }); } if (sschscresult.length > 0) { doc.moveDown(1); doc.fontSize(localheader); doc.font('Times-Roman') .text('Education', { align: 'left', underline: true }); doc.fontSize(localdata); for (i = 0; i < sschscresult.length; i++) { if (sschscresult[i].examtype == 'SSC') { doc.font('Times-Roman').text('SSC -' + sschscresult[i].institution + ' -' + sschscresult[i].passedyear + ' GPA:-' + sschscresult[i].gpa, { align: 'left', }); } else if (sschscresult[i].examtype == 'HSC') { doc.font('Times-Roman').text('HSC -' + sschscresult[i].institution + ' -' + sschscresult[i].passedyear + ' GPA:-' + sschscresult[i].gpa, { align: 'left', }); } else if (sschscresult[i].examtype == 'Graduation') { doc.font('Times-Roman').text('Graduation -' + sschscresult[i].institution + ' -' + sschscresult[i].passedyear + ' CGPA:-' + sschscresult[i].gpa, { align: 'left', }); } } } // projects is here ---------------->>> if (project.length > 0) { doc.moveDown(1); doc.fontSize(localheader); doc.font('Times-Roman') .text('Projects', { align: 'left', underline: true }); doc.fontSize(localdata); // doc.font('Times-Roman').text(' Project Title ', { // align: 'left', // continued:true // }); // doc.moveDown(1); // doc.font('Times-Roman').text(' Project Title ', { // align: 'right' // }); doc.moveDown(1); for (i = 0; i < project.length; i++) { doc.font('Times-Roman').text('' + project[i].projecttitle, { align: 'left', continued: true }); doc.moveDown(1); doc.font('Times-Roman').text(' -' + project[i].projectdetails, { align: 'right' }); doc.moveDown(1); } } if (publication.length > 0) { doc.moveDown(1); doc.fontSize(localheader); doc.font('Times-Roman') .text('Publications', { align: 'left', underline: true }); doc.fontSize(localdata); doc.moveDown(1); for (i = 0; i < publication.length; i++) { doc.fontSize(localheader); doc.font('Times-Roman').text('' + publication[i].publicationtitle, { align: 'left', continued: true }); doc.moveDown(1); doc.fontSize(localdata); doc.font('Times-Roman').text(publication[i].publicationplace + '--' + publication[i].publicationshort + '--' + publication[i].publicationurl, { align: 'right' }); doc.moveDown(1); } } if (award.length > 0) { doc.moveDown(1); doc.fontSize(localheader); doc.font('Times-Roman') .text('Awards', { align: 'left', underline: true }); doc.fontSize(localdata); doc.moveDown(1); for (i = 0; i < award.length; i++) { doc.fontSize(localdata); doc.font('Times-Roman').text('' + award[i].awardtitle, { align: 'left', continued: true }); doc.moveDown(1); doc.fontSize(localdata); doc.font('Times-Roman').text('--' + award[i].awarddetails, { align: 'right' }); doc.moveDown(1); } } if (interest.length > 0) { doc.moveDown(1); doc.fontSize(localheader); doc.font('Times-Roman') .text('Interests', { align: 'left', underline: true }); doc.fontSize(localdata); doc.moveDown(1); for (i = 0; i < interest.length; i++) { doc.fontSize(localheader); doc.font('Times-Roman').text('' + interest[i].interestabout, { align: 'left', continued: true }); doc.moveDown(1); doc.fontSize(localdata); doc.font('Times-Roman').text('--' + interest[i].interestshortails + '--' + interest[i].interesturl, { align: 'right' }); doc.moveDown(1); } } doc.end(); } }); } }); } }); } }); } }); } }); } }); } }); console.log('before pipe'); console.log('-----------> pdf created'); req.flash('success_msg', 'Your CV is created on ' + path); res.redirect('/generatecvs'); }); module.exports = router;
'use strict'; describe('Airport', function(){ var airport; var plane; beforeEach(function(){ airport = new Airport(); plane = jasmine.createSpyObj('plane',['land']); }); it('has no planes by default', function(){ expect(airport.hangar).toEqual([]); }); it('can clear planes for landing', function(){ airport.clearForLanding(plane); expect(airport.hangar).toEqual([plane]); }); it('can clear plane for takeoff', function(){ plane.land(airport) airport.clearForTakeOff(); expect(airport.hangar).toEqual([]) }) it('returns a type of weather' , function(){ expect(airport.isStormy()).toEqual(false) }); it('prevent takeoff when stormy', function() { spyOn(airport, 'isStormy').and.returnValue(true) expect(function(){ airport.clearForTakeOff(plane)}).toThrow('cannot takeoff') }) it('prevents landing when stormy', function(){ spyOn(airport, 'isStormy').and.returnValue(true) expect(function(){ airport.clearForLanding(plane)}).toThrow('cannot land') }) it('prevents landing when full', function(){ airport.clearForLanding(plane) console.log(airport) expect(function(){ airport.clearForLanding(plane)}).toThrow('cannot land') }); it('has a default capacity if nothing passed in', function(){ airport = new Airport() expect(airport.capacity).toEqual(1) }) it('has default capacity of value passed in', function(){ airport = new Airport(5) expect(airport.capacity).toEqual(5) // }) });
import React from 'react'; import { View, ActivityIndicator, FlatList, Linking, TouchableHighlight } from 'react-native'; import { Text, Card } from 'react-native-elements'; const axios = require('axios'); const DIAGNOSIS = { Burn: { text: "Hold the burn under cool running water for several minutes. Cover the burn with a sterile, non-stick bandage. Give the victim an aspirin or pain reliever. Soothe the area with a burn cream. Do not put cloth directly on the wound. Do not break blisters or try to remove clothing stuck to the burn.", links: [ "https://www.beprepared.com/blog/8866/first-aid-for-burns/", "https://www.redcross.org/take-a-class/cpr/performing-cpr/cpr-steps" ], }, Laceration: { text: "Apply direct pressure on the area. Remove any clothing or debris on the wound. Don't remove large or deeply embedded objects. First stop the bleeding with firm pressure, not on sensitive areas like eyes. Clean the area with warm water and gentle soap and/or apply antibiotic ointment, then put a sterile bandage on the area and apply more as necessary. Be especially aware of deep puncture wounds or bites (animals or human).", links: [ "https://www.mayoclinic.org/first-aid/first-aid-severe-bleeding/basics/art-20056661", "https://www.webmd.com/first-aid/cuts-or-lacerations-treatment" ], }, Bruise: { text: "Rest the bruised area, if possible. Ice the bruise with an ice pack wrapped in a towel. Leave it in place for 10 to 20 minutes. Repeat several times a day for a day or two as needed. Compress the bruised area if it is swelling, using an elastic bandage. Don't make it too tight. Elevate the injured area.", links: [ "https://www.mayoclinic.org/first-aid/first-aid-bruise/basics/art-20056663", ], }, Rash: { text: "Wash the rash with mild soap but don't scrub. Rinse with warm water. Pat the skin dry, rather than rubbing it. Don't cover the rash. Medicine like Zinc oxide ointment, Calamine lotion or for severe itching, applying hydrocortisone cream, are very effective.", links: [ "https://myhealth.alberta.ca/Health/pages/conditions.aspx?hwid=tw6850", ], }, } export default class DiagnosisScreen extends React.PureComponent { constructor(props) { super(props); this.endpoint = '<put endpoint here>'; this.apiKey = '<put api key here>'; this.state = {}; } componentDidMount() { this.queryServer(); } async queryServer() { // Get response from server let response = await axios.post(this.endpoint, { iam_apikey: this.apiKey, img: this.props.navigation.getParam('img'), }); this.setState({ result: response.data }); } renderDiagnosis(displayResult) { if (displayResult in DIAGNOSIS) { return ( <View> <Card> <Text style={{ fontSize: 20 }}>{DIAGNOSIS[displayResult]['text']}</Text> </Card> <Card> <FlatList data={DIAGNOSIS[displayResult]['links']} renderItem={({ item, index, separators }) => ( <TouchableHighlight onPress={() => Linking.openURL(item)} onShowUnderlay={separators.highlight} onHideUnderlay={separators.unhighlight} style={{ margin: 10 }}> <View style={{ backgroundColor: 'gainsboro' }}> <Text style={{ fontSize: 15, color: 'blue' }}>{item}</Text> </View> </TouchableHighlight> )} /> </Card> </View> ); } else { return ( <View></View> ); } } render() { const receivedResult = !!this.state.result if (!receivedResult) { return ( <ActivityIndicator size="large" color="#0000ff" /> ); } else { let displayResult = "No Problem"; let percentage = ""; if (this.state.result["images"][0]["classifiers"][0]["classes"].length > 0) { displayResult = this.state.result["images"][0]["classifiers"][0]["classes"][0]["class"]; percentage = Math.round(this.state.result["images"][0]["classifiers"][0]["classes"][0]["score"] * 100) + "%"; } return ( <View style={{ margin: 10 }}> <View style={{ display: "flex", flexDirection: "row" }}> <Text h1>{displayResult}</Text> <View style={{ display: "flex", flex: 1 }}></View> <Text h1>{percentage}</Text> </View> {this.renderDiagnosis(displayResult)} </View> ); } } }
$('#retry-btn').mousedown(function(){ $('#retry-btn').css('width', parseFloat($('#retry-btn').css('width')) - 10 + "px"); }); $('#retry-btn').mouseup(function(){ $('#retry-btn').css('width', parseFloat($('#retry-btn').css('width')) + 10 + "px"); //setTimeout(function(){ window.location.href = "game.html"; //}, 200); });
module.exports = function(dummy, anaConfig, req, res, callback) { try { var input = {}; var intentName = req.body.result.metadata.intentName; var appName = req.body.result.parameters.epm_application; if (appName == "" || appName == null) appName = "vision"; switch (true) { case (intentName == "EPM_MDXQuery"): { input.qString = "/HyperionPlanning/rest/11.1.2.4/applications/" + appName + "/dataexport/plantypes/Plan1"; input.method = "POST"; input.body = "mdxQuery=SELECT {[Period].[" + req.body.result.parameters.Period + "]} ON COLUMNS, {[Account].[" + req.body.result.parameters.epm_account + "]} ON ROWS FROM Vision.Plan1 WHERE ([Year].[" + req.body.result.parameters.epm_year + "],[Scenario].[" + req.body.result.parameters.epm_scenario + "],[Version].[" + req.body.result.parameters.epm_version + "],[Entity].[" + "403" + "],[Product].[" + "No Product" + "])"; callback(input); break; } case (intentName == "EPM_Jobs"): { input.qString = "/HyperionPlanning/rest/11.1.2.4/applications/" + appName + "/jobs"; input.method = "POST"; input.body = { "jobType": "CUBE_REFRESH", "jobName": "CubeRefresh" }; callback(input); break; } case (intentName == "EPM_Jobs - custom" || intentName == "EPM_JobStatus"): { var jobId = ""; if (intentName == "EPM_Jobs - custom") { var array = req.body.result.contexts; for (var key in array) { console.log("**************************\narray " + key + " : " + JSON.stringify(array[key])); if (array[key].name == "jobid") { jobId = array[key].parameters["jobid"]; break; } } } else if (intentName == "EPM_JobStatus") { jobId = req.body.result.parameters.jobid; } console.log("jobid : " + jobId); if( jobId != "" && jobId != null){ input.qString = "/HyperionPlanning/rest/11.1.2.4/applications/" + appName + "/jobs/" + jobId; input.method = "GET"; callback(input); }else{ res.json({ speech: "Unble to process your request. Please try again later." }); } break; } } } catch (e) { console.log("Error : " + e); res.json({ speech: "Unble to process your request. Please try again later." }); } }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Auxiliary from '../../hoc/Auxiliary'; import Burger from '../../components/Food/CustomBuild/Burger/Burger'; import BuildController from '../../components/Food/CustomBuild/Burger/BuildController/BuildController'; import Modal from '../../components/UI/Modal/Modal' import OrderSummary from '../../components/Order/OrderSummary' import axios from '../../axios-link'; import Spinner from '../../components/UI/Spinner/Spinner'; import withErrorHandler from '../../hoc/ErrorHandling/withErrorHandler'; import * as reduxActions from '../../store/actions/index'; //Auto picks up index file, when pointing to root. const LIMITS = { lower: 0, upper: 4 } export class BurgerBuilder extends Component { state = { confirmationModalShown: false, loadingOrder: false }; //EXAMPLE ON GETTIN DATA-INITIAL SETUP componentDidMount() { this.props.onInitIngredients(); /* axios.get('/ingredientsTest.json') .then(response => { console.log(response); this.setState({ ingredients: response.data }); }).catch(err => console.log(err.message)); */ } purchaseHandler = () => { if (this.props.isAuth) { this.setState({ confirmationModalShown: true }); } else { this.props.history.push('/auth'); } } confirmationCancelHandler = () => { this.setState({ confirmationModalShown: false }); } confirmationContinueHandler = () => { //Ingredients passes with redux //this.props.history.push('checkout/contact-data', { ingredients: this.props.ings, price: this.state.price }); this.props.onInitPurchase(); this.props.history.push('checkout/contact-data'); } getPrice = () => this.props.price.toFixed(2); render() { const addEnabled = { ...this.props.ings }; const removeEnabled = { ...addEnabled } for (let key in addEnabled) { addEnabled[key] = addEnabled[key] < LIMITS.upper; removeEnabled[key] = removeEnabled[key] > LIMITS.lower; } const modalContent = this.state.loadingOrder ? <Spinner /> : <OrderSummary price={this.getPrice()} cancel={this.confirmationCancelHandler} continue={this.confirmationContinueHandler} items={this.props.ings} />; return ( <Auxiliary> <Modal shown={this.state.confirmationModalShown} modalClose={this.confirmationCancelHandler}> {modalContent} </Modal> <Burger ingredients={this.props.ings} /> <BuildController addIngredient={this.props.onIngredientAdded} removeIngredient={this.props.onIngredientRemoved} addEnabled={addEnabled} removeEnabled={removeEnabled} order={this.purchaseHandler} price={this.getPrice()} isAuth={this.props.isAuth} /> </Auxiliary> ); } } const mapStateToProps = state => { return { ings: state.burgerBuilder.ingredients, price: state.burgerBuilder.price, isAuth: state.auth.token !== null } } const mapDispatchToProps = dispatch => { return { onIngredientAdded: (ingName) => dispatch(reduxActions.addIngredient(ingName)), onIngredientRemoved: (ingName) => { dispatch(reduxActions.removeIngredient(ingName)) }, onInitIngredients: () => dispatch(reduxActions.initIngredients()), onInitPurchase: () => dispatch(reduxActions.purchaseInit()) } } export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(BurgerBuilder, axios));
jest.mock('sequelize'); const Model = require('./02.04-model'); test('It should not throw when passed a model containing an empty list of meetings', () => { const model = new Model(); model.meetings = []; expect(model.isAvailable.bind(model, new Date(Date.now()))).not.toThrow(); }); test('It should not throw when passed a model containing an empty list of meetings', () => { const model = Object.assign(new Model(), { meetings: [] }); expect(model.isAvailable.bind(model, new Date(Date.now()))).not.toThrow(); });
var button = document.getElementById("button"); var expression = new Expression(); var history = { } button.onclick = function() { var clickBut = event.target; var resultValue = 0; if (! (clickBut.nodeName === "SPAN") ) return false; // 将点击按钮显示 var displyContent = document.getElementsByClassName("content")[0]; changeContent(displyContent, clickBut); //获得值 if (/[0-9]/g.test(clickBut.id)){ let i = 0; switch (true){ case expression.poeratorMark.length > i: i++; if (expression.mark == -1){ expression.varl = expression.varl * -1; expression.mark = 1; } expression.varlues.push(expression.varl); expression.varl = ""; expression.varl += clickBut.id; break; case expression.poeratorMark.length == i: expression.varl += clickBut.id; break; } } // 根据按键执行不同功能或设置标记 switch(true){ // 功能键 case clickBut.parentNode.className === "fun": exFunction(clickBut, expression, displyContent); break; // 运算符 case clickBut.parentNode.className === "operator": if(clickBut.id === "mult" || clickBut.id === "division") { expression.priority = 1; } expression.poeratorMark.push(clickBut.id); break; //将浮点数标记为1 case clickBut.id === "point": expression.float = 1; expression.varl += "." break; //将符号标记为-1 case clickBut.id === "negative": expression.mark = -1; break; } /******* 函数定义,测试区 start **********/ /* * 根据点击按钮更改显示内容 * changeContent(target, btn, result); * target :elementObject 需要修改内容的元素节点 * btn :elementObje 要显示的按钮 * result : tring || number 要直接显示的内容 */ function changeContent(target, btn, result) { if ( ! ( result === undefined ) ) { target.innerHTML = result; return; } if ( ! (btn.parentNode.className === "fun" || btn.id === "result" ) ) { target.innerHTML += btn.innerHTML; } else { target.innerHTML += ""; } } // 执行各项功能 function exFunction(elm, expr, target) { switch (true) { //计算,输出结果,并初始化表达式对象 case elm.id === "result": resultValue = compute(expr); changeContent(displyContent, clickBut, resultValue); expression = new Expression(); break; //实现删除一项输入 case elm.id === "delect": break; //实现删除所有 case elm.id === "delect-all": expre = new Expression(); changeContent(target, elm, "") break; } } function compute(expr){ //检查各项标记 //处理浮点数 expression.varlues.push(expression.varl); if (expr.float) { var accuracy = []; var arr = 0 expr.varlues.map(function(val) { accuracy.pop( val.length - val.charAt(".") ); } ); expr.varlues.map(function(val) { val = 10* arr * parseFloat(val); } ); } //处理优先级 if (expr.priority){ var count = [] count.push( expr.varlues.shift() ); for( var i = 0 ; expr.poeratorMark.length > i; i++){ switch(true) { case expr.poeratorMark[i] === "mult": count.push( count.pop() * expr.varlues.shift() ); break; case expr.poeratorMark[i] === "division": var quotient = count.pop() / expr.varlues.shift(); if ( quotient == Infinity || quotient == -Infinity ) return "error: 0"; count.push( quotient ); break; default: count.push( expr.varlues.shift() ); } } expr.varlues = count; } console.log("完成乘除运算", expr.varlues); //将所有数进行加或减运算 var prValue = Number( expr.varlues.shift() ); for(var i = 0 ; expr.poeratorMark.length > i; i++){ var num = 0; switch(true) { case expr.poeratorMark[i] === "add": num = expr.varlues.shift(); prValue += Number(num); break; case expr.poeratorMark[i] === "sub": num = expr.varlues.shift(); prValue -= num; break; default: continue; } } if(expr.float) prValue = prValue / arr * val; return prValue; } /******* 函数定义,测试区 end **********/ } function Expression () { this.varl = ""; //保存正在输入值 this.poeratorMark = []; //运算符位 this.varlues = []; //所有的值 this.mark = 1; //是否是带符号数,1为无符号数,-1为符号数 this.float = 0; //是否是浮点数 this.priority = 0; //优先级 }
(function() { 'use strict'; angular.module('yrzb') // 银行卡、充值、还款等涉及钱的路由 .config(function($stateProvider, $urlRouterProvider) { //Provider方法 function stateProvider(){ var args = Array.prototype.slice.call(arguments); var state = args[0]; var noCtrl = args[1].substring(0,1) === '?'; var url = noCtrl ? args[1].substring(1) : args[1]; $stateProvider.state('app.' + state, { url: url, views: { menuContent: { templateUrl: tplSrc + state.replace(/([A-Z])/g,"-$1").toLowerCase() + '.html', controller: noCtrl ? false : state.substring(0,1).toUpperCase() + state.substring(1) + 'Ctrl' } } }); } var tplSrc = 'templates/money/'; var routMap = { myMoney: '/money/myMoney', myMoneyRecord: '/money/myMoneyRecord', myMoneyRepayment: '/money/myMoneyRepayment', cash: '/money/cash', cashApply: '/money/cashApply', cashSuccess: '/money/CashSuccess' }; for(var r in routMap){ if(routMap.hasOwnProperty(r)){ stateProvider.apply(this, [r, routMap[r]]); } } }); }());
import React from "react"; const Elevliste = () => { return ( <div> <button onClick={() => { window.location.assign("/") }}>Tilbake</button> </div> )}; export default Elevliste;
console.log("hilo"); // eslint-disable-next-line no-undef const $ = jQuery; $(document).ready(function () { const toggleShowDueBack = function (event) { console.log(this); console.log(this.value); const target = $("#status")[0]; console.log(target); console.log(target.value); if (target.value !== "" && target.value !== "Available") { $(".n-due-back-group").css("height", "70px"); // show } else { $(".n-due-back-group").css("height", "0"); // hide } }; toggleShowDueBack(); $("#status").on("input", toggleShowDueBack); });
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.helloWorld = functions.https.onRequest((request, response) => { functions.logger.info("Hello World logs!", {structuredData: true}); response.send("Hello World"); }) exports.helloWorld2 = functions.https.onRequest((request, response) => { functions.logger.info("Hello2 World logs!", {structuredData: true}); functions.logger.info("emulator test2"); response.send("Hello World2"); }) exports.onCreateUser = functions.auth.user().onCreate(async(userRecord, _context) => { var email = userRecord.email ? userRecord.email : "" var photoURL = userRecord.photoURL ? userRecord.photoURL : "" var displayName = userRecord.displayName ? userRecord.displayName : "" var serverTimestamp = admin.firestore.FieldValue.serverTimestamp() functions.logger.info("user created", userRecord); await admin.firestore().collection('members').doc(userRecord.uid).set({ docId: userRecord.uid, uid: userRecord.uid, email: email, displayName: displayName, photoURL: photoURL, departmentId: "9999", createdAt: serverTimestamp, updatedAt: serverTimestamp, }); return; }); //mail送信API const sendgrid = require('@sendgrid/mail') exports.sendMail = functions.https.onRequest(async (request, response) => { functions.logger.info("sendMail start"); const apiKey = functions.config().sendgrid_service.key; const fromEmail = functions.config().sendgrid_service.email; const fromName = functions.config().sendgrid_service.name; sendgrid.setApiKey(apiKey); const msg = { to: "m-hirano@mediaseek.co.jp", from: `${fromName} <${fromEmail}>`, subject: `【${fromName}】問い合わせ受理メール`, text: `XXXX様 問い合わせありがとうございます。担当者が確認して返信したいと思いますので 少々お待ち下さい。 このメールには返信できません。` }; sendgrid.send(msg).then((result )=>{ functions.logger.info("sendMail success"); response.send("sendMail success"); return console.log("Successfully sent message:", result); }) .catch((error)=>{ functions.logger.error("sendMail error"); functions.logger.error(error); response.send("sendMail error"); return console.log("Error sending message:", error); }) //return; }) //webhook-url-in-slack const { IncomingWebhook } = require('@slack/webhook'); exports.webhookslack = functions.https.onRequest(async (request, response) => { functions.logger.info("webhookslack start"); const webhook = new IncomingWebhook(functions.config().slack_service.adminurl); const testId = 'test0001'; const postId = 'post0001'; const commentName = 'masalib'; const array = [ `新しいコメントが届きました!`, `<https://xxxxx.jp/jump?id=${testId}&post=${postId}|こちらから飛ぶ>`, `名前: ${commentName}` ] // slack APIが受け取れるオブジェクトを作成する const data = { text: array.join('\n'), // 配列を`\n`で結合、改行する username: 'FirebaseApp-BOT', icon_emoji: ':ghost:' } await webhook.send(data); response.send("webhookslack success"); return; })
const Registro = (update) =>{ const formulario = $('<div class="cont-form"></div>'); const divLogo1 = $('<div class="logo-form"></div>'); const logo1 = $('<img src="img/logo.png">'); const form = $('<div class="form"></div>'); const divLogo = $('<div class="logo margin-bottom"></div>'); const logo = $('<img src="img/titulo.png">'); const nombre = $('<input id="nombre" class="margin-bottom" type="text" placeholder="Nombre" name="" value="">'); const email = $('<input id="email" class="margin-bottom" type="text" placeholder="Email" name="" value="">'); const jugarEnviar = $('<button id="btn" class="jugar disabled" type="button" name="button">Jugar</button>'); formulario.append(divLogo1, form); form.append(divLogo, nombre, email, jugarEnviar); divLogo.append(logo); divLogo1.append(logo1); //Accedemos a nuestra base de datos mediante la URL de tu app var ref = new Firebase("https://juego-2ede8.firebaseio.com"); //Hacemos referencia a nuestro nodo del sensor Temp var tempRef = ref.child("person"); const validateFields = () => { if((/[0-9a-zA-Z._]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+/.test(email.val())) && (nombre.val().length != 0) ) { jugarEnviar.prop('disabled', false); jugarEnviar.focus(); } else { jugarEnviar.prop('disabled', true); // $("#spanText").attr("css", { backgroundColor: "gray" }); } } nombre.on('keypress', (event) => { const charCode = event.keyCode; if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 32) { return true; } else { return false; } }); nombre.on('keyup', (e) => { validateFields(); }); email.on('keyup', (e) => { validateFields(); if( jugarEnviar.prop('disabled') == 'true') { $("#btn").attr("css",{backgroundColor: "green"} ); } }); $(_ => { if (nombre.val()=="" & email.val()=="") { $('#btn').attr("disabled", true); } }); jugarEnviar.on('click', function(){ if (nombre.val()=="" & email.val()=="") { $('#btn').attr("disabled", true); }else{ $('#btn').attr("disabled", false); } state.page=1; console.log(state.page); const inputnombre = nombre.val(); console.log(inputnombre); const inputemail = email.val(); //Agregamos un dato nuevo en la base de datos // tempRef.push().set({ // //generamos un valor aleatorio // nombre: inputnombre, // //generamos un timestamp // email: inputemail // }); update(); }); return formulario; }; function aparecer (objeto){ objeto.css('display','inline-block'); } function oculto (objeto){ objeto.css('display','none'); } function ubicacion(objeto){ var bodyWidth = document.body.clientWidth var bodyHeight = document.body.clientHeight; const randPosX = Math.floor((Math.random()*(bodyWidth-90))); const randPosY = Math.floor((Math.random()*(bodyHeight-90))); objeto.css('left', randPosX); objeto.css('top', randPosY); } function contador(obj, img1) { var imagenes = ["carro-nube.png", "edificio-nube.png"]; var t = 0; var x = setInterval( function() { t++; if(t==1){ aparecer(obj); obj.children().attr("src", "img/"+imagenes[Math.floor(Math.random() * imagenes.length)]); ubicacion(obj); } if(t==8) { t = 0; }; },70); } const Header = () =>{ const contenedor = $('<div class="contenedor"></div>'); const divImagen = $('<div id="rand_pos" class="rand"></div>'); const imagen = $('<img src="img/carro-nube.png">'); contenedor.append(divImagen); divImagen.append(imagen); // console.log(state.imagen); $(_ => { contador(divImagen, imagen); var cont = 0; $('#rand_pos').click(function() { cont = cont +1; state.puntaje=cont; console.log(cont); }); setTimeout(function(){ const root = $('#root'); root.empty(); root.append(Puntaje()); }, 10000); }); return contenedor; }; const Puntaje = () =>{ const contienePuntaje = $('<div class="puntaje"></div>'); const texto = $('<h1>Puntaje: '+state.puntaje+'</h1>'); contienePuntaje.append(texto); return contienePuntaje; };
import React, { useState, useEffect } from "react"; import List from "./List"; import ListView from "./ListView"; import db from "../firebaseConfig"; import Switch from "@material-ui/core/Switch"; import { Button, Col, Row } from "react-bootstrap"; import "../App.css"; const MainBoard = () => { const [view, setView] = useState(false); const [listName, setListName] = useState(""); const [lists, setLists] = useState([]); //fetches all the lists inside the collection "board" inside the database. const fetchLists = async () => { await db.collection("board").onSnapshot(function (querySnapshot) { setLists( querySnapshot.docs.map((list, index) => { return { id: list.id, sortedByName: false, key: index, listName: list.listName, ...list.data(), }; }) ); }); }; useEffect(() => { fetchLists(); }, []); // add a list inside the board when clicked with the name inside the state "listName" const onSubmit = (e) => { e.preventDefault(); db.collection("board").add({ listName, }); setListName(""); }; const onChange = (e) => { e.preventDefault(); setListName(e.target.value); }; const handleChange = () => { setView(!view); }; return ( <div className="mainContainer"> <div style={{ display: 'flex', flexDirection : 'row', justifyContent: 'space-between'}}> <div style={{ margin: '10px'}}> <form onSubmit={onSubmit}> <input type="text" name="List" placeholder="List Name" value={listName} onChange={onChange} />{" "} <Button type="submit">Add List</Button> </form> </div> <div> <span>Board View</span> <Switch checked={view} onChange={handleChange} color="primary" name="board" inputProps={{ "aria-label": "primary checkbox" }} /> <span>List View</span> </div> </div> {!view ? ( <Row> {lists.map((list) => { return ( <Col> <List listName={list.listName} id={list.id} key={list.id} /> </Col> ); })} </Row> ) : ( <div> {lists.map((list) => { return ( <ListView listName={list.listName} id={list.id} key={list.id} /> ); })} </div> )} </div> ); }; export default MainBoard;